repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/theseus-navigator/lib/src
mirrored_repositories/theseus-navigator/lib/src/widgets/navigator_builder.dart
import 'package:flutter/material.dart'; import '../destination.dart'; import '../navigation_controller.dart'; import '../utils/log/log.dart'; /// Builds a navigation widget. /// /// It is used by [NavigationController] to build a navigation widget sub-tree /// around a content of destinations, managed by this navigation controller. /// /// See also: /// - [DefaultNavigatorBuilder] /// - [BottomNavigationBuilder] /// abstract class NavigatorBuilder { /// Creates an instance of [NavigatorBuilder]. /// /// Does not keep upward destination by default. /// const NavigatorBuilder({ KeepingStateInParameters? keepStateInParameters, }) : keepStateInParameters = keepStateInParameters ?? KeepingStateInParameters.auto; /// Automatic persisting of upward destination. /// final KeepingStateInParameters keepStateInParameters; /// Returns a widget that wraps a content of navigator's destinations. /// Widget build(BuildContext context, NavigationController navigator); } /// Implementation of [NavigatorBuilder] that manages a stack of destinations using /// Flutter's [Navigator] widget. /// class DefaultNavigatorBuilder extends NavigatorBuilder { /// Creates an instance of [DefaultNavigatorBuilder]. /// /// Set [NavigatorBuilder.keepStateInParameters] to [KeepingStateInParameters.auto] /// by default to allow persisting navigation stack in the web browser history. /// const DefaultNavigatorBuilder({ KeepingStateInParameters? keepStateInParameters, }) : super(keepStateInParameters: keepStateInParameters); @override Widget build(BuildContext context, NavigationController navigator) { final pages = <_TheseusPage>[]; for (int i = 0; i < navigator.stack.length; i++) { final destination = navigator.stack[i]; pages.add(_TheseusPage( // TODO: Remove reference to 'i' in the key key: ValueKey('${destination.uri}-$i'), destination: destination, )); } return Navigator( key: ValueKey(navigator.tag), pages: pages, onPopPage: (route, result) { Log.d(runtimeType, 'onPopPage()'); navigator.goBack(); route.didPop(result); return true; }, ); } } class _TheseusPage extends Page { const _TheseusPage({ required this.destination, required LocalKey key, }) : super(key: key); final Destination destination; @override Route createRoute(BuildContext context) { switch (destination.settings.transition) { case DestinationTransition.material: return MaterialPageRoute( settings: this, builder: (context) => destination.build(context), ); case DestinationTransition.materialDialog: return DialogRoute( context: context, settings: this, builder: (context) => destination.build(context), ); case DestinationTransition.custom: return PageRouteBuilder( settings: this, pageBuilder: (context, animation, secondaryAnimation) => destination.build(context), transitionsBuilder: destination.settings.transitionBuilder!, ); case DestinationTransition.none: default: return PageRouteBuilder( settings: this, pageBuilder: (context, animation, secondaryAnimation) => destination.build(context), transitionsBuilder: (context, animation, secondaryAnimation, child) => child, ); } } }
0
mirrored_repositories/theseus-navigator/lib/src
mirrored_repositories/theseus-navigator/lib/src/utils/utils.dart
export 'log/log.dart'; export 'platform/platform.dart';
0
mirrored_repositories/theseus-navigator/lib/src/utils
mirrored_repositories/theseus-navigator/lib/src/utils/log/log.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/foundation.dart'; class Log { static int _logLevel = 0; static set logLevel(LogLevel value) => _logLevel = LogLevel.values.indexOf(value); static void d(Object tag, [String? message]) { if (kDebugMode || _logLevel == LogLevel.values.indexOf(LogLevel.d)) { _write(LogLevel.d, tag, message); } } static void e(Object tag, [String? message]) { if (_logLevel <= LogLevel.values.indexOf(LogLevel.e)) { _write(LogLevel.e, tag, message); } } static void w(Object tag, [String? message]) { if (_logLevel <= LogLevel.values.indexOf(LogLevel.w)) { _write(LogLevel.w, tag, message); } } static void i(Object tag, [String? message]) { if (_logLevel <= LogLevel.values.indexOf(LogLevel.i)) { _write(LogLevel.i, tag, message); } } static void _write(LogLevel type, Object tag, String? message) { // ignore: avoid_print print( '''${type.toStringFormatted()}, ${DateTime.now()}, ${_tagToString(tag)}: ${message ?? ""}'''); } static String _tagToString(Object tag) => tag is String ? tag : tag.toString(); } enum LogLevel { d, e, w, i } extension _LogTypeExtension on LogLevel { String toStringFormatted() => '[${toString().split('.').last.toUpperCase()}]'; }
0
mirrored_repositories/theseus-navigator/lib/src/utils
mirrored_repositories/theseus-navigator/lib/src/utils/platform/platform_web.dart
// ignore_for_file: public_member_api_docs import 'platform.dart'; PlatformType get currentPlatform => PlatformType.web;
0
mirrored_repositories/theseus-navigator/lib/src/utils
mirrored_repositories/theseus-navigator/lib/src/utils/platform/platform.dart
// ignore_for_file: public_member_api_docs import 'platform_web.dart' if (dart.library.io) 'platform_io.dart'; abstract class Platform { static bool get isWeb => currentPlatform == PlatformType.web; static bool get isMacOS => currentPlatform == PlatformType.macOS; static bool get isWindows => currentPlatform == PlatformType.windows; static bool get isLinux => currentPlatform == PlatformType.linux; static bool get isAndroid => currentPlatform == PlatformType.android; static bool get isIOS => currentPlatform == PlatformType.iOS; static bool get isFuchsia => currentPlatform == PlatformType.fuchsia; } enum PlatformType { web, windows, linux, macOS, android, fuchsia, iOS }
0
mirrored_repositories/theseus-navigator/lib/src/utils
mirrored_repositories/theseus-navigator/lib/src/utils/platform/platform_io.dart
// ignore_for_file: public_member_api_docs import 'dart:io' as io; import 'platform.dart'; PlatformType get currentPlatform { if (io.Platform.isWindows) return PlatformType.windows; if (io.Platform.isFuchsia) return PlatformType.fuchsia; if (io.Platform.isMacOS) return PlatformType.macOS; if (io.Platform.isLinux) return PlatformType.linux; if (io.Platform.isIOS) return PlatformType.iOS; return PlatformType.android; }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/route_parser_test.dart
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'package:theseus_navigator/src/route_parser.dart'; import 'common/index.dart'; void main() { late NavigationScheme navigationScheme; late NavigationScheme navigationSchemeNoError; late TheseusRouteInformationParser parser; late TheseusRouteInformationParser parserNoError; group('TheseusRouteInformationParser', () { setUp(() { navigationScheme = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.categoriesTyped, TestDestinations.about, ], errorDestination: TestDestinations.error, ); navigationSchemeNoError = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.categoriesTyped, TestDestinations.about, ], ); parser = TheseusRouteInformationParser( navigationScheme: navigationScheme, ); parserNoError = TheseusRouteInformationParser( navigationScheme: navigationSchemeNoError, ); }); test('Parsing supported uri should return a destination', () async { expect( await parser .parseRouteInformation(RouteInformation(uri: Uri.parse('/home'))), TestDestinations.home); }); test('Parsing not supported uri should return an error destination', () async { expect( await parser.parseRouteInformation( RouteInformation(uri: Uri.parse('/home2'))), TestDestinations.error); }); test( 'Throw exception when parsing not supported uri and error destination is not provided', () async { expect( () async => await parserNoError.parseRouteInformation( RouteInformation(uri: Uri.parse('/home2'))), throwsA(isA<UnknownUriException>())); }); test( 'Parsing supported uri which contains wrong parameter values should return an error destination', () async { expect( await parser.parseRouteInformation( RouteInformation(uri: Uri.parse('/categories/10'))), TestDestinations.error); }); test( 'Throw exception when parsing supported uri which contains wrong parameter values, and the error destination is not provided', () async { expect( () async => await parserNoError.parseRouteInformation( RouteInformation(uri: Uri.parse('/categories/10'))), throwsA(isA<UnknownUriException>())); }); test('Restore route information from the destination', () { expect(parser.restoreRouteInformation(TestDestinations.home)?.uri.toString(), '/home'); }); test( 'Do not restore route information for the destination when updating history is disabled in destination settings', () { expect( parser .restoreRouteInformation(TestDestinations.login.withSettings( TestDestinations.login.settings .copyWith(updateHistory: false))) ?.uri.toString(), null); }); }); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/destination_parser_test.dart
import 'package:flutter/foundation.dart' hide Category; import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'common/index.dart'; void main() { const parser = DefaultDestinationParser(); final categoriesParser = CategoriesParser(); group('Destination Parser', () { group('Path parameter', () { test('Segment is path parameter', () { expect(parser.isPathParameter('{id}'), true); expect(parser.isPathParameter('{id'), false); expect(parser.isPathParameter('id}'), false); expect(parser.isPathParameter('id'), false); }); test('Parse parameter name', () { expect(parser.parsePathParameterName('{id}'), 'id'); expect(() => parser.parsePathParameterName(':id'), throwsA(isA<Exception>())); }); }); group('Matching URI', () { test('1 segment path', () { final destination = TestDestinations.home; expect(parser.isMatch('/home', destination), true); expect(parser.isMatch('/home1', destination), false); expect(parser.isMatch('/home/1', destination), false); }); test('2 segments path', () { final destination = TestDestinations.about; expect(parser.isMatch('/settings/about', destination), true); expect(parser.isMatch('/settings/about?q=query', destination), true); expect(parser.isMatch('/settings', destination), false); expect(parser.isMatch('/home/about', destination), false); expect(parser.isMatch('/settings/profile', destination), false); }); test('2 segments path with path parameter', () { final destination = TestDestinations.categories; expect(parser.isMatch('/categories/1', destination), true); expect(parser.isMatch('/categories/2', destination), true); expect(parser.isMatch('/categories', destination), true); expect(parser.isMatch('/categories/1?q=query', destination), true); expect(parser.isMatch('/categories?q=query', destination), true); expect(parser.isMatch('/home/1', destination), false); expect(parser.isMatch('/categories/1/search', destination), false); }); test('4 segments path with 2 path parameters', () { final destination = TestDestinations.categoriesBrands; expect(parser.isMatch('/categories/1/brands/2', destination), true); expect(parser.isMatch('/categories/1/brands', destination), true); expect(parser.isMatch('/categories/1/brands/2?q=query', destination), true); expect( parser.isMatch('/categories/1/brands?q=query', destination), true); expect(parser.isMatch('/categories/1', destination), false); }); }); group('Parsing parameters', () { test('No path parameters', () async { final destination1 = TestDestinations.home; final destination2 = TestDestinations.about; expect( await parser.parseParameters('/home', destination1), destination1); expect(await parser.parseParameters('/settings/about', destination2), destination2); }); test('1 path parameter', () async { final destination1 = TestDestinations.categories; final destination2 = destination1 .withParameters(DestinationParameters(<String, String>{'id': '1'})); expect( await parser.parseParameters('/categories', destination1) == destination1, true); expect( await parser.parseParameters('/categories/1', destination1) == destination2, true); expect( await parser.parseParameters('/categories/2', destination1) == destination2, false); }); test('1 path parameter - Typed parameters', () async { final destination1 = TestDestinations.categoriesTyped; const parentCategory1 = Category(id: 1, name: 'Category 1'); final destination2 = destination1 .withParameters(CategoriesParameters(parent: parentCategory1)); final result1 = await categoriesParser.parseParameters('/categories', destination1); expect(result1 == destination1, true); final result2 = await categoriesParser.parseParameters( '/categories/1', destination1); expect(result2 == destination2, true); expect(result2.parameters is CategoriesParameters, true); expect(result2.parameters!.map.isNotEmpty, true); expect( mapEquals( result2.parameters!.map, <String, String>{'parentId': '1'}), true); final result3 = await categoriesParser.parseParameters( '/categories/2', destination1); expect(result3 == destination2, false); }); test('Query parameters', () async { final destination1 = TestDestinations.categories; final destination2 = destination1.withParameters( DestinationParameters(<String, String>{'q': 'query'})); expect( await parser.parseParameters('/categories?q=query', destination1) == destination2, true); expect( await parser.parseParameters('/categories?q=1', destination1) == destination2, false); }); test('Query parameters - Clear unused for typed parameters', () async { final destination1 = TestDestinations.categoriesTyped; const parentCategory1 = Category(id: 1, name: 'Category 1'); final destination2 = destination1 .withParameters(CategoriesParameters(parent: parentCategory1)); final result = await categoriesParser.parseParameters( '/categories/1?q=query', destination2); expect(result.parameters is CategoriesParameters, true); expect(result.parameters!.map.isNotEmpty, true); expect( mapEquals(result.parameters!.map, <String, String>{ 'parentId': '1', }), true); }); test('Query parameters - Keep reserved parameters - state', () async { final destination1 = TestDestinations.categoriesTyped; const parentCategory1 = Category(id: 1, name: 'Category 1'); final destination2 = destination1 .withParameters(CategoriesParameters(parent: parentCategory1)); final result = await categoriesParser.parseParameters( '/categories/1?state=/settings/about', destination2); expect(result.parameters is CategoriesParameters, true); expect(result.parameters!.map.isNotEmpty, true); expect( mapEquals(result.parameters!.map, <String, String>{ 'parentId': '1', 'state': TestDestinations.about.path }), true); }); test('Exception on not matching destination', () async { final destination1 = TestDestinations.home; expect(() async => await parser.parseParameters('/home1', destination1), throwsA(isA<DestinationNotMatchException>())); }); }); group('Generate destination URI', () { test('No path parameters', () { final destination1 = TestDestinations.home; final destination2 = TestDestinations.about; expect(parser.uri(destination1), '/home'); expect(parser.uri(destination2), '/settings/about'); }); test('1 path parameter with value', () { final destination1 = TestDestinations.categories .withParameters(DestinationParameters(<String, String>{'id': '1'})); final destination2 = destination1.withParameters( DestinationParameters(<String, String>{'q': 'query'})); final destination3 = destination1.withParameters( DestinationParameters(<String, String>{'q': 'query', 'id': '2'})); expect(parser.uri(destination1), '/categories/1'); expect(parser.uri(destination2), '/categories?q=query'); expect(parser.uri(destination3), '/categories/2?q=query'); }); test('2 path parameters with values', () { final destination1 = TestDestinations.categoriesBrands.withParameters( DestinationParameters( <String, String>{'categoryId': '1', 'brandId': '2'})); expect(parser.uri(destination1), '/categories/1/brands/2'); }); test('Query parameters', () { final destination1 = TestDestinations.categories.withParameters( DestinationParameters(<String, String>{'q': 'query'})); final destination2 = destination1.withParameters(DestinationParameters( <String, String>{'q': 'query', 'sort': 'name'})); expect(parser.uri(destination1), '/categories?q=query'); expect(parser.uri(destination2), '/categories?q=query&sort=name'); }); }); }); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/navigation_controller_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'common/index.dart'; void main() { late NavigationController navigator; late NavigationController navigatorCustomInitial; late NavigationController navigatorNotNotify; late NavigationController navigatorAlwaysKeepState; late NavigationController navigatorUpward; group('Navigation Controller', () { setUp(() { navigator = NavigationController( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], ); navigatorCustomInitial = NavigationController( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], initialDestinationIndex: 2, ); navigatorNotNotify = NavigationController( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], notifyOnError: false, ); }); group('Initial destination', () { test('Default initial destination is the first in the list', () { expect(navigator.currentDestination, TestDestinations.home); }); test('Custom initial destination', () { expect( navigatorCustomInitial.currentDestination, TestDestinations.about); }); }); group('Navigation', () { test('Navigate to another destination by "push" method', () async { await navigator.goTo(TestDestinations.catalog); expect(navigator.currentDestination, TestDestinations.catalog); expect(navigator.stack.length, 2); expect(navigator.backFrom, null); }); test('Navigate to another 2 destinations by "push" method', () async { await navigator.goTo(TestDestinations.catalog); await navigator.goTo(TestDestinations.about); expect(navigator.currentDestination, TestDestinations.about); expect(navigator.stack.length, 3); expect(navigator.backFrom, null); }); test('Navigate to another destination by "push" method and return back', () async { await navigator.goTo(TestDestinations.catalog); navigator.goBack(); expect(navigator.currentDestination, TestDestinations.home); expect(navigator.stack.length, 1); expect(navigator.backFrom, TestDestinations.catalog); expect(navigator.shouldClose, false); }); test( 'Navigate to another 2 destinations by "push" method and return back to initial destination', () async { await navigator.goTo(TestDestinations.catalog); await navigator.goTo(TestDestinations.about); navigator.goBack(); navigator.goBack(); expect(navigator.currentDestination, TestDestinations.home); expect(navigator.stack.length, 1); expect(navigator.backFrom, TestDestinations.catalog); expect(navigator.shouldClose, false); }); test('Navigate to another destination by "replace" method', () async { await navigator.goTo(TestDestinations.catalog.withSettings( TestDestinations.catalog.settings .copyWith(transitionMethod: TransitionMethod.replace))); expect(navigator.currentDestination, TestDestinations.catalog); expect(navigator.stack.length, 1); expect(navigator.backFrom, null); }); test('Navigate to the same destination will not change the stack', () async { await navigator.goTo(TestDestinations.home); expect(navigator.currentDestination, TestDestinations.home); expect(navigator.stack.length, 1); expect(navigator.backFrom, null); }); test( 'Navigate back from the last destination in the stack should set close flag', () { navigator.goBack(); expect(navigator.currentDestination, TestDestinations.home); expect(navigator.stack.length, 1); expect(navigator.backFrom, TestDestinations.home); expect(navigator.shouldClose, true); }); }); group('Upward navigation', () { setUp(() { navigatorUpward = NavigationController( destinations: [ TestDestinations.home, TestDestinations.categoriesTyped, TestDestinations.about, ], ); }); test('Missed destinations should be added to the stack', () async { final categories1 = TestDestinations.categoriesTyped.withParameters( CategoriesParameters(parent: categoriesDataSource[0])); final categories2 = TestDestinations.categoriesTyped.withParameters( CategoriesParameters(parent: categoriesDataSource[1])); final categories3 = TestDestinations.categoriesTyped.withParameters( CategoriesParameters(parent: categoriesDataSource[2])); await navigatorUpward.goTo(categories3); expect(navigatorUpward.currentDestination, categories3); expect(navigatorUpward.stack.length, 4); expect(navigatorUpward.stack[1], categories1); expect(navigatorUpward.stack[2], categories2); expect(navigatorUpward.backFrom, null); expect(navigatorUpward.shouldClose, false); }); test( 'Upward destinations should not be duplicated, if some of them are already in the stack', () async { final categories1 = TestDestinations.categoriesTyped.withParameters( CategoriesParameters(parent: categoriesDataSource[0])); final categories2 = TestDestinations.categoriesTyped.withParameters( CategoriesParameters(parent: categoriesDataSource[1])); final categories3 = TestDestinations.categoriesTyped.withParameters( CategoriesParameters(parent: categoriesDataSource[2])); await navigatorUpward.goTo(categories1); expect(navigatorUpward.currentDestination, categories1); expect(navigatorUpward.stack.length, 2); await navigatorUpward.goTo(categories3); expect(navigatorUpward.currentDestination, categories3); expect(navigatorUpward.stack.length, 4); expect(navigatorUpward.stack[1], categories1); expect(navigatorUpward.stack[2], categories2); expect(navigatorUpward.backFrom, null); expect(navigatorUpward.shouldClose, false); }); }); group('Error handling', () { test('Navigation to nonexistent destination should set error', () async { await navigator.goTo(TestDestinations.login); expect(navigator.currentDestination, TestDestinations.home); expect(navigator.stack.length, 1); expect(navigator.error != null, true); expect(navigator.error.toString(), 'NavigationControllerError: destination=/login'); }); test( 'Throw exception when navigate to non-existent destination and the navigator is configured to not notify on errors ', () async { expect( () async => await navigatorNotNotify.goTo(TestDestinations.login), throwsA(isA<UnknownDestinationException>())); expect(navigatorNotNotify.currentDestination, TestDestinations.home); expect(navigatorNotNotify.stack.length, 1); // In case of exception the error is not set expect(navigatorNotNotify.error != null, false); }); }); group('Persisting of navigation state in destination parameters', () { setUp(() { navigator = NavigationController( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], ); navigatorAlwaysKeepState = NavigationController( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], builder: const DefaultNavigatorBuilder( keepStateInParameters: KeepingStateInParameters.always), ); }); test('Do not keep navigation state in auto mode on non-web platform', () { expect(navigator.keepStateInParameters, false); }); test('Explicitly keep navigation state', () { expect(navigatorAlwaysKeepState.keepStateInParameters, true); }); }); }); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/destination_test.dart
import 'package:flutter/foundation.dart' hide Category; import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'common/index.dart'; void main() { group('Destination', () { test('Equality', () { final categoryParametersId1 = DestinationParameters(<String, String>{'id': '1'}); final categoryParametersId2 = DestinationParameters(<String, String>{'id': '2'}); final categoryParametersId1Q1 = DestinationParameters(<String, String>{'id': '1', 'q': '1'}); expect(TestDestinations.home == TestDestinations.home, true); expect(TestDestinations.home == TestDestinations.about, false); expect(TestDestinations.categories == TestDestinations.categories, true); expect( TestDestinations.categories.withParameters(categoryParametersId1) == TestDestinations.categories.withParameters(categoryParametersId1), true); expect( TestDestinations.categories.withParameters(categoryParametersId1) == TestDestinations.categories.withParameters(categoryParametersId2), false); expect( TestDestinations.categories.withParameters(categoryParametersId1) == TestDestinations.categories .withParameters(categoryParametersId1Q1), false); expect(TestDestinations.home != TestDestinations.about, true); }); test('Matching URI', () { final destination1 = TestDestinations.categories; final destination2 = destination1 .withParameters(DestinationParameters(<String, String>{'id': '1'})); expect(destination1.isMatch('/categories/1'), true); expect(destination1.isMatch('/categories'), true); expect(destination1.isMatch('/home'), false); expect(destination2.isMatch('/categories/1'), true); }); test('Parsing URI', () async { final destination1 = TestDestinations.categories; final destination2 = destination1 .withParameters(DestinationParameters(<String, String>{'id': '1'})); final destination3 = destination1 .withParameters(DestinationParameters(<String, String>{'id': '2'})); expect(await destination1.parse('/categories/1') == destination2, true); expect(await destination1.parse('/categories/1') == destination3, false); }); test('Parsing URI - typed parameters', () async { final destination1 = TestDestinations.categoriesTyped; const parentCategory1 = Category(id: 1, name: 'Category 1'); const parentCategory2 = Category(id: 2, name: 'Category 2'); final destination2 = destination1 .withParameters(CategoriesParameters(parent: parentCategory1)); final destination3 = destination1 .withParameters(CategoriesParameters(parent: parentCategory2)); final result = await destination1.parse('/categories/1'); expect(result == destination2, true); expect(result.parameters is CategoriesParameters, true); expect(result.parameters!.parent == parentCategory1, true); expect(result == destination3, false); }); test('Applying parameters', () async { final destination1 = TestDestinations.categories; final categoryParametersId1 = DestinationParameters(<String, String>{'id': '1'}); final destination2 = destination1.withParameters(categoryParametersId1); expect(destination2.parameters is CategoriesParameters, false); expect(destination2.parameters!.map.isNotEmpty, true); expect( mapEquals(destination2.parameters!.map, <String, String>{'id': '1'}), true); }); test('Applying parameters - Typed parameters', () async { final destination1 = TestDestinations.categoriesTyped; const parentCategory1 = Category(id: 1, name: 'Category 1'); final destination2 = destination1 .withParameters(CategoriesParameters(parent: parentCategory1)); expect(destination2.parameters is CategoriesParameters, true); expect(destination2.parameters!.map.isNotEmpty, true); expect( mapEquals( destination2.parameters!.map, <String, String>{'parentId': '1'}), true); }); test('Settings to display a dialog', () async { final destination1 = TestDestinations.aboutWithDialogSettings; expect(destination1.settings.transitionMethod, TransitionMethod.push); expect(destination1.settings.transition, DestinationTransition.materialDialog); }); test('Settings without visual effects on transition', () async { final destination1 = TestDestinations.aboutWithQuietSettings; expect(destination1.settings.transitionMethod, TransitionMethod.replace); expect(destination1.settings.transition, DestinationTransition.none); }); }); group('Destination Parameters', () { test('Reserved parameters', () { expect(DestinationParameters.isReservedParameter('id'), false); expect(DestinationParameters.isReservedParameter('state'), true); }); }); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/router_delegate_test.dart
// ignore_for_file: invalid_use_of_protected_member import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'package:theseus_navigator/src/router_delegate.dart'; import 'common/index.dart'; void main() { late NavigationScheme navigationScheme; late TheseusRouterDelegate delegate; late List<String> log; TestWidgetsFlutterBinding.ensureInitialized(); void currentDestinationListener() { log.add(navigationScheme.currentDestination.uri); } group('TheseusRouterDelegate', () { setUp(() { navigationScheme = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.about, TestDestinations.categoriesTyped, ], errorDestination: TestDestinations.error, ); delegate = navigationScheme.routerDelegate; log = <String>[]; navigationScheme.addListener(currentDestinationListener); }); group('Set new route by the platform', () { test('New route is pushed to the app', () async { await delegate.setNewRoutePath(TestDestinations.about); expect(delegate.currentConfiguration, TestDestinations.about); expect(navigationScheme.currentDestination, TestDestinations.about); expect( navigationScheme .findNavigator(navigationScheme.currentDestination) ?.stack .length, 1); }); test( 'New route with custom "upwardDestinationBuilder" is pushed to the app', () async { final destination = TestDestinations.categoriesTyped.withParameters( CategoriesParameters(parent: categoriesDataSource[1])); await delegate.setNewRoutePath(destination); expect(navigationScheme.currentDestination, destination); expect( navigationScheme .findNavigator(navigationScheme.currentDestination) ?.stack .length, 2); }); test( 'Pushing the same route as the current one should not cause notifying router delegate by navigation scheme', () async { // Navigation scheme notifies once on initialization expect(log.length, 0); final destination = TestDestinations.home; await delegate.setNewRoutePath(destination); expect(log.length, 0); expect(navigationScheme.currentDestination, destination); expect( navigationScheme .findNavigator(navigationScheme.currentDestination) ?.stack .length, 1); }); }); group('Pop route', () { test( 'Popping the only route should keep the current destination on non-Android platform', () async { final result = await delegate.popRoute(); expect(result, true); expect(navigationScheme.currentDestination, TestDestinations.home); }); test( 'Popping the current route should set the current destination to previous one', () async { await navigationScheme.goTo(TestDestinations.about); expect(navigationScheme.currentDestination, TestDestinations.about); expect( navigationScheme .findNavigator(navigationScheme.currentDestination) ?.stack .length, 2); final result = await delegate.popRoute(); expect(result, true); expect(navigationScheme.currentDestination, TestDestinations.home); }); }); group('Service', () { test('Stop listen to navigation scheme on dispose', () async { expect(navigationScheme.hasListeners, true); navigationScheme.removeListener(currentDestinationListener); navigationScheme.routerDelegate.dispose(); expect(navigationScheme.hasListeners, false); }); }); }); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/navigation_scheme_test.dart
// ignore_for_file: invalid_use_of_protected_member import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'common/common.dart'; void main() { late NavigationScheme navigationScheme; late NavigationScheme navigationSchemeNoError; TestWidgetsFlutterBinding.ensureInitialized(); group('Navigation Scheme', () { setUp(() { navigationScheme = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], ); }); group('Finding destinations and navigators', () { test('Finding existing destination', () { expect( navigationScheme.findDestination('/home'), TestDestinations.home); expect(navigationScheme.findDestination('/catalog'), TestDestinations.catalog); expect(navigationScheme.findDestination('/categories'), TestDestinations.categories); expect(navigationScheme.findDestination('/categories/1'), TestDestinations.categories); }); test('Finding home destination', () { expect(navigationScheme.findDestination('/'), TestDestinations.home); }); test('Finding nonexistent destination', () { expect(navigationScheme.findDestination('/login'), null); }); test('Finding navigator for existing destination', () { expect(navigationScheme.findNavigator(TestDestinations.home), navigationScheme.rootNavigator); expect(navigationScheme.findNavigator(TestDestinations.catalog), navigationScheme.rootNavigator); expect(navigationScheme.findNavigator(TestDestinations.categories), TestNavigators.catalog); expect( navigationScheme.findNavigator(TestDestinations.categories .withParameters( DestinationParameters(<String, String>{'id': '1'}))), TestNavigators.catalog); }); test('Finding navigator for nonexistent destination', () { expect(navigationScheme.findNavigator(TestDestinations.login), null); }); }); group('General navigation', () { test( 'Initial destination is a one, which has "isHome" parameter set to "true" independent on its position in the destination list', () { expect(navigationScheme.currentDestination, TestDestinations.home); final navigationScheme1 = NavigationScheme( destinations: [ TestDestinations.catalog, TestDestinations.home, TestDestinations.about, ], ); expect(navigationScheme1.currentDestination, TestDestinations.home); }); test('Navigate to another primary destination', () async { await navigationScheme.goTo(TestDestinations.about); expect(navigationScheme.currentDestination, TestDestinations.about); }); test( 'Navigate to transit destination makes the current destination set to first nested destination', () async { await navigationScheme.goTo(TestDestinations.catalog); expect( navigationScheme.currentDestination, TestDestinations.categories); }); test('Navigate to nested destination', () async { await navigationScheme.goTo(TestDestinations.categories); expect( navigationScheme.currentDestination, TestDestinations.categories); }); test('Navigate to another primary destination and return back', () async { await navigationScheme.goTo(TestDestinations.about); navigationScheme.goBack(); expect(navigationScheme.currentDestination, TestDestinations.home); expect(navigationScheme.shouldClose, false); }); test( 'Navigate back when the only destination is in the stack should close the app', () { navigationScheme.goBack(); expect(navigationScheme.shouldClose, true); }); }); group('Redirection', () { setUp(() { navigationScheme = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.aboutRedirectionApplied, TestDestinations.login, ], ); }); test('Home destination can be redirected', () async { final navigationScheme = NavigationScheme( destinations: [ TestDestinations.homeRedirectionApplied, TestDestinations.login, ], ); await Future.delayed(const Duration(seconds: 1)); expect(navigationScheme.currentDestination, TestDestinations.login); }); test( 'Original destination is saved in the settings of redirection destination', () async { await navigationScheme.goTo(TestDestinations.aboutRedirectionApplied); expect(navigationScheme.currentDestination, TestDestinations.login); expect(navigationScheme.currentDestination.settings.redirectedFrom, TestDestinations.aboutRedirectionApplied); expect(navigationScheme.redirectedFrom, TestDestinations.aboutRedirectionApplied); }); test( 'User can navigate back from the redirected destination reached with "push" method, even the validation is still failed', () async { await navigationScheme.goTo(TestDestinations.aboutRedirectionApplied); expect(navigationScheme.currentDestination, TestDestinations.login); await navigationScheme.goBack(); expect(navigationScheme.currentDestination, TestDestinations.aboutRedirectionApplied); }); test( 'User can navigate back from the redirected destination reached with "replace" method, in case the validation is passed', () async { bool isValid = false; final destinationWithRedirection = Destination( path: '/settings/about', builder: TestDestinations.dummyBuilder, redirections: [ Redirection( destination: TestDestinations.login.copyWith( settings: const DestinationSettings.material() .copyWith(transitionMethod: TransitionMethod.replace)), validator: (destination) async => isValid, ), ], ); final navigationScheme = NavigationScheme( destinations: [ TestDestinations.home, destinationWithRedirection, TestDestinations.login, ], ); await Future.delayed(const Duration(seconds: 1)); await navigationScheme.goTo(destinationWithRedirection); expect(navigationScheme.currentDestination, TestDestinations.login); isValid = true; await navigationScheme.goBack(); expect(navigationScheme.currentDestination, destinationWithRedirection); }); }); group('Error handling', () { late NavigationScheme navigationSchemeCustom; setUp(() { navigationScheme = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], errorDestination: TestDestinations.error, ); navigationSchemeNoError = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, ], ); navigationSchemeCustom = NavigationScheme( navigator: NavigationController( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.about, TestDestinations.error, ], ), errorDestination: TestDestinations.error, ); }); test( 'When provided, the error destination is included to the navigation scheme', () { expect( navigationScheme.findDestination('/error'), TestDestinations.error); }); test( 'For custom root navigator, if the error destination is provided, it should be included to the navigation scheme', () { expect(navigationSchemeCustom.findDestination('/error'), TestDestinations.error); }); test( 'Redirect to error destination when navigate to non-existent destination', () async { await navigationScheme.goTo(TestDestinations.login); expect(navigationScheme.currentDestination, TestDestinations.error); }); test('User can navigate back from the error destination', () async { await navigationScheme.goTo(TestDestinations.login); navigationScheme.goBack(); expect(navigationScheme.currentDestination, TestDestinations.home); }); test('Throw an exception if no error destination provided', () async { expect( () async => await navigationSchemeNoError.goTo(TestDestinations.login), throwsA(isA<UnknownDestinationException>())); }); }); group('Persisting of navigation state in destination parameters', () { late NavigationScheme navigationSchemeKeepState; setUp(() { navigationSchemeKeepState = NavigationScheme( navigator: NavigationController( destinations: [ TestDestinations.home, TestDestinations.login, TestDestinations.about, ], builder: const DefaultNavigatorBuilder( keepStateInParameters: KeepingStateInParameters.always), ), ); }); test('Navigation state is not persisted by default on non-web platform', () async { await navigationScheme.goTo(TestDestinations.about); expect(navigationScheme.currentDestination, TestDestinations.about); expect( navigationScheme.currentDestination.parameters?.map .containsKey([DestinationParameters.stateParameterName]) ?? false, false); }); test( 'When enabled, the navigation state should persist in the parameters of requested destination.', () async { final upwardDestination = navigationSchemeKeepState.currentDestination; await navigationSchemeKeepState.goTo(TestDestinations.about); expect( TestDestinations.about .isMatch(navigationSchemeKeepState.currentDestination.uri), true); expect( navigationSchemeKeepState.currentDestination.parameters?.map .containsKey(DestinationParameters.stateParameterName) ?? false, true); final encodedState = navigationSchemeKeepState.currentDestination .parameters?.map[DestinationParameters.stateParameterName] ?? ''; final persistedState = jsonDecode(String.fromCharCodes(base64.decode(encodedState))); expect(persistedState['/'].contains(upwardDestination.path), true); }); test( 'Navigation stack should be restored on navigation to a destination containing navigation state in parameters.', () async { await navigationSchemeKeepState.goTo(TestDestinations.about); final destinationWithState = navigationSchemeKeepState.currentDestination; await navigationSchemeKeepState.goTo(TestDestinations.login .withSettings( TestDestinations.login.settings.copyWith(reset: true))); expect(navigationSchemeKeepState.currentDestination.path, TestDestinations.login.path); expect(navigationSchemeKeepState.rootNavigator.stack.length, 1); await navigationSchemeKeepState.goTo(destinationWithState .withSettings(destinationWithState.settings.copyWith(reset: true))); expect( navigationSchemeKeepState.currentDestination, destinationWithState); expect(navigationSchemeKeepState.rootNavigator.stack.length, 2); expect(navigationSchemeKeepState.rootNavigator.stack[0], TestDestinations.home); }); }); group('Service', () { test('Stop listen to navigators on dispose', () async { expect(navigationScheme.rootNavigator.hasListeners, true); navigationScheme.dispose(); expect(navigationScheme.rootNavigator.hasListeners, false); }); }); }); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/all_test.dart
import 'destination_test.dart' as destination; import 'destination_parser_test.dart' as destination_parser; import 'navigation_scheme_test.dart' as navigation_scheme; import 'navigation_controller_test.dart' as navigation_controller; import 'redirection_test.dart' as redirection; import 'route_parser_test.dart' as route_parser; import 'router_delegate_test.dart' as router_delegate; import 'widgets/destination_widget_test.dart' as destination_widget; import 'widgets/navigator_builder_test.dart' as navigator_builder_widget; import 'widgets/router_delegate_widget_test.dart' as router_delegate_widget; void main() { destination.main(); destination_parser.main(); navigation_scheme.main(); navigation_controller.main(); redirection.main(); router_delegate.main(); route_parser.main(); destination_widget.main(); navigator_builder_widget.main(); router_delegate_widget.main(); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/test/redirection_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'common/common.dart'; void main() { group('Redirection', () { test('Validation successful', () async { final redirection = Redirection( destination: TestDestinations.login, validator: (destination) async => true, ); expect(await redirection.validate(TestDestinations.home), true); }); test('Validation failed', () async { final redirection = Redirection( destination: TestDestinations.login, validator: (destination) async => false, ); expect(await redirection.validate(TestDestinations.home), false); }); test('No validator function should fail validation', () async { final redirection = Redirection( destination: TestDestinations.login, ); expect(await redirection.validate(TestDestinations.home), false); }); }); }
0
mirrored_repositories/theseus-navigator/test
mirrored_repositories/theseus-navigator/test/widgets/router_delegate_widget_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import '../common/index.dart'; void main() { late NavigationScheme navigationScheme; late NavigationScheme navigationSchemeCustomWaiting; group('TheseusRouterDelegate Widgets', () { setUp(() { navigationScheme = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.aboutRedirectionNotApplied, ], errorDestination: TestDestinations.error, ); navigationSchemeCustomWaiting = NavigationScheme( destinations: [ TestDestinations.home, TestDestinations.catalog, TestDestinations.aboutRedirectionNotApplied, ], errorDestination: TestDestinations.error, waitingOverlayBuilder: (context, destination) => Container( key: const Key('_TheseusCustomWaitingOverlay_'), color: Colors.red, ), ); }); testWidgets('Delegate builds root Navigator', (tester) async { await tester.pumpWidget(_mainWrapper(navigationScheme: navigationScheme)); await tester.pumpAndSettle(); expect(find.byKey(ValueKey(navigationScheme.rootNavigator.tag)), findsOneWidget); }); testWidgets('Show waiting overlay while resolving the destination', (tester) async { const waitingOverlayKey = Key('_TheseusWaitingOverlay_'); await tester.pumpWidget(_mainWrapper(navigationScheme: navigationScheme)); await tester.pumpAndSettle(); expect(find.byKey(ValueKey(navigationScheme.rootNavigator.tag)), findsOneWidget); expect(find.byKey(waitingOverlayKey), findsNothing); navigationScheme.goTo(TestDestinations.aboutRedirectionNotApplied); await tester.pump(const Duration(seconds: 1)); await tester.pump(); expect(find.byKey(waitingOverlayKey), findsOneWidget); await tester.pumpAndSettle(); expect(find.byKey(waitingOverlayKey), findsNothing); }); testWidgets( 'If provided, show custom waiting overlay while resolving the destination', (tester) async { const waitingOverlayKey = Key('_TheseusCustomWaitingOverlay_'); await tester.pumpWidget( _mainWrapper(navigationScheme: navigationSchemeCustomWaiting)); await tester.pumpAndSettle(); expect(find.byKey(ValueKey(navigationSchemeCustomWaiting.rootNavigator.tag)), findsOneWidget); expect(find.byKey(waitingOverlayKey), findsNothing); navigationSchemeCustomWaiting .goTo(TestDestinations.aboutRedirectionNotApplied); await tester.pump(const Duration(seconds: 1)); await tester.pump(); expect(find.byKey(waitingOverlayKey), findsOneWidget); await tester.pump(const Duration(seconds: 5)); await tester.pumpAndSettle(); expect(find.byKey(waitingOverlayKey), findsNothing); }); }); } Widget _mainWrapper({ required NavigationScheme navigationScheme, }) { return MaterialApp.router( routerDelegate: navigationScheme.routerDelegate, routeInformationParser: navigationScheme.routeParser, ); }
0
mirrored_repositories/theseus-navigator/test
mirrored_repositories/theseus-navigator/test/widgets/destination_widget_test.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import '../common/index.dart'; void main() { group('Destination Widgets', () { setUp(() {}); testWidgets('Transit destination builds wrapper widget', (tester) async { await tester.pumpWidget( _destinationWrapper(destination: TestDestinations.catalogTransit)); await tester.pumpAndSettle(); expect(find.text('Catalog'), findsOneWidget); }); testWidgets('Copy of transit destination builds wrapper widget', (tester) async { await tester.pumpWidget(_destinationWrapper( destination: TestDestinations.catalogTransit.withSettings( TestDestinations.catalogTransit.settings .copyWith(transitionMethod: TransitionMethod.replace)))); await tester.pumpAndSettle(); expect(find.text('Catalog'), findsOneWidget); }); }); } Widget _destinationWrapper({ required Destination destination, }) { return MaterialApp( home: Builder( builder: (context) => destination.build(context), ), ); }
0
mirrored_repositories/theseus-navigator/test
mirrored_repositories/theseus-navigator/test/widgets/navigator_builder_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; void main() { group('Default Navigator Builder', () { test('Default keep upward destination mode is "auto"', () { const navigatorBuilder = DefaultNavigatorBuilder(); expect( navigatorBuilder.keepStateInParameters == KeepingStateInParameters.auto, true); }); test('Explicit keep upward destination mode', () { const navigatorBuilder = DefaultNavigatorBuilder( keepStateInParameters: KeepingStateInParameters.always); expect( navigatorBuilder.keepStateInParameters == KeepingStateInParameters.always, true); }); }); }
0
mirrored_repositories/theseus-navigator/test
mirrored_repositories/theseus-navigator/test/common/custom_parameters.dart
import 'package:theseus_navigator/theseus_navigator.dart'; class Category { const Category({ required this.id, required this.name, }); final int id; final String name; } const categoriesDataSource = <Category>[ Category(id: 1, name: 'Category 1'), Category(id: 2, name: 'Category 2'), Category(id: 3, name: 'Category 3'), ]; class CategoriesParameters extends DestinationParameters { CategoriesParameters({ this.parent, }); final Category? parent; } class CategoriesParser extends DestinationParser<CategoriesParameters> { @override Future<CategoriesParameters> parametersFromMap( Map<String, String> map) async { Category? parentCategory; if (map.containsKey('parentId')) { parentCategory = categoriesDataSource.firstWhere( (element) => element.id == int.tryParse(map['parentId'] ?? '')); } return CategoriesParameters(parent: parentCategory); } @override Map<String, String> parametersToMap(CategoriesParameters parameters) { final result = <String, String>{}; if (parameters.parent != null) { result['parentId'] = parameters.parent!.id.toString(); } return result; } }
0
mirrored_repositories/theseus-navigator/test
mirrored_repositories/theseus-navigator/test/common/index.dart
export 'common.dart'; export 'custom_parameters.dart';
0
mirrored_repositories/theseus-navigator/test
mirrored_repositories/theseus-navigator/test/common/common.dart
import 'package:flutter/widgets.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'index.dart'; class TestDestinations { static Widget dummyBuilder<T extends DestinationParameters>( BuildContext context, T? parameters) => Container(); static final home = Destination( path: '/home', builder: dummyBuilder, isHome: true, ); static final homeRedirectionApplied = Destination( path: '/home', builder: dummyBuilder, isHome: true, redirections: [ Redirection( destination: TestDestinations.login, validator: (destination) async => false, ), ], ); static final about = Destination( path: '/settings/about', builder: dummyBuilder, ); static final aboutRedirectionNotApplied = Destination( path: '/settings/about', builder: dummyBuilder, redirections: [ Redirection( destination: TestDestinations.login, validator: (destination) async => Future.delayed(const Duration(seconds: 5), () => true), ), ], ); static final aboutRedirectionApplied = Destination( path: '/settings/about', builder: dummyBuilder, redirections: [ Redirection( destination: TestDestinations.login, validator: (destination) async => false, ), ], ); static final aboutWithDialogSettings = Destination( path: '/settings/about', builder: dummyBuilder, settings: const DestinationSettings.dialog(), ); static final aboutWithQuietSettings = Destination( path: '/settings/about', builder: dummyBuilder, settings: const DestinationSettings.quiet(), ); static final catalog = Destination( path: '/catalog', navigator: TestNavigators.catalog, ); static final catalogTransit = Destination.transit( path: '/catalog', navigator: TestNavigators.catalog, builder: (context, parameters, childBuilder) { return Column( children: [ const Text('Catalog'), Expanded(child: childBuilder(context)), ], ); }, ); static final categories = Destination( path: '/categories/{id}', builder: dummyBuilder, ); static final categoriesTyped = Destination<CategoriesParameters>( path: '/categories/{parentId}', builder: dummyBuilder, parser: CategoriesParser(), upwardDestinationBuilder: (destination) async { final parameters = destination.parameters; if (parameters == null) { return null; } final parent = parameters.parent; if (parent == null || parent.id == 1) { return null; } return destination.withParameters( CategoriesParameters(parent: categoriesDataSource[parent.id - 2])); }, ); static final categoriesBrands = Destination( path: '/categories/{categoryId}/brands/{brandId}', builder: dummyBuilder, ); static final login = Destination( path: '/login', builder: dummyBuilder, ); static final error = Destination( path: '/error', builder: dummyBuilder, ); } class TestNavigators { static final catalog = NavigationController(destinations: [ TestDestinations.categories, TestDestinations.categoriesBrands, ], tag: 'Catalog'); }
0
mirrored_repositories/theseus-navigator/example
mirrored_repositories/theseus-navigator/example/lib/redirection_01.dart
import 'package:flutter/material.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; void main() => runApp(const App()); class Destinations { static final home = Destination( path: '/home', isHome: true, builder: (context, parameters) => const HomeScreen(), ); static final settings = Destination( path: '/settings', builder: (context, parameters) => const SettingsScreen(), redirections: [ Redirection( validator: (destination) async { await Future.delayed(const Duration(seconds: 3)); return isLoggedIn; }, destination: login, ), ], ); static final login = Destination( path: '/login', builder: (context, parameters) => const LoginScreen(), ); } final navigationScheme = NavigationScheme( destinations: [ Destinations.home, Destinations.settings, Destinations.login, ], waitingOverlayBuilder: (context, destination) { return Container( color: Colors.white, child: const Center( child: CircularProgressIndicator(), ), ); }, ); bool isLoggedIn = false; class App extends StatelessWidget { const App({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp.router( routerDelegate: navigationScheme.routerDelegate, routeInformationParser: navigationScheme.routeParser, ); } } class HomeScreen extends StatelessWidget { const HomeScreen({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Home')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () { navigationScheme.goTo(Destinations.settings); }, child: const Text('Settings'), ), ElevatedButton( onPressed: () { navigationScheme.goTo(Destinations.login); }, child: const Text('Login'), ), ], ), ), ); } } class SettingsScreen extends StatelessWidget { const SettingsScreen({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Settings')), body: const Center(child: Text('Settings screen')), ); } } class LoginScreen extends StatelessWidget { const LoginScreen({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( onPressed: () { isLoggedIn = !isLoggedIn; navigationScheme.goBack(); }, child: Text(isLoggedIn ? 'Log Out' : 'Log In'), ), ), ); } }
0
mirrored_repositories/theseus-navigator/example
mirrored_repositories/theseus-navigator/example/lib/tab_bar_navigation_1.dart
import 'package:flutter/material.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; void main() => runApp(const App()); final navigationScheme = NavigationScheme( navigator: NavigationController( destinations: [ Destination( path: '/todo', isHome: true, builder: (context, parameters) => TaskListView( tasks: tasks.where((element) => !element.isCompleted).toList()), tag: 'To do', ), Destination( path: '/completed', builder: (context, parameters) => TaskListView( tasks: tasks.where((element) => element.isCompleted).toList()), tag: 'Completed', ), Destination( path: '/all', builder: (context, parameters) => const TaskListView(tasks: tasks), tag: 'All', ), ], builder: TabsNavigationBuilder( tabs: [ const Tab(child: Text('TO DO'),), const Tab(child: Text('COMPLETED'),), const Tab(child: Text('ALL'),), ], appBarParametersBuilder: (context, destination) => AppBarParameters( title: Text('Tasks - ${destination.tag}'), ), ), ), ); class App extends StatelessWidget { const App({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp.router( routerDelegate: navigationScheme.routerDelegate, routeInformationParser: navigationScheme.routeParser, ); } } class TaskListView extends StatelessWidget { const TaskListView({ Key? key, required this.tasks, }) : super(key: key); final List<Task> tasks; @override Widget build(BuildContext context) { return ListView( children: [ ...tasks.map((element) => TaskListItem(task: element),).toList(), ], ); } } class TaskListItem extends StatelessWidget { const TaskListItem({ Key? key, required this.task, }) : super(key: key); final Task task; @override Widget build(BuildContext context) { return ListTile( title: Text(task.name), ); } } class Task { const Task({ required this.id, required this.name, this.description, this.isCompleted = false, }); final int id; final String name; final String? description; final bool isCompleted; } const tasks = <Task>[ Task(id: 1, name: 'Task 1', description: 'Description of task #1'), Task(id: 2, name: 'Task 2', description: 'Description of task #2', isCompleted: true), Task(id: 3, name: 'Task 3', description: 'Description of task #3', isCompleted: true), Task(id: 4, name: 'Task 4', description: 'Description of task #4'), Task(id: 5, name: 'Task 5', description: 'Description of task #5'), ];
0
mirrored_repositories/theseus-navigator/example
mirrored_repositories/theseus-navigator/example/lib/main.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'navigation.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Theseus Navigator Demo', theme: Theme.of(context).copyWith( dividerColor: Colors.transparent, colorScheme: ColorScheme.fromSwatch().copyWith( primary: Colors.blueGrey, secondary: Colors.amber, // secondaryContainer: Colors.blue, ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( backgroundColor: Colors.amber, ), ), bottomNavigationBarTheme: const BottomNavigationBarThemeData( selectedItemColor: Colors.blue, ), tabBarTheme: const TabBarTheme( labelColor: Colors.blue, unselectedLabelColor: Colors.blueGrey, )), routerConfig: navigationScheme.config, ); } }
0
mirrored_repositories/theseus-navigator/example
mirrored_repositories/theseus-navigator/example/lib/navigation.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'auth/index.dart'; import 'catalog/index.dart'; import 'error/index.dart'; import 'home/index.dart'; import 'settings/index.dart'; final navigationScheme = NavigationScheme( destinations: [ PrimaryDestinations.login, PrimaryDestinations.main, PrimaryDestinations.customTransition, ], errorDestination: PrimaryDestinations.error, ); class PrimaryDestinations { static final login = Destination( path: '/auth', builder: (context, parameters) => const LoginScreen(), ); static final main = Destination( path: '/main', isHome: true, navigator: mainNavigator, ); static final customTransition = Destination( path: '/customTransition', builder: (context, parameters) => const CustomTransitionScreen(), settings: DestinationSettings( transitionMethod: TransitionMethod.push, transition: DestinationTransition.custom, transitionBuilder: (context, animation, secondaryAnimation, child) { const begin = Offset(1.0, 1.0); const end = Offset.zero; const curve = Curves.ease; final tween = Tween(begin: begin, end: end); final curvedAnimation = CurvedAnimation( parent: animation, curve: curve, ); return SlideTransition( position: tween.animate(curvedAnimation), child: child, ); }), ); static final error = Destination( path: '/error', builder: (context, parameters) => const ErrorScreen(), ); } final mainNavigator = NavigationController( destinations: [ MainDestinations.home, MainDestinations.catalog, MainDestinations.settings, ], builder: MainNavigatorBuilder(), tag: 'Main', ); class MainDestinations { static final home = Destination( path: '/home', navigator: homeNavigator, settings: DestinationSettings.quiet(), ); static final catalog = Destination( path: '/catalog', navigator: catalogNavigator, settings: DestinationSettings.quiet(), ); static final settings = Destination( path: '/settings', builder: (context, parameters) => const SettingsScreen(), settings: DestinationSettings.quiet(), redirections: [ Redirections.login, ], ); } class MainNavigatorBuilder extends NavigatorBuilder { @override Widget build(BuildContext context, NavigationController navigator) { return _MainNavigatorWrapper(navigator: navigator); } } class _MainNavigatorWrapper extends StatelessWidget { const _MainNavigatorWrapper({ Key? key, required this.navigator, }) : super(key: key); final NavigationController navigator; static const bottomNavigationBuilder = BottomNavigationBuilder( bottomNavigationItems: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home_rounded), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.list_rounded), label: 'Catalog', ), BottomNavigationBarItem( icon: Icon(Icons.more_horiz_rounded), label: 'Settings', ), ], ); static final bottomNavigationBuilderMaterial3 = BottomNavigationBuilder.navigationBar( navigationBarItems: const <NavigationDestination>[ NavigationDestination( icon: Icon(Icons.home_rounded), label: 'Home', ), NavigationDestination( icon: Icon(Icons.list_rounded), label: 'Catalog', ), NavigationDestination( icon: Icon(Icons.more_horiz_rounded), label: 'Settings', ), ], ); static const drawerNavigationBuilder = DrawerNavigationBuilder( drawerItems: <DrawerItem>[ DrawerItem( leading: Icon(Icons.home_rounded), title: 'Home', ), DrawerItem( leading: Icon(Icons.list_rounded), title: 'Catalog', ), DrawerItem( leading: Icon(Icons.more_horiz_rounded), title: 'Settings', ), ], parameters: DrawerParameters( selectedColor: Colors.blue, )); static const tabsNavigationBuilder = TabsNavigationBuilder( tabs: <Widget>[ Tab( icon: Icon(Icons.home_rounded), child: Text('Home'), ), Tab( icon: Icon(Icons.list_rounded), child: Text('Catalog'), ), Tab( icon: Icon(Icons.more_horiz_rounded), child: Text('Settings'), ), ], wrapInScaffold: true, ); @override Widget build(BuildContext context) { return ValueListenableBuilder<TopLevelNavigationType>( valueListenable: topLevelNavigationType, builder: (context, value, child) { switch (value) { case TopLevelNavigationType.bottom: return bottomNavigationBuilder.build(context, navigator); case TopLevelNavigationType.bottomMaterial3: return bottomNavigationBuilderMaterial3.build(context, navigator); case TopLevelNavigationType.drawer: return drawerNavigationBuilder.build(context, navigator); case TopLevelNavigationType.tabs: return tabsNavigationBuilder.build(context, navigator); } }, ); } } class Redirections { static final login = Redirection( // validator: (destination) => SynchronousFuture(isLoggedIn.value), validator: (destination) => Future.delayed(const Duration(seconds: 3), () => isLoggedIn.value), destination: PrimaryDestinations.login.withSettings( PrimaryDestinations.login.settings.copyWith(updateHistory: false)), ); }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/widgets/info_item.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class InfoItem extends StatelessWidget { const InfoItem({ Key? key, required this.title, required this.description, this.child, this.isAccentStyle = false, this.isCentered = false, this.isDarkStyle = false, this.onTap, }) : super(key: key); final String title; final String description; final Widget? child; final bool isAccentStyle; final bool isCentered; final bool isDarkStyle; final VoidCallback? onTap; @override Widget build(BuildContext context) { final cardColor = isAccentStyle ? Theme.of(context).colorScheme.secondary.withOpacity(0.24) : (isDarkStyle ? Theme.of(context).colorScheme.primary : null); return Padding( padding: const EdgeInsets.only(top: 20.0, left: 16.0, right: 16.0), child: Card( color: cardColor, child: InkWell( onTap: onTap, child: Container( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( title, style: GoogleFonts.robotoMono( fontWeight: FontWeight.bold, color: isAccentStyle ? Theme.of(context).colorScheme.primary : Colors.lightBlueAccent, ), ), Padding( padding: const EdgeInsets.only(top: 20.0), child: Text( description, textAlign: isCentered ? TextAlign.center : null, style: isDarkStyle ? Theme.of(context).textTheme.bodyText1!.copyWith( color: Colors.white, ) : null, ), ), if (child != null) Padding( padding: const EdgeInsets.only(top: 20.0), child: child!, ), ], ), ), ), )); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/auth/index.dart
export 'auth_model.dart'; export 'login_screen.dart';
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/auth/auth_model.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/foundation.dart'; final isLoggedIn = ValueNotifier<bool>(false);
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/auth/login_screen.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import '../widgets/info_item.dart'; import 'auth_model.dart'; import '../navigation.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Login'), ), body: Column( children: [ if (navigationScheme.redirectedFrom != null) const InfoItem( title: 'Redirection', description: '''You are redirected to this screen because of Settings screen requires user to be logged in.''', isDarkStyle: true, ), Expanded( child: Center( child: ValueListenableBuilder<bool>( valueListenable: isLoggedIn, builder: (context, value, child) { return ElevatedButton( onPressed: () { setState(() { isLoggedIn.value = !value; if (isLoggedIn.value) { navigationScheme.goBack(); } }); }, child: Text(value ? 'Log out' : 'Log in'), ); }, ), ), ), ], ), ); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/home/home_navigator.dart
import 'package:theseus_navigator/theseus_navigator.dart'; import 'home_dialog.dart'; import 'home_screen.dart'; final homeNavigator = NavigationController( destinations: [ HomeDestinations.home1, HomeDestinations.home2, HomeDestinations.dialog, ], tag: 'Home', ); class HomeDestinations { static final home1 = Destination( path: '/home1', builder: (context, parameters) => const HomeScreen( title: 'Home 1', next: true, ), ); static final home2 = Destination( path: '/home2', builder: (context, parameters) => const HomeScreen(title: 'Home 2'), upwardDestinationBuilder: (destination) async => home1, ); static final dialog = Destination( path: '/dialog', builder: (context, parameters) => const HomeDialog( title: 'Dialog', message: 'This destination is shown as a dialog.', ), settings: DestinationSettings.dialog(), upwardDestinationBuilder: (Destination<DestinationParameters> destination) async { final from = destination.parameters?.map['from']; if (from == '/home1') { return home1; } else if (from == '/home2') { return home2; } else { return null; } }, ); }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/home/home_dialog.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import '../navigation.dart'; class HomeDialog extends StatelessWidget { const HomeDialog({ Key? key, required this.title, required this.message, }) : super(key: key); final String title; final String message; @override Widget build(BuildContext context) { return AlertDialog( title: Text(title), content: Text(message), actions: [ TextButton( onPressed: () => navigationScheme.goBack(), child: const Text('Close'), ), ], ); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/home/home_screen.dart
// ignore_for_file: public_member_api_docs import 'package:example/home/home_navigator.dart'; import 'package:flutter/material.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; import 'package:url_launcher/url_launcher.dart'; import '../catalog/index.dart'; import '../navigation.dart'; import '../widgets/info_item.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({ Key? key, this.title, this.next = false, }) : super(key: key); final String? title; final bool next; @override Widget build(BuildContext context) { return BackButtonListener( onBackButtonPressed: () async { return false; }, child: WillPopScope( onWillPop: () async { return true; }, child: Scaffold( appBar: AppBar( title: Text(title ?? 'Home'), ), body: ListView( children: [ InfoItem( title: 'Theseus Navigator', description: 'A demo app of Theseus Navigator package.\nversion 0.8.3', isAccentStyle: true, isCentered: true, child: ElevatedButton( onPressed: _openPubDev, child: const Text('Open on PUB.DEV')), ), const InfoItem( title: 'Primary destinations', description: '''This is default destination that is opened on app launch. Other primary destinations in this demo app are accessible by bottom navigation bar. You can also provide your custom navigation builder, like Drawer etc.''', isDarkStyle: true, ), InfoItem( title: 'Deep link', description: '''Opens screen for specific category, deeply in the categories hierarchy. The bottom navigation bar will be switched to the Catalog tab, and the parent category screens will be added to the navigation stack''', child: ElevatedButton( onPressed: () async { navigationScheme .goTo(CatalogDestinations.categories.copyWith( parameters: CategoriesDestinationParameters( parentCategory: await CategoryRepository().getCategory('3')), settings: CatalogDestinations.categories.settings .copyWith(reset: true), )); }, child: const Text('Category 3')), ), InfoItem( title: 'Dialog', description: '''Display a modal dialog''', onTap: () { navigationScheme.goTo(HomeDestinations.dialog.withParameters( DestinationParameters( {'from': navigationScheme.currentDestination.path}))); }, ), InfoItem( title: 'Custom transition animations', description: '''Opens new screen with a custom transition animations''', onTap: () { navigationScheme.goTo(PrimaryDestinations.customTransition); }, ), InfoItem( title: 'Error handling', description: '''When trying to navigate to nonexistent destination, user will be redirected to the error screen if the "errorDestination" is specified.''', child: ElevatedButton( onPressed: () async { navigationScheme.goTo(Destination( path: '/nonexistent', builder: (context, parameters) => const HomeScreen(), )); }, child: const Text('Nonexistent screen')), ), if (next) InfoItem( title: 'Navigate next screen', description: '''Opens another screen in the same bottom navigation tab. New screen will be added to the local navigation stack.''', child: ElevatedButton( onPressed: () async { navigationScheme.goTo(HomeDestinations.home2); }, child: const Text('Home 2')), ), const SizedBox( height: 20.0, ) ], ), ), ), ); } Future<void> _openPubDev() async { if (!await launchUrl( Uri.parse('https://pub.dev/packages/theseus_navigator'))) { throw 'Could not launch url'; } } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/home/custom_transition.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; class CustomTransitionScreen extends StatelessWidget { const CustomTransitionScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Custom Transition'), ), body: Container( color: Theme.of(context).colorScheme.secondary, ), ); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/home/index.dart
export 'home_navigator.dart'; export 'home_screen.dart'; export 'custom_transition.dart';
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/catalog/catalog_navigator.dart
// ignore_for_file: public_member_api_docs import 'package:theseus_navigator/theseus_navigator.dart'; import 'category.dart'; import 'category_list_screen.dart'; import 'category_repository.dart'; final catalogNavigator = NavigationController( destinations: [ CatalogDestinations.categories, ], tag: 'Catalog', ); class CatalogDestinations { static final categories = Destination<CategoriesDestinationParameters>( path: '/categories', builder: (context, parameters) => CategoryListScreen(parentCategory: parameters?.parentCategory), parser: CategoriesDestinationParser(categoryRepository: CategoryRepository()), upwardDestinationBuilder: (destination) async => destination.parameters?.parentCategory == null ? null : destination.withParameters(CategoriesDestinationParameters( parentCategory: destination.parameters?.parentCategory!.parent)), ); } class CategoriesDestinationParameters extends DestinationParameters { CategoriesDestinationParameters({ this.parentCategory, }); final Category? parentCategory; } class CategoriesDestinationParser extends DestinationParser<CategoriesDestinationParameters> { CategoriesDestinationParser({required this.categoryRepository}); final CategoryRepository categoryRepository; @override Future<CategoriesDestinationParameters> parametersFromMap( Map<String, String> map) async { final parentCategoryId = map['parentCategoryId']; if (parentCategoryId == null) { return CategoriesDestinationParameters(); } else { final category = await categoryRepository.getCategory(parentCategoryId); if (category != null) { return CategoriesDestinationParameters( parentCategory: category, ); } else { throw UnknownDestinationException(); } } } @override Map<String, String> parametersToMap(CategoriesDestinationParameters parameters) { final result = <String, String>{}; if (parameters.parentCategory != null) { result['parentCategoryId'] = parameters.parentCategory!.id; } return result; } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/catalog/category_list_screen.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'category.dart'; import 'catalog_navigator.dart'; import 'category_repository.dart'; import '../widgets/info_item.dart'; class CategoryListScreen extends StatefulWidget { const CategoryListScreen({ Key? key, this.parentCategory, }) : super(key: key); final Category? parentCategory; @override _CategoryListScreenState createState() => _CategoryListScreenState(); } class _CategoryListScreenState extends State<CategoryListScreen> { final CategoryRepository categoryRepository = CategoryRepository(); @override void initState() { super.initState(); print('${widget.runtimeType}, initState(): parentCategory=${widget.parentCategory}'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.parentCategory?.name ?? 'Catalog'), ), body: FutureBuilder<List<Category>>( future: categoryRepository.getCategories(parent: widget.parentCategory), builder: (context, snapshot) { if (snapshot.hasData) { return ListView( children: [ const InfoItem( title: 'Nested navigation', description: '''The Catalog screen is managed by its own nested TheseusNavigator. It keeps the navigation state in the catalog, while you are switching to other primary destinations using bottom navigation bar.''', isDarkStyle: true, ), const SizedBox( height: 20.0, ), ...snapshot.data! .map((category) => InkWell( onTap: () { catalogNavigator.goTo(CatalogDestinations .categories .withParameters( CategoriesDestinationParameters( parentCategory: category, ))); }, child: Padding( padding: const EdgeInsets.all(8.0), child: Card( child: Container( height: 100.0, alignment: Alignment.center, child: Text(category.name), ), ), ), )) .toList(), ], ); } return Container(); }), ); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/catalog/category.dart
// ignore_for_file: public_member_api_docs class Category { Category({ required this.id, required this.name, this.parent, }); final String id; final String name; final Category? parent; }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/catalog/index.dart
export 'catalog_navigator.dart'; export 'category.dart'; export 'category_list_screen.dart'; export 'category_repository.dart';
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/catalog/category_repository.dart
// ignore_for_file: public_member_api_docs import 'package:collection/collection.dart'; import 'category.dart'; class CategoryRepository { CategoryRepository() { final category1 = Category(id: '1', name: 'Category 1'); final category2 = Category(id: '2', name: 'Category 2'); final category3 = Category(id: '3', name: 'Category 3', parent: category1); final category4 = Category(id: '4', name: 'Category 4', parent: category1); _categories = <Category>[ category1, category2, category3, category4, ]; } late final List<Category> _categories; Future<Category?> getCategory(String id) async { // await Future.delayed(const Duration(seconds: 3)); return _categories.firstWhereOrNull((category) => category.id == id); } Future<List<Category>> getCategories({Category? parent}) async { return _categories .where((category) => category.parent?.id == parent?.id) .toList(); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/settings/settings_model.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/foundation.dart'; final topLevelNavigationType = ValueNotifier<TopLevelNavigationType>(TopLevelNavigationType.bottomMaterial3); enum TopLevelNavigationType { bottom, bottomMaterial3, drawer, tabs, }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/settings/index.dart
export 'settings_model.dart'; export 'settings_screen.dart';
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/settings/settings_screen.dart
// ignore_for_file: public_member_api_docs import 'package:example/settings/index.dart'; import 'package:flutter/material.dart'; import '../auth/auth_model.dart'; import '../widgets/info_item.dart'; class SettingsScreen extends StatefulWidget { const SettingsScreen({Key? key}) : super(key: key); @override _SettingsScreenState createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> { @override void initState() { super.initState(); print('${widget.runtimeType}, initState():'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Settings'), ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ InfoItem( title: 'Login', description: '', child: ValueListenableBuilder<bool>( valueListenable: isLoggedIn, builder: (context, value, child) { return ElevatedButton( onPressed: () { isLoggedIn.value = !value; }, child: Text(value ? 'Log out' : 'Log in'), ); }, ), ), InfoItem( title: 'Top level navigation', description: '', child: ValueListenableBuilder<TopLevelNavigationType>( valueListenable: topLevelNavigationType, builder: (context, value, child) { return Column( children: [ RadioListTile<TopLevelNavigationType>( title: const Text('Bottom navigation bar'), value: TopLevelNavigationType.bottom, groupValue: value, onChanged: (value) => topLevelNavigationType.value = TopLevelNavigationType.bottom, ), RadioListTile<TopLevelNavigationType>( title: const Text('Bottom navigation bar - Material 3'), value: TopLevelNavigationType.bottomMaterial3, groupValue: value, onChanged: (value) => topLevelNavigationType.value = TopLevelNavigationType.bottomMaterial3, ), RadioListTile<TopLevelNavigationType>( title: const Text('Drawer'), value: TopLevelNavigationType.drawer, groupValue: value, onChanged: (value) => topLevelNavigationType.value = TopLevelNavigationType.drawer, ), RadioListTile<TopLevelNavigationType>( title: const Text('Tab bar'), value: TopLevelNavigationType.tabs, groupValue: value, onChanged: (value) => topLevelNavigationType.value = TopLevelNavigationType.tabs, ), ], ); }, ), ), ], ), ), ); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/cookbook/persisting_upward_destination_01.dart
import 'package:flutter/material.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; void main() => runApp(const App()); final navigationScheme = NavigationScheme( destinations: [ MainDestinations.screen1, MainDestinations.screen2, MainDestinations.screen3, MainDestinations.screen4, MainDestinations.screen5, ], ); class MainDestinations { static final screen1 = Destination( path: '/screen1', isHome: true, builder: (context, parameters) => const Screen1(), ); static final screen2 = Destination( path: '/screen2', builder: (context, parameters) => const Screen2(), ); static final screen3 = Destination( path: '/screen3', builder: (context, parameters) => const Screen3(), ); static final screen4 = Destination( path: '/screen4', builder: (context, parameters) => const Screen4(), ); static final screen5 = Destination( path: '/screen5', builder: (context, parameters) => const Screen5(), upwardDestinationBuilder: (destination) async => screen4, ); } class App extends StatelessWidget { const App({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp.router( routerDelegate: navigationScheme.routerDelegate, routeInformationParser: navigationScheme.routeParser, ); } } class Screen1 extends StatelessWidget { const Screen1({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Screen 1'),), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen2), child: const Text('to Screen 2'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen3), child: const Text('to Screen 3'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen4), child: const Text('to Screen 4'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen5), child: const Text('to Screen 5'), ), ], ), ), ); } } class Screen2 extends StatelessWidget { const Screen2({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Screen 2'),), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen1), child: const Text('to Screen 1'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen3), child: const Text('to Screen 3'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen4), child: const Text('to Screen 4'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen5), child: const Text('to Screen 5'), ), ], ), ), ); } } class Screen3 extends StatelessWidget { const Screen3({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Screen 3'),), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen1), child: const Text('to Screen 1'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen2), child: const Text('to Screen 2'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen4), child: const Text('to Screen 4'), ), ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen5), child: const Text('to Screen 5'), ), ], ), ), ); } } class Screen4 extends StatelessWidget { const Screen4({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Screen 4 - Parent'),), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () => navigationScheme.goTo(MainDestinations.screen5), child: const Text('to Screen 5 (child)'), ), ], ), ), ); } } class Screen5 extends StatelessWidget { const Screen5({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Screen 5 - Child'),), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ], ), ), ); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/cookbook/bottom_navigation_bar_01.dart
import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:theseus_navigator/theseus_navigator.dart'; void main() => runApp(const App()); final navigationScheme = NavigationScheme( navigator: NavigationController( destinations: [ Destination.transit( path: '/tasks/root', isHome: true, navigator: NavigationController( destinations: [ TasksDestinations.taskList, TasksDestinations.taskDetails, ], ), ), Destination( path: '/settings', builder: (context, parameters) => const SettingsScreen(), ), ], builder: BottomNavigationBuilder.navigationBar( navigationBarItems: const [ NavigationDestination( icon: Icon(Icons.list_rounded), label: 'Tasks', ), NavigationDestination( icon: Icon(Icons.more_horiz_rounded), label: 'Settings', ), ], ), ), ); class TasksDestinations { static final taskList = Destination( path: '/tasks', builder: (context, parameters) => const TaskListScreen(), ); static final taskDetails = Destination( path: '/task/{id}', builder: (context, DestinationParameters? parameters) => TaskDetailsScreen(taskId: parameters?.map['id']), upwardDestinationBuilder: (destination) async => taskList, ); } class App extends StatelessWidget { const App({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp.router( routerDelegate: navigationScheme.routerDelegate, routeInformationParser: navigationScheme.routeParser, ); } } class TaskListScreen extends StatelessWidget { const TaskListScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Tasks'), ), body: ListView( children: [ ...tasks .map((e) => ListTile( title: Text(e.name), subtitle: Text(e.id), onTap: () => navigationScheme.goTo(TasksDestinations .taskDetails .withParameters(DestinationParameters({'id': e.id}))), )) .toList() ], ), ); } } class TaskDetailsScreen extends StatelessWidget { const TaskDetailsScreen({ Key? key, required this.taskId, }) : super(key: key); final String? taskId; @override Widget build(BuildContext context) { final task = tasks.firstWhereOrNull( (element) => element.id == taskId, ); return Scaffold( appBar: AppBar( title: const Text('Task details'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text(task?.name ?? ''), Text(task?.id ?? ''), ], ), ), ); } } class SettingsScreen extends StatelessWidget { const SettingsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Settings'), ), body: Center(child: Text(runtimeType.toString())), ); } } const tasks = <Task>[ Task(id: '1', name: 'Task 1'), Task(id: '2', name: 'Task 2'), Task(id: '3', name: 'Task 3'), Task(id: '4', name: 'Task 4'), Task(id: '5', name: 'Task 5'), Task(id: '6', name: 'Task 6'), Task(id: '7', name: 'Task 7'), Task(id: '8', name: 'Task 8'), Task(id: '9', name: 'Task 9'), Task(id: '10', name: 'Task 10'), ]; class Task { const Task({ required this.id, required this.name, }); final String id; final String name; }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/error/error_screen.dart
// ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; class ErrorScreen extends StatelessWidget { const ErrorScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Error'), ), body: const Center( child: Text('An error was happened!'), ), ); } }
0
mirrored_repositories/theseus-navigator/example/lib
mirrored_repositories/theseus-navigator/example/lib/error/index.dart
export 'error_screen.dart';
0
mirrored_repositories/theseus-navigator/example
mirrored_repositories/theseus-navigator/example/test/widget_test.dart
import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Test', (WidgetTester tester) async { }); }
0
mirrored_repositories/openreads
mirrored_repositories/openreads/lib/main.dart
import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:dynamic_color/dynamic_color.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_displaymode/flutter_displaymode.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/constants/locale.dart'; import 'package:openreads/core/helpers/old_android_http_overrides.dart'; import 'package:openreads/logic/bloc/challenge_bloc/challenge_bloc.dart'; import 'package:openreads/logic/bloc/display_bloc/display_bloc.dart'; import 'package:openreads/logic/bloc/migration_v1_to_v2_bloc/migration_v1_to_v2_bloc.dart'; import 'package:openreads/logic/bloc/open_lib_bloc/open_lib_bloc.dart'; import 'package:openreads/logic/bloc/open_library_search_bloc/open_library_search_bloc.dart'; import 'package:openreads/logic/bloc/rating_type_bloc/rating_type_bloc.dart'; import 'package:openreads/logic/bloc/sort_bloc/sort_bloc.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; import 'package:openreads/logic/bloc/welcome_bloc/welcome_bloc.dart'; import 'package:openreads/logic/cubit/book_cubit.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/logic/cubit/default_book_status_cubit.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/resources/connectivity_service.dart'; import 'package:openreads/resources/open_library_service.dart'; import 'package:openreads/ui/books_screen/books_screen.dart'; import 'package:openreads/ui/welcome_screen/welcome_screen.dart'; import 'package:path_provider/path_provider.dart'; late BookCubit bookCubit; late Directory appDocumentsDirectory; late Directory appTempDirectory; late GlobalKey<ScaffoldMessengerState> snackbarKey; late DateFormat dateFormat; void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); _setAndroidConfig(); HydratedBloc.storage = await HydratedStorage.build( storageDirectory: await getApplicationDocumentsDirectory(), ); appDocumentsDirectory = await getApplicationDocumentsDirectory(); appTempDirectory = await getTemporaryDirectory(); snackbarKey = GlobalKey<ScaffoldMessengerState>(); bookCubit = BookCubit(); // TODO: move to app's context final localeCodes = supportedLocales.map((e) => e.locale).toList(); runApp( EasyLocalization( supportedLocales: localeCodes, path: 'assets/translations', fallbackLocale: const Locale('en', 'US'), useFallbackTranslations: true, child: const App(), ), ); } class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MultiRepositoryProvider( providers: [ RepositoryProvider(create: (context) => OpenLibraryService()), RepositoryProvider(create: (context) => ConnectivityService()), ], child: MultiBlocProvider( providers: [ BlocProvider<EditBookCubit>(create: (context) => EditBookCubit()), BlocProvider<EditBookCoverCubit>( create: (context) => EditBookCoverCubit(), ), BlocProvider<CurrentBookCubit>( create: (context) => CurrentBookCubit(), ), BlocProvider<DefaultBooksFormatCubit>( create: (context) => DefaultBooksFormatCubit(), ), BlocProvider<ThemeBloc>(create: (context) => ThemeBloc()), BlocProvider<DisplayBloc>(create: (context) => DisplayBloc()), BlocProvider<SortBloc>(create: (context) => SortBloc()), BlocProvider<WelcomeBloc>(create: (context) => WelcomeBloc()), BlocProvider<ChallengeBloc>(create: (context) => ChallengeBloc()), BlocProvider<RatingTypeBloc>(create: (context) => RatingTypeBloc()), BlocProvider<OpenLibrarySearchBloc>( create: (context) => OpenLibrarySearchBloc()), BlocProvider<MigrationV1ToV2Bloc>( create: (context) => MigrationV1ToV2Bloc()), BlocProvider<OpenLibBloc>( create: (context) => OpenLibBloc( RepositoryProvider.of<OpenLibraryService>(context), RepositoryProvider.of<ConnectivityService>(context), ), ), ], child: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, themeState) { if (themeState is SetThemeState) { return BlocBuilder<WelcomeBloc, WelcomeState>( builder: (_, welcomeState) { return OpenreadsApp( themeState: themeState, welcomeState: welcomeState, ); }, ); } else { return const SizedBox(); } }, ), ), ); } } class OpenreadsApp extends StatefulWidget { const OpenreadsApp({ super.key, required this.themeState, required this.welcomeState, }); final SetThemeState themeState; final WelcomeState welcomeState; @override State<OpenreadsApp> createState() => _OpenreadsAppState(); } class _OpenreadsAppState extends State<OpenreadsApp> with WidgetsBindingObserver { late bool welcomeMode; _decideWelcomeMode(WelcomeState welcomeState) { if (welcomeState is ShowWelcomeState) { welcomeMode = true; } else { welcomeMode = false; } } @override void initState() { super.initState(); _decideWelcomeMode(widget.welcomeState); } @override Widget build(BuildContext context) { _initDateFormat(context); return DynamicColorBuilder( builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) { if (widget.themeState.amoledDark) { darkDynamic = darkDynamic?.copyWith( background: Colors.black, ); } SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); final themeMode = widget.themeState.themeMode; return AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle( statusBarColor: Colors.transparent, systemNavigationBarColor: Colors.transparent, statusBarBrightness: themeMode == ThemeMode.system ? MediaQuery.platformBrightnessOf(context) == Brightness.dark ? Brightness.light : Brightness.dark : themeMode == ThemeMode.dark ? Brightness.light : Brightness.dark, statusBarIconBrightness: themeMode == ThemeMode.system ? MediaQuery.platformBrightnessOf(context) == Brightness.dark ? Brightness.light : Brightness.dark : themeMode == ThemeMode.dark ? Brightness.light : Brightness.dark, systemNavigationBarIconBrightness: themeMode == ThemeMode.system ? MediaQuery.platformBrightnessOf(context) == Brightness.dark ? Brightness.light : Brightness.dark : themeMode == ThemeMode.dark ? Brightness.light : Brightness.dark, ), child: MaterialApp( title: Constants.appName, scaffoldMessengerKey: snackbarKey, theme: ThemeData( useMaterial3: true, colorSchemeSeed: widget.themeState.useMaterialYou ? null : widget.themeState.primaryColor, colorScheme: widget.themeState.useMaterialYou ? lightDynamic : null, brightness: Brightness.light, fontFamily: widget.themeState.fontFamily, ), darkTheme: ThemeData( useMaterial3: true, colorSchemeSeed: widget.themeState.useMaterialYou ? null : widget.themeState.primaryColor, colorScheme: widget.themeState.useMaterialYou ? darkDynamic : null, brightness: Brightness.dark, fontFamily: widget.themeState.fontFamily, scaffoldBackgroundColor: widget.themeState.amoledDark ? Colors.black : null, appBarTheme: widget.themeState.amoledDark ? const AppBarTheme(backgroundColor: Colors.black) : null, ), themeMode: themeMode, home: welcomeMode ? WelcomeScreen(themeData: Theme.of(context)) : const BooksScreen(), localizationsDelegates: context.localizationDelegates, supportedLocales: context.supportedLocales, locale: context.locale, ), ); }); } } _setAndroidConfig() async { if (Platform.isAndroid) { var androidInfo = await DeviceInfoPlugin().androidInfo; var sdkInt = androidInfo.version.sdkInt; if (sdkInt >= 23) { await FlutterDisplayMode.setHighRefreshRate(); } // https://github.com/dart-lang/http/issues/627 if (sdkInt <= 25) { HttpOverrides.global = OldAndroidHttpOverrides(); } } } Future _initDateFormat(BuildContext context) async { await initializeDateFormatting(); // ignore: use_build_context_synchronously dateFormat = DateFormat.yMMMMd(context.locale.toString()); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/database/database_controler.dart
import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/database/database_provider.dart'; import 'package:openreads/model/book.dart'; import 'package:sqflite/sqflite.dart'; class DatabaseController { final dbClient = DatabaseProvider.dbProvider; Future<int> createBook(Book book) async { final db = await dbClient.db; return db.insert("booksTable", book.toJSON()); } Future<List<Book>> getAllNotDeletedBooks({List<String>? columns}) async { final db = await dbClient.db; var result = await db.query( "booksTable", columns: columns, where: 'deleted = 0', ); return result.isNotEmpty ? result.map((item) => Book.fromJSON(item)).toList() : []; } Future<List<Book>> getAllBooks({List<String>? columns}) async { final db = await dbClient.db; var result = await db.query( "booksTable", columns: columns, ); return result.isNotEmpty ? result.map((item) => Book.fromJSON(item)).toList() : []; } Future<List<Book>> getBooks({ List<String>? columns, required int status, }) async { final db = await dbClient.db; var result = await db.query( "booksTable", columns: columns, where: 'status = ? AND deleted = 0', whereArgs: [status], ); return result.isNotEmpty ? result.map((item) => Book.fromJSON(item)).toList() : []; } Future<List<Book>> searchBooks({ List<String>? columns, required String query, }) async { final db = await dbClient.db; var result = await db.query( "booksTable", columns: columns, where: "(title LIKE ? OR subtitle LIKE ? OR author LIKE ?) AND deleted LIKE ?", whereArgs: [ '%$query%', '%$query%', '%$query%', '0', ], ); return result.isNotEmpty ? result.map((item) => Book.fromJSON(item)).toList() : []; } Future<int> countBooks({ List<String>? columns, required int status, }) async { final db = await dbClient.db; final count = Sqflite.firstIntValue(await db.rawQuery( 'SELECT COUNT(*) FROM booksTable WHERE status = $status AND deleted = 0', )); return count ?? 0; } Future<int> updateBook(Book book) async { final db = await dbClient.db; return await db.update("booksTable", book.toJSON(), where: "id = ?", whereArgs: [book.id]); } Future<int> deleteBook(int id) async { final db = await dbClient.db; return await db.delete("booksTable", where: 'id = ?', whereArgs: [id]); } Future<Book?> getBook(int id) async { final db = await dbClient.db; var result = await db.query( "booksTable", limit: 1, where: 'id = ?', whereArgs: [id], ); return result.isNotEmpty ? result.map((item) => Book.fromJSON(item)).toList()[0] : null; } Future<List<Book>> getDeletedBooks() async { final db = await dbClient.db; var result = await db.query( "booksTable", where: 'deleted = 1', ); return result.isNotEmpty ? result.map((item) => Book.fromJSON(item)).toList() : []; } Future<int> removeAllBooks() async { final db = await dbClient.db; return await db.delete("booksTable"); } Future<List<Object?>> bulkUpdateBookFormat( Set<int> ids, BookFormat bookFormat, ) async { final db = await dbClient.db; var batch = db.batch(); String bookFormatString = bookFormat == BookFormat.audiobook ? 'audiobook' : bookFormat == BookFormat.ebook ? 'ebook' : bookFormat == BookFormat.paperback ? 'paperback' : bookFormat == BookFormat.hardcover ? 'hardcover' : 'paperback'; for (int id in ids) { batch.update("booksTable", {"book_type": bookFormatString}, where: "id = ?", whereArgs: [id]); } return await batch.commit(); } Future<List<Object?>> bulkUpdateBookAuthor( Set<int> ids, String author, ) async { final db = await dbClient.db; var batch = db.batch(); for (int id in ids) { batch.update("booksTable", {"author": author}, where: "id = ?", whereArgs: [id]); } return await batch.commit(); } Future<List<Book>> getBooksWithSameTag(String tag) async { final db = await dbClient.db; var result = await db.query( "booksTable", where: 'tags IS NOT NULL AND deleted = 0', orderBy: 'publication_year ASC', ); final booksWithTag = List<Book>.empty(growable: true); if (result.isNotEmpty) { final books = result.map((item) => Book.fromJSON(item)).toList(); for (final book in books) { if (book.tags != null && book.tags!.isNotEmpty) { for (final bookTag in book.tags!.split('|||||')) { if (bookTag == tag) { booksWithTag.add(book); } } } } } return booksWithTag; } Future<List<Book>> getBooksWithSameAuthor(String author) async { final db = await dbClient.db; var result = await db.query( "booksTable", where: 'author = ? AND deleted = 0', whereArgs: [author], orderBy: 'publication_year ASC', ); return result.isNotEmpty ? result.map((item) => Book.fromJSON(item)).toList() : []; } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/database/database_provider.dart
import 'dart:io'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; import 'package:sqflite/sqflite.dart'; // Instruction how to add a new database field: // 1. Add new parameters to the Book class in book.dart // 2. Increase version number in the createDatabase method below // 3. Add new fields to the booksTable in the onCreate argument below // 4. Add a new case to the onUpgrade argument below // 5. Add a new list of migration scripts to the migrationScriptsVx // 6. Add a new method _updateBookDatabaseVytoVx // 7. Update existing methods with new migration scripts // 7. Update existing methods names with new version number class DatabaseProvider { static final DatabaseProvider dbProvider = DatabaseProvider(); late final Future<Database> db = createDatabase(); Future<Database> createDatabase() async { Directory docDirectory = await getApplicationDocumentsDirectory(); String path = join( docDirectory.path, "Books.db", ); return await openDatabase( path, version: 8, onCreate: (Database db, int version) async { await db.execute("CREATE TABLE booksTable (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "title TEXT, " "subtitle TEXT, " "author TEXT, " "description TEXT, " "book_type TEXT, " "status INTEGER, " "rating INTEGER, " "favourite INTEGER, " "deleted INTEGER, " "start_date TEXT, " "finish_date TEXT, " "pages INTEGER, " "publication_year INTEGER, " "isbn TEXT, " "olid TEXT, " "tags TEXT, " "my_review TEXT, " "notes TEXT, " "has_cover INTEGER, " "blur_hash TEXT, " "readings TEXT, " "date_added TEXT, " "date_modified TEXT " ")"); }, onUpgrade: (Database db, int oldVersion, int newVersion) async { if (newVersion > oldVersion) { var batch = db.batch(); switch (oldVersion) { case 1: _updateBookDatabaseV1toV8(batch); break; case 2: _updateBookDatabaseV2toV8(batch); break; case 3: _updateBookDatabaseV3toV8(batch); break; case 4: _updateBookDatabaseV4toV8(batch); break; case 5: _updateBookDatabaseV5toV8(batch); break; case 6: _updateBookDatabaseV6toV8(batch); break; case 7: _updateBookDatabaseV7toV8(batch); break; } await batch.commit(); } }, ); } void _executeBatch(Batch batch, List<String> scripts) { for (var script in scripts) { batch.execute(script); } } final migrationScriptsV2 = [ "ALTER TABLE booksTable ADD description TEXT", ]; final migrationScriptsV3 = [ "ALTER TABLE booksTable ADD book_type TEXT", ]; final migrationScriptsV4 = [ "ALTER TABLE booksTable ADD has_cover INTEGER DEFAULT 0", ]; final migrationScriptsV5 = [ "ALTER TABLE booksTable ADD notes TEXT", ]; final migrationScriptsV6 = [ "ALTER TABLE booksTable ADD reading_time INTEGER", ]; // added readings - combined start_date, finish_date and reading_time final migrationScriptsV7 = [ "ALTER TABLE booksTable ADD readings TEXT", "UPDATE booksTable SET readings = COALESCE(start_date, '') || '|' || COALESCE(finish_date, '') || '|' || COALESCE(CAST(reading_time AS TEXT), '')", ]; final migrationScriptsV8 = [ "ALTER TABLE booksTable ADD date_added TEXT DEFAULT '${DateTime.now().toIso8601String()}'", "ALTER TABLE booksTable ADD date_modified TEXT DEFAULT '${DateTime.now().toIso8601String()}'", ]; void _updateBookDatabaseV1toV8(Batch batch) { _executeBatch( batch, migrationScriptsV2 + migrationScriptsV3 + migrationScriptsV4 + migrationScriptsV5 + migrationScriptsV6 + migrationScriptsV7 + migrationScriptsV8, ); } void _updateBookDatabaseV2toV8(Batch batch) { _executeBatch( batch, migrationScriptsV3 + migrationScriptsV4 + migrationScriptsV5 + migrationScriptsV6 + migrationScriptsV7 + migrationScriptsV8, ); } void _updateBookDatabaseV3toV8(Batch batch) { _executeBatch( batch, migrationScriptsV4 + migrationScriptsV5 + migrationScriptsV6 + migrationScriptsV7 + migrationScriptsV8, ); } void _updateBookDatabaseV4toV8(Batch batch) { _executeBatch( batch, migrationScriptsV5 + migrationScriptsV6 + migrationScriptsV7 + migrationScriptsV8, ); } void _updateBookDatabaseV5toV8(Batch batch) { _executeBatch( batch, migrationScriptsV6 + migrationScriptsV7 + migrationScriptsV8, ); } void _updateBookDatabaseV6toV8(Batch batch) { _executeBatch( batch, migrationScriptsV7 + migrationScriptsV8, ); } void _updateBookDatabaseV7toV8(Batch batch) { _executeBatch( batch, migrationScriptsV8, ); } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/resources/connectivity_service.dart
import 'dart:async'; import 'package:connectivity_plus/connectivity_plus.dart'; class ConnectivityService { final _connectivity = Connectivity(); final connectivityStream = StreamController<List<ConnectivityResult>>.broadcast(); ConnectivityService() { _connectivity.onConnectivityChanged.listen((event) { connectivityStream.add(event); }); } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/resources/open_library_service.dart
import 'package:flutter/services.dart'; import 'package:http/http.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/model/ol_edition_result.dart'; import 'package:openreads/model/ol_search_result.dart'; import 'package:openreads/model/ol_work_result.dart'; class OpenLibraryService { static const baseUrl = 'https://openlibrary.org/'; static const coversBaseUrl = 'https://covers.openlibrary.org'; Future<OLSearchResult> getResults({ required String query, required int offset, required int limit, required OLSearchType searchType, }) async { final searchTypeParam = searchType == OLSearchType.general ? 'q' : searchType == OLSearchType.author ? 'author' : searchType == OLSearchType.title ? 'title' : searchType == OLSearchType.isbn ? 'isbn' : 'q'; const modeParam = '&mode=everything'; const fieldsParam = '&fields=key,title,subtitle,author_key,author_name,editions,number_of_pages_median,first_publish_year,isbn,edition_key,cover_edition_key,cover_i'; final offsetParam = '&offset=$offset'; final limitParam = '&limit=$limit'; final uri = Uri.parse( '${baseUrl}search.json?$searchTypeParam=$query$limitParam$offsetParam$modeParam$fieldsParam', ); final response = await get(uri); return openLibrarySearchResultFromJson(response.body); } Future<OLEditionResult> getEdition(String edition) async { final uri = Uri.parse('$baseUrl/works/$edition.json'); final response = await get(uri); return openLibraryEditionResultFromJson(response.body); } Future<OLWorkResult> getWork(String work) async { final uri = Uri.parse('$baseUrl$work.json'); final response = await get(uri); return openLibraryWorkResultFromJson(response.body); } Future<Uint8List?> getCover(String isbn) async { try { final response = await get( Uri.parse('$coversBaseUrl/b/isbn/$isbn-L.jpg'), ); // If the response is less than 500 bytes, // probably the cover is not available if (response.bodyBytes.length < 500) return null; return response.bodyBytes; } catch (e) { return null; } } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/resources/repository.dart
import 'package:openreads/database/database_controler.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/core/constants/enums/enums.dart'; class Repository { final DatabaseController dbController = DatabaseController(); Future getAllNotDeletedBooks() => dbController.getAllNotDeletedBooks(); Future getAllBooks() => dbController.getAllBooks(); Future<List<Book>> getBooks(int status) => dbController.getBooks( status: status, ); Future<List<Book>> searchBooks(String query) => dbController.searchBooks( query: query, ); Future<int> countBooks(int status) => dbController.countBooks(status: status); Future<int> insertBook(Book book) => dbController.createBook(book); Future updateBook(Book book) => dbController.updateBook(book); Future bulkUpdateBookFormat(Set<int> ids, BookFormat bookFormat) => dbController.bulkUpdateBookFormat(ids, bookFormat); Future bulkUpdateBookAuthor(Set<int> ids, String author) => dbController.bulkUpdateBookAuthor(ids, author); Future deleteBook(int index) => dbController.deleteBook(index); Future<Book?> getBook(int index) => dbController.getBook(index); Future<List<Book>> getDeletedBooks() => dbController.getDeletedBooks(); Future<int> removeAllBooks() => dbController.removeAllBooks(); Future<List<Book>> getBooksWithSameTag(String tag) => dbController.getBooksWithSameTag(tag); Future<List<Book>> getBooksWithSameAuthor(String author) => dbController.getBooksWithSameAuthor(author); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/app_language.dart
import 'dart:ui'; class AppLanguage { String fullName; Locale locale; AppLanguage( this.fullName, this.locale, ); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/book_from_backup_v3.dart
import 'package:flutter/foundation.dart'; class BookFromBackupV3 { final int? id; final String? bookTitle; final String? bookAuthor; final String? bookStatus; final double? bookRating; final int? bookIsFav; final int? bookIsDeleted; final String? bookStartDate; final String? bookFinishDate; final int? bookNumberOfPages; final int? bookPublishYear; final String? bookISBN13; final String? bookISBN10; final String? bookOLID; final String? bookTags; final String? bookNotes; final Uint8List? bookCoverImg; BookFromBackupV3({ this.id, this.bookTitle, this.bookAuthor, this.bookStatus, this.bookRating, this.bookIsFav, this.bookIsDeleted, this.bookStartDate, this.bookFinishDate, this.bookNumberOfPages, this.bookPublishYear, this.bookISBN13, this.bookISBN10, this.bookOLID, this.bookTags, this.bookNotes, this.bookCoverImg, }); factory BookFromBackupV3.fromJson(Map<String, dynamic> json) { return BookFromBackupV3( id: json['id'] as int?, bookTitle: json['item_bookTitle'] as String?, bookAuthor: json['item_bookAuthor'] as String?, bookStatus: json['item_bookStatus'] as String?, bookRating: json['item_bookRating'] as double?, bookIsFav: json['item_bookIsFav'] as int?, bookIsDeleted: json['item_bookIsDeleted'] as int?, bookStartDate: json['item_bookStartDate'] as String?, bookFinishDate: json['item_bookFinishDate'] as String?, bookNumberOfPages: json['item_bookNumberOfPages'] as int?, bookPublishYear: json['item_bookPublishYear'] as int?, bookISBN13: json['item_bookISBN13'] as String?, bookISBN10: json['item_bookISBN10'] as String?, bookOLID: json['item_bookOLID'] as String?, bookTags: json['item_bookTags'] as String?, bookNotes: json['item_bookNotes'] as String?, bookCoverImg: json['item_bookCoverImg'] as Uint8List?, ); } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/year_from_backup_v3.dart
class YearFromBackupV3 { final int? id; final String? year; final int? yearChallengeBooks; final int? yearChallengePages; YearFromBackupV3({ this.id, this.year, this.yearChallengeBooks, this.yearChallengePages, }); factory YearFromBackupV3.fromJson(Map<String, dynamic> json) { return YearFromBackupV3( id: json['id'] as int?, year: json['item_year'] as String?, yearChallengeBooks: json['item_challenge_books'] as int?, yearChallengePages: json['item_challenge_pages'] as int?, ); } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/ol_edition_result.dart
import 'dart:convert'; import 'package:openreads/core/constants/enums/enums.dart'; OLEditionResult openLibraryEditionResultFromJson(String str) => OLEditionResult.fromJson(json.decode(str)); class OLEditionResult { OLEditionResult({ this.publishers, this.numberOfPages, this.isbn10, this.covers, this.key, this.authors, this.ocaid, this.contributions, this.languages, this.classifications, this.sourceRecords, this.title, this.subtitle, this.identifiers, this.isbn13, this.localId, this.publishDate, this.works, this.type, this.latestRevision, this.revision, this.created, this.lastModified, this.physicalFormat, }); final List<String>? publishers; final int? numberOfPages; final List<String>? isbn10; final List<int?>? covers; final String? key; final List<Type>? authors; final String? ocaid; final List<String>? contributions; final List<Type>? languages; final Classifications? classifications; final List<String>? sourceRecords; final String? title; final String? subtitle; final Identifiers? identifiers; final List<String>? isbn13; final List<String>? localId; final String? publishDate; final List<Type>? works; final Type? type; final int? latestRevision; final int? revision; final Created? created; final Created? lastModified; final BookFormat? physicalFormat; factory OLEditionResult.fromJson(Map<String, dynamic> json) { return OLEditionResult( publishers: json["publishers"] == null ? null : List<String>.from(json["publishers"].map((x) => x)), numberOfPages: json["number_of_pages"], isbn10: json["isbn_10"] == null ? null : List<String>.from(json["isbn_10"].map((x) => x)), covers: json["covers"] == null ? null : List<int?>.from(json["covers"].map((x) => x)), key: json["key"], authors: json["authors"] == null ? null : List<Type>.from(json["authors"].map((x) => Type.fromJson(x))), ocaid: json["ocaid"], contributions: json["contributions"] == null ? null : List<String>.from(json["contributions"].map((x) => x)), languages: json["languages"] == null ? null : List<Type>.from(json["languages"].map((x) => Type.fromJson(x))), classifications: json["classifications"] == null ? null : Classifications.fromJson(json["classifications"]), sourceRecords: json["source_records"] == null ? null : List<String>.from(json["source_records"].map((x) => x)), title: json["title"], subtitle: json["subtitle"], identifiers: json["identifiers"] == null ? null : Identifiers.fromJson(json["identifiers"]), isbn13: json["isbn_13"] == null ? null : List<String>.from(json["isbn_13"].map((x) => x)), localId: json["local_id"] == null ? null : List<String>.from(json["local_id"].map((x) => x)), publishDate: json["publish_date"], works: json["works"] == null ? null : List<Type>.from(json["works"].map((x) => Type.fromJson(x))), type: json["type"] == null ? null : Type.fromJson(json["type"]), latestRevision: json["latest_revision"], revision: json["revision"], created: json["created"] == null ? null : Created.fromJson(json["created"]), lastModified: json["last_modified"] == null ? null : Created.fromJson(json["last_modified"]), physicalFormat: json['physical_format'] != null ? json['physical_format'] == 'Hardcover' ? BookFormat.hardcover : json['physical_format'] == 'Mass Market Paperback' ? BookFormat.paperback : null : null, ); } } class Type { Type({ this.key, }); final String? key; factory Type.fromJson(Map<String, dynamic> json) => Type( key: json["key"], ); } class Classifications { Classifications(); factory Classifications.fromJson(Map<String, dynamic> json) => Classifications(); } class Created { Created({ this.type, this.value, }); final String? type; final String? value; factory Created.fromJson(Map<String, dynamic> json) => Created( type: json["type"], value: json["value"], ); } class Identifiers { Identifiers({ this.goodreads, this.librarything, }); final List<String>? goodreads; final List<String>? librarything; factory Identifiers.fromJson(Map<String, dynamic> json) => Identifiers( goodreads: json["goodreads"] == null ? null : List<String>.from(json["goodreads"].map((x) => x)), librarything: json["librarything"] == null ? null : List<String>.from(json["librarything"].map((x) => x)), ); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/book_read_stat.dart
class BookReadStat { int? year; List<int> values; BookReadStat({ this.year, required this.values, }); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/reading_time.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:openreads/generated/locale_keys.g.dart'; // Converts milliseconds to days, hours, minutes to exactly what has been set. // This is needed because built-in DateTime returns the whole duration either in days or hours but not both class ReadingTime { int days; int hours; int minutes; int milliSeconds; ReadingTime( {required this.milliSeconds, required this.days, required this.minutes, required this.hours}); factory ReadingTime.fromMilliSeconds(int milliSeconds) { int timeInSeconds = milliSeconds ~/ 1000; int days = timeInSeconds ~/ (24 * 3600); timeInSeconds = timeInSeconds % (24 * 3600); int hours = timeInSeconds ~/ 3600; timeInSeconds %= 3600; int minutes = timeInSeconds ~/ 60; return ReadingTime( milliSeconds: milliSeconds, days: days, minutes: minutes, hours: hours); } factory ReadingTime.toMilliSeconds(int days, hours, minutes) { int seconds = ((days * 86400) + (hours * 3600) + (minutes * 60)).toInt(); return ReadingTime( milliSeconds: seconds * 1000, days: days, minutes: minutes, hours: hours); } @override String toString() { String result = ""; if (days != 0) { result += LocaleKeys.day.plural(days).tr(); } if (hours != 0) { if (result.isNotEmpty) { result += " "; } result += LocaleKeys.hour.plural(hours).tr(); } if (minutes != 0) { if (result.isNotEmpty) { result += " "; } result += LocaleKeys.minute.plural(minutes).tr(); } return result; } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/book_yearly_stat.dart
import 'package:openreads/model/book.dart'; class BookYearlyStat { Book? book; int? year; String value; String? title; BookYearlyStat({ this.book, this.year, this.title, required this.value, }); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/ol_search_result.dart
import 'dart:convert'; OLSearchResult openLibrarySearchResultFromJson(String str) => OLSearchResult.fromJson(json.decode(str)); class OLSearchResult { OLSearchResult({ this.numFound, this.start, this.numFoundExact, required this.docs, this.openLibrarySearchResultNumFound, this.q, this.offset, }); final int? numFound; final int? start; final bool? numFoundExact; final List<OLSearchResultDoc> docs; final int? openLibrarySearchResultNumFound; final String? q; final dynamic offset; factory OLSearchResult.fromJson(Map<String, dynamic> json) => OLSearchResult( numFound: json["numFound"], start: json["start"], numFoundExact: json["numFoundExact"], docs: List<OLSearchResultDoc>.from( json["docs"].map((x) => OLSearchResultDoc.fromJson(x))), openLibrarySearchResultNumFound: json["num_found"], q: json["q"], offset: json["offset"], ); } class OLSearchResultDoc { OLSearchResultDoc({ this.key, this.type, this.seed, this.title, this.titleSuggest, this.editionCount, this.editionKey, this.publishDate, this.publishYear, this.firstPublishYear, this.medianPages, this.lccn, this.publishPlace, this.oclc, this.contributor, this.lcc, this.ddc, this.isbn, this.lastModifiedI, this.ebookCountI, this.ebookAccess, this.hasFulltext, this.publicScanB, this.ia, this.iaCollection, this.iaCollectionS, this.lendingEditionS, this.lendingIdentifierS, this.printdisabledS, this.coverEditionKey, this.coverI, this.firstSentence, this.publisher, this.language, this.authorKey, this.authorName, this.authorAlternativeName, this.person, this.place, this.subject, this.idAlibrisId, this.idAmazon, this.idBodleianOxfordUniversity, this.idDepsitoLegal, this.idGoodreads, this.idGoogle, this.idHathiTrust, this.idLibrarything, this.idPaperbackSwap, this.idWikidata, this.idYakaboo, this.iaLoadedId, this.iaBoxId, this.publisherFacet, this.personKey, this.placeKey, this.personFacet, this.subjectFacet, this.version, this.placeFacet, this.lccSort, this.authorFacet, this.subjectKey, this.ddcSort, this.idAmazonCaAsin, this.idAmazonCoUkAsin, this.idAmazonDeAsin, this.idAmazonItAsin, this.idCanadianNationalLibraryArchive, this.idOverdrive, this.idAbebooksDe, this.idBritishLibrary, this.idBritishNationalBibliography, this.time, this.timeFacet, this.timeKey, this.subtitle, }); final String? key; final Type? type; final List<String>? seed; final String? title; final String? titleSuggest; final int? editionCount; final List<String>? editionKey; final List<String>? publishDate; final List<int>? publishYear; final int? firstPublishYear; final int? medianPages; final List<String>? lccn; final List<String>? publishPlace; final List<String>? oclc; final List<String>? contributor; final List<String>? lcc; final List<String>? ddc; final List<String>? isbn; final int? lastModifiedI; final int? ebookCountI; final EbookAccess? ebookAccess; final bool? hasFulltext; final bool? publicScanB; final List<String>? ia; final List<String>? iaCollection; final String? iaCollectionS; final String? lendingEditionS; final String? lendingIdentifierS; final String? printdisabledS; final String? coverEditionKey; final int? coverI; final List<String>? firstSentence; final List<String>? publisher; final List<String>? language; final List<String>? authorKey; final List<String>? authorName; final List<String>? authorAlternativeName; final List<String>? person; final List<String>? place; final List<String>? subject; final List<String>? idAlibrisId; final List<String>? idAmazon; final List<String>? idBodleianOxfordUniversity; final List<String>? idDepsitoLegal; final List<String>? idGoodreads; final List<String>? idGoogle; final List<String>? idHathiTrust; final List<String>? idLibrarything; final List<String>? idPaperbackSwap; final List<String>? idWikidata; final List<String>? idYakaboo; final List<String>? iaLoadedId; final List<String>? iaBoxId; final List<String>? publisherFacet; final List<String>? personKey; final List<String>? placeKey; final List<String>? personFacet; final List<String>? subjectFacet; final double? version; final List<String>? placeFacet; final String? lccSort; final List<String>? authorFacet; final List<String>? subjectKey; final String? ddcSort; final List<String>? idAmazonCaAsin; final List<String>? idAmazonCoUkAsin; final List<String>? idAmazonDeAsin; final List<String>? idAmazonItAsin; final List<String>? idCanadianNationalLibraryArchive; final List<String>? idOverdrive; final List<String>? idAbebooksDe; final List<String>? idBritishLibrary; final List<String>? idBritishNationalBibliography; final List<String>? time; final List<String>? timeFacet; final List<String>? timeKey; final String? subtitle; factory OLSearchResultDoc.fromJson(Map<String, dynamic> json) => OLSearchResultDoc( key: json["key"], type: json["type"] == null ? null : typeValues.map[json["type"]], seed: json["seed"] == null ? null : List<String>.from(json["seed"].map((x) => x)), title: json["title"], titleSuggest: json["title_suggest"], editionCount: json["edition_count"], editionKey: json["edition_key"] == null ? null : List<String>.from(json["edition_key"].map((x) => x)), publishDate: json["publish_date"] == null ? null : List<String>.from(json["publish_date"].map((x) => x)), publishYear: json["publish_year"] == null ? null : List<int>.from(json["publish_year"].map((x) => x)), firstPublishYear: json["first_publish_year"], medianPages: json["number_of_pages_median"], lccn: json["lccn"] == null ? null : List<String>.from(json["lccn"].map((x) => x)), publishPlace: json["publish_place"] == null ? null : List<String>.from(json["publish_place"].map((x) => x)), oclc: json["oclc"] == null ? null : List<String>.from(json["oclc"].map((x) => x)), contributor: json["contributor"] == null ? null : List<String>.from(json["contributor"].map((x) => x)), lcc: json["lcc"] == null ? null : List<String>.from(json["lcc"].map((x) => x)), ddc: json["ddc"] == null ? null : List<String>.from(json["ddc"].map((x) => x)), isbn: json["isbn"] == null ? null : List<String>.from(json["isbn"].map((x) => x)), lastModifiedI: json["last_modified_i"], ebookCountI: json["ebook_count_i"], ebookAccess: json["ebook_access"] == null ? null : ebookAccessValues.map[json["ebook_access"]], hasFulltext: json["has_fulltext"], publicScanB: json["public_scan_b"], ia: json["ia"] == null ? null : List<String>.from(json["ia"].map((x) => x)), iaCollection: json["ia_collection"] == null ? null : List<String>.from(json["ia_collection"].map((x) => x)), iaCollectionS: json["ia_collection_s"], lendingEditionS: json["lending_edition_s"], lendingIdentifierS: json["lending_identifier_s"], printdisabledS: json["printdisabled_s"], coverEditionKey: json["cover_edition_key"], coverI: json["cover_i"], firstSentence: json["first_sentence"] == null ? null : List<String>.from(json["first_sentence"].map((x) => x)), publisher: json["publisher"] == null ? null : List<String>.from(json["publisher"].map((x) => x)), language: json["language"] == null ? null : List<String>.from(json["language"].map((x) => x)), authorKey: json["author_key"] == null ? null : List<String>.from(json["author_key"].map((x) => x)), authorName: json["author_name"] == null ? null : List<String>.from(json["author_name"].map((x) => x)), authorAlternativeName: json["author_alternative_name"] == null ? null : List<String>.from(json["author_alternative_name"].map((x) => x)), person: json["person"] == null ? null : List<String>.from(json["person"].map((x) => x)), place: json["place"] == null ? null : List<String>.from(json["place"].map((x) => x)), subject: json["subject"] == null ? null : List<String>.from(json["subject"].map((x) => x)), idAlibrisId: json["id_alibris_id"] == null ? null : List<String>.from(json["id_alibris_id"].map((x) => x)), idAmazon: json["id_amazon"] == null ? null : List<String>.from(json["id_amazon"].map((x) => x)), idBodleianOxfordUniversity: json["id_bodleian__oxford_university"] == null ? null : List<String>.from( json["id_bodleian__oxford_university"].map((x) => x)), idDepsitoLegal: json["id_depósito_legal"] == null ? null : List<String>.from(json["id_depósito_legal"].map((x) => x)), idGoodreads: json["id_goodreads"] == null ? null : List<String>.from(json["id_goodreads"].map((x) => x)), idGoogle: json["id_google"] == null ? null : List<String>.from(json["id_google"].map((x) => x)), idHathiTrust: json["id_hathi_trust"] == null ? null : List<String>.from(json["id_hathi_trust"].map((x) => x)), idLibrarything: json["id_librarything"] == null ? null : List<String>.from(json["id_librarything"].map((x) => x)), idPaperbackSwap: json["id_paperback_swap"] == null ? null : List<String>.from(json["id_paperback_swap"].map((x) => x)), idWikidata: json["id_wikidata"] == null ? null : List<String>.from(json["id_wikidata"].map((x) => x)), idYakaboo: json["id_yakaboo"] == null ? null : List<String>.from(json["id_yakaboo"].map((x) => x)), iaLoadedId: json["ia_loaded_id"] == null ? null : List<String>.from(json["ia_loaded_id"].map((x) => x)), iaBoxId: json["ia_box_id"] == null ? null : List<String>.from(json["ia_box_id"].map((x) => x)), publisherFacet: json["publisher_facet"] == null ? null : List<String>.from(json["publisher_facet"].map((x) => x)), personKey: json["person_key"] == null ? null : List<String>.from(json["person_key"].map((x) => x)), placeKey: json["place_key"] == null ? null : List<String>.from(json["place_key"].map((x) => x)), personFacet: json["person_facet"] == null ? null : List<String>.from(json["person_facet"].map((x) => x)), subjectFacet: json["subject_facet"] == null ? null : List<String>.from(json["subject_facet"].map((x) => x)), version: json["_version_"] == null ? null : json["_version_"].toDouble(), placeFacet: json["place_facet"] == null ? null : List<String>.from(json["place_facet"].map((x) => x)), lccSort: json["lcc_sort"], authorFacet: json["author_facet"] == null ? null : List<String>.from(json["author_facet"].map((x) => x)), subjectKey: json["subject_key"] == null ? null : List<String>.from(json["subject_key"].map((x) => x)), ddcSort: json["ddc_sort"], idAmazonCaAsin: json["id_amazon_ca_asin"] == null ? null : List<String>.from(json["id_amazon_ca_asin"].map((x) => x)), idAmazonCoUkAsin: json["id_amazon_co_uk_asin"] == null ? null : List<String>.from(json["id_amazon_co_uk_asin"].map((x) => x)), idAmazonDeAsin: json["id_amazon_de_asin"] == null ? null : List<String>.from(json["id_amazon_de_asin"].map((x) => x)), idAmazonItAsin: json["id_amazon_it_asin"] == null ? null : List<String>.from(json["id_amazon_it_asin"].map((x) => x)), idCanadianNationalLibraryArchive: json["id_canadian_national_library_archive"] == null ? null : List<String>.from( json["id_canadian_national_library_archive"].map((x) => x)), idOverdrive: json["id_overdrive"] == null ? null : List<String>.from(json["id_overdrive"].map((x) => x)), idAbebooksDe: json["id_abebooks_de"] == null ? null : List<String>.from(json["id_abebooks_de"].map((x) => x)), idBritishLibrary: json["id_british_library"] == null ? null : List<String>.from(json["id_british_library"].map((x) => x)), idBritishNationalBibliography: json["id_british_national_bibliography"] == null ? null : List<String>.from( json["id_british_national_bibliography"].map((x) => x)), time: json["time"] == null ? null : List<String>.from(json["time"].map((x) => x)), timeFacet: json["time_facet"] == null ? null : List<String>.from(json["time_facet"].map((x) => x)), timeKey: json["time_key"] == null ? null : List<String>.from(json["time_key"].map((x) => x)), subtitle: json["subtitle"], ); } enum EbookAccess { borrowable, noEbook, public, printdisabled } final ebookAccessValues = EnumValues({ "borrowable": EbookAccess.borrowable, "no_ebook": EbookAccess.noEbook, "printdisabled": EbookAccess.printdisabled, "public": EbookAccess.public }); enum Type { work } final typeValues = EnumValues({"work": Type.work}); class EnumValues<T> { Map<String, T> map; EnumValues(this.map); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/book.dart
import 'dart:convert'; import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/model/book_from_backup_v3.dart'; class Book { int? id; String title; String? subtitle; String author; String? description; BookStatus status; bool favourite; bool deleted; int? rating; int? pages; int? publicationYear; String? isbn; String? olid; String? tags; String? myReview; String? notes; Uint8List? cover; // Not used since 2.2.0 String? blurHash; BookFormat bookFormat; bool hasCover; List<Reading> readings; DateTime dateAdded; DateTime dateModified; Book({ this.id, required this.title, required this.author, required this.status, this.subtitle, this.description, this.favourite = false, this.deleted = false, this.rating, this.pages, this.publicationYear, this.isbn, this.olid, this.tags, this.myReview, this.notes, this.cover, this.blurHash, this.bookFormat = BookFormat.paperback, this.hasCover = false, required this.readings, required this.dateAdded, required this.dateModified, }); factory Book.empty({ BookStatus status = BookStatus.read, BookFormat bookFormat = BookFormat.paperback, }) { return Book( id: null, title: '', author: '', status: status, favourite: false, deleted: false, bookFormat: bookFormat, hasCover: false, readings: List<Reading>.empty(growable: true), tags: LocaleKeys.owned_book_tag.tr(), dateAdded: DateTime.now(), dateModified: DateTime.now(), ); } factory Book.fromJSON(Map<String, dynamic> json) { return Book( id: json['id'], title: json['title'], subtitle: json['subtitle'], author: json['author'], description: json['description'], status: parseBookStatus(json['status']), rating: json['rating'], favourite: (json['favourite'] == 1) ? true : false, hasCover: (json['has_cover'] == 1) ? true : false, deleted: (json['deleted'] == 1) ? true : false, pages: json['pages'], publicationYear: json['publication_year'], isbn: json['isbn'], olid: json['olid'], tags: json['tags'], myReview: json['my_review'], notes: json['notes'], cover: json['cover'] != null ? Uint8List.fromList(json['cover'].cast<int>().toList()) : null, blurHash: json['blur_hash'], bookFormat: json['book_type'] == 'audiobook' ? BookFormat.audiobook : json['book_type'] == 'ebook' ? BookFormat.ebook : json['book_type'] == 'hardcover' ? BookFormat.hardcover : json['book_type'] == 'paperback' ? BookFormat.paperback : BookFormat.paperback, readings: _sortReadings(_parseReadingsFromJson(json)), dateAdded: json['date_added'] != null ? DateTime.parse(json['date_added']) : DateTime.now(), dateModified: json['date_modified'] != null ? DateTime.parse(json['date_modified']) : DateTime.now(), ); } Book copyWith({ String? title, String? author, BookStatus? status, String? subtitle, String? description, bool? favourite, bool? deleted, int? rating, int? pages, int? publicationYear, String? isbn, String? olid, String? tags, String? myReview, String? notes, Uint8List? cover, String? blurHash, BookFormat? bookFormat, bool? hasCover, List<Reading>? readings, DateTime? dateAdded, DateTime? dateModified, }) { return Book( id: id, title: title ?? this.title, subtitle: subtitle ?? this.subtitle, author: author ?? this.author, status: status ?? this.status, description: description ?? this.description, favourite: favourite ?? this.favourite, deleted: deleted ?? this.deleted, rating: rating ?? this.rating, pages: pages ?? this.pages, publicationYear: publicationYear ?? this.publicationYear, isbn: isbn ?? this.isbn, olid: olid ?? this.olid, tags: tags ?? this.tags, myReview: myReview ?? this.myReview, notes: notes ?? this.notes, cover: cover ?? this.cover, blurHash: blurHash ?? this.blurHash, bookFormat: bookFormat ?? this.bookFormat, hasCover: hasCover ?? this.hasCover, readings: readings ?? this.readings, dateAdded: dateAdded ?? this.dateAdded, dateModified: dateModified ?? this.dateModified, ); } Book copyWithNullCover() { return Book( id: id, title: title, subtitle: subtitle, author: author, status: status, description: description, favourite: favourite, deleted: deleted, rating: rating, pages: pages, publicationYear: publicationYear, isbn: isbn, olid: olid, tags: tags, myReview: myReview, notes: notes, cover: null, blurHash: blurHash, bookFormat: bookFormat, hasCover: hasCover, readings: readings, dateAdded: dateAdded, dateModified: dateModified, ); } factory Book.fromBookFromBackupV3( BookFromBackupV3 oldBook, String? blurHash) { return Book( title: oldBook.bookTitle ?? '', author: oldBook.bookAuthor ?? '', status: oldBook.bookStatus == 'not_finished' ? BookStatus.unfinished : oldBook.bookStatus == 'to_read' ? BookStatus.forLater : oldBook.bookStatus == 'in_progress' ? BookStatus.inProgress : BookStatus.read, rating: oldBook.bookRating != null ? (oldBook.bookRating! * 10).toInt() : null, favourite: oldBook.bookIsFav == 1, deleted: oldBook.bookIsDeleted == 1, pages: oldBook.bookNumberOfPages, publicationYear: oldBook.bookPublishYear, isbn: oldBook.bookISBN13 ?? oldBook.bookISBN10, olid: oldBook.bookOLID, tags: oldBook.bookTags != null && oldBook.bookTags != 'null' ? jsonDecode(oldBook.bookTags!).join('|||||') : null, notes: oldBook.bookNotes, cover: oldBook.bookCoverImg, blurHash: blurHash, bookFormat: BookFormat.paperback, hasCover: false, readings: (oldBook.bookStartDate == null || oldBook.bookStartDate == "null" || oldBook.bookStartDate == "none") && (oldBook.bookFinishDate == null || oldBook.bookFinishDate == "null" || oldBook.bookFinishDate == "none") ? List<Reading>.empty(growable: true) : [ Reading( startDate: oldBook.bookStartDate != null && oldBook.bookStartDate != 'none' && oldBook.bookStartDate != 'null' ? DateTime.fromMillisecondsSinceEpoch( int.parse(oldBook.bookStartDate!)) : null, finishDate: oldBook.bookFinishDate != null && oldBook.bookFinishDate != 'none' && oldBook.bookFinishDate != 'null' ? DateTime.fromMillisecondsSinceEpoch( int.parse(oldBook.bookFinishDate!)) : null) ], dateAdded: DateTime.now(), dateModified: DateTime.now(), ); } Map<String, dynamic> toJSON() { return { 'id': id, 'title': title, 'subtitle': subtitle, 'author': author, 'description': description, 'status': status.value, 'rating': rating, 'favourite': favourite ? 1 : 0, 'deleted': deleted ? 1 : 0, 'pages': pages, 'publication_year': publicationYear, 'isbn': isbn, 'olid': olid, 'tags': tags, 'my_review': myReview, 'notes': notes, 'blur_hash': blurHash, 'has_cover': hasCover ? 1 : 0, 'book_type': bookFormat == BookFormat.audiobook ? 'audiobook' : bookFormat == BookFormat.ebook ? 'ebook' : bookFormat == BookFormat.hardcover ? 'hardcover' : bookFormat == BookFormat.paperback ? 'paperback' : 'paperback', 'readings': readings.map((reading) => reading.toString()).join(';'), 'date_added': dateAdded.toIso8601String(), 'date_modified': dateModified.toIso8601String(), }; } File? getCoverFile() { final fileExists = File('${appDocumentsDirectory.path}/$id.jpg').existsSync(); if (fileExists) { return File('${appDocumentsDirectory.path}/$id.jpg'); } else { return null; } } Uint8List? getCoverBytes() { final fileExists = File('${appDocumentsDirectory.path}/$id.jpg').existsSync(); if (fileExists) { return File('${appDocumentsDirectory.path}/$id.jpg').readAsBytesSync(); } else { return null; } } static List<Reading> _parseReadingsFromJson(Map<String, dynamic> json) { if (json['readings'] != null) { final splittedReadings = json['readings'].split(';'); if (splittedReadings.isNotEmpty) { return List<Reading>.from( splittedReadings.map((e) { final reading = Reading.fromString(e); if (reading.startDate == null && reading.finishDate == null && reading.customReadingTime == null) { return null; } else { return reading; } }).where((reading) => reading != null), ); } else { return List<Reading>.empty(growable: true); } } else if (json['start_date'] != null || json['finish_date'] != null) { return [ Reading( startDate: json['start_date'] != null ? DateTime.parse(json['start_date']) : null, finishDate: json['finish_date'] != null ? DateTime.parse(json['finish_date']) : null) ]; } else { return List<Reading>.empty(growable: true); } } // order readings // first order the ones with only start date - first newest // after them order ones with finish date - first newest static List<Reading> _sortReadings(List<Reading> readings) { final sortedReadings = readings; sortedReadings.sort((a, b) { if (a.finishDate == null && b.finishDate != null) { return -1; } else if (a.finishDate != null && b.finishDate == null) { return 1; } else if (a.finishDate != null && b.finishDate != null) { return b.finishDate!.compareTo(a.finishDate!); } else { return b.startDate!.compareTo(a.startDate!); } }); return sortedReadings; } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/ol_work_result.dart
import 'dart:convert'; OLWorkResult openLibraryWorkResultFromJson(String str) => OLWorkResult.fromJson(json.decode(str)); class OLWorkResult { OLWorkResult({ this.description, }); final String? description; factory OLWorkResult.fromJson(Map<String, dynamic> json) => OLWorkResult( description: json["description"] is Map ? (json["description"]["value"] ?? json["description"]) : json["description"], ); }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/yearly_challenge.dart
class YearlyChallenge { int year; int? books; int? pages; YearlyChallenge({ required this.year, required this.books, required this.pages, }); factory YearlyChallenge.fromJSON(Map<String, dynamic> json) { return YearlyChallenge( year: json['year'], books: json['books'], pages: json['pages'], ); } Map<String, dynamic> toJSON() { return { 'year': year, 'books': books, 'pages': pages, }; } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/model/reading.dart
import 'package:openreads/model/reading_time.dart'; class Reading { DateTime? startDate; DateTime? finishDate; ReadingTime? customReadingTime; Reading({ this.startDate, this.finishDate, this.customReadingTime, }); factory Reading.fromString(String input) { List<String> dateAndValue = input.split('|'); if (dateAndValue.length != 3) { return Reading(); } DateTime? startDate = dateAndValue[0] != '' ? DateTime.parse(dateAndValue[0]) : null; DateTime? finishDate = dateAndValue[1] != '' ? DateTime.parse(dateAndValue[1]) : null; final customReadingTime = dateAndValue[2] != '' ? ReadingTime.fromMilliSeconds( int.parse(dateAndValue[2]), ) : null; return Reading( startDate: startDate, finishDate: finishDate, customReadingTime: customReadingTime, ); } @override String toString() { final startDate = this.startDate != null ? this.startDate!.toIso8601String() : ''; final finishDate = this.finishDate != null ? this.finishDate!.toIso8601String() : ''; final customReadingTime = this.customReadingTime != null ? this.customReadingTime!.milliSeconds.toString() : ''; return '$startDate|$finishDate|$customReadingTime'; } Reading copyWith({ DateTime? startDate, DateTime? finishDate, ReadingTime? customReadingTime, }) { return Reading( startDate: startDate ?? this.startDate, finishDate: finishDate ?? this.finishDate, customReadingTime: customReadingTime ?? this.customReadingTime, ); } }
0
mirrored_repositories/openreads/lib/core
mirrored_repositories/openreads/lib/core/constants/locale.dart
import 'dart:ui'; import 'package:openreads/model/app_language.dart'; final supportedLocales = [ AppLanguage('العربية', const Locale('ar', 'SA')), AppLanguage('català', const Locale('ca', 'ES')), AppLanguage('čeština', const Locale('cs', 'CZ')), AppLanguage('Deutsch', const Locale('de', 'DE')), AppLanguage('dansk', const Locale('da', 'DK')), AppLanguage('English', const Locale('en', 'US')), AppLanguage('Euskara', const Locale('eu')), AppLanguage('eesti keel', const Locale('et')), AppLanguage('español', const Locale('es', 'ES')), AppLanguage('suomi', const Locale('fi', 'FI')), AppLanguage('Filipino', const Locale('fil', 'PH')), AppLanguage('français', const Locale('fr', 'FR')), AppLanguage('galego', const Locale('gl')), AppLanguage('hrvatski', const Locale('hr', 'HR')), AppLanguage('हिन्दी', const Locale('hi', 'IN')), AppLanguage('italiano', const Locale('it', 'IT')), AppLanguage('日本語', const Locale('ja', 'JP')), AppLanguage('한국어', const Locale('ko')), AppLanguage('ქართული', const Locale('ka', 'GE')), AppLanguage('limba română', const Locale('ro', 'RO')), AppLanguage('മലയാളം', const Locale('ml')), AppLanguage('Nederlands', const Locale('nl', 'NL')), AppLanguage('Norsk', const Locale('no', 'NO')), AppLanguage('ଓଡ଼ିଆ', const Locale('or', 'IN')), AppLanguage('ਪੰਜਾਬੀ', const Locale('pa')), AppLanguage('polski', const Locale('pl', 'PL')), AppLanguage('português', const Locale('pt', 'PT')), AppLanguage('português brasileiro', const Locale('pt', 'BR')), AppLanguage('русский язык', const Locale('ru', 'RU')), AppLanguage('svenska', const Locale('sv', 'SE')), AppLanguage('Türkçe', const Locale('tr', 'TR')), AppLanguage('Українська', const Locale('uk', 'UA')), AppLanguage('Tiếng Việt', const Locale('vi', 'VN')), AppLanguage('中文', const Locale('zh', 'CN')), ];
0
mirrored_repositories/openreads/lib/core
mirrored_repositories/openreads/lib/core/constants/constants.dart
class Constants { static const appName = 'Openreads'; static const formHeight = 60.0; static const blurHashX = 2; static const blurHashY = 2; static const maxTagLength = 100; static const duckDuckGoURL = 'https://duckduckgo.com/'; static const duckDuckGoImagesURL = 'https://duckduckgo.com/i.js'; } class SharedPreferencesKeys { static const coverMigrationDone = 'is_cover_migration_done'; static const duckDuckGoWarning = 'show_duck_duck_go_warning'; }
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/ol_search_type.dart
enum OLSearchType { general, title, author, isbn, openlibraryId, }
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/enums.dart
export 'book_format.dart'; export 'book_status.dart'; export 'bulk_edit_option.dart'; export 'font.dart'; export 'ol_search_type.dart'; export 'rating_type.dart'; export 'sort_type.dart';
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/bulk_edit_option.dart
enum BulkEditOption { format, author, delete, }
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/rating_type.dart
enum RatingType { bar, number, }
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/book_format.dart
enum BookFormat { paperback, hardcover, ebook, audiobook, } extension BookFormatExtension on BookFormat { int get value { switch (this) { case BookFormat.paperback: return 0; case BookFormat.hardcover: return 1; case BookFormat.ebook: return 2; case BookFormat.audiobook: return 3; default: return 0; } } } BookFormat parseBookFormat(int value) { switch (value) { case 0: return BookFormat.paperback; case 1: return BookFormat.hardcover; case 2: return BookFormat.ebook; case 3: return BookFormat.audiobook; default: return BookFormat.paperback; } }
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/font.dart
enum Font { system, montserrat, lato, sofiaSans, poppins, raleway, nunito, playfairDisplay, kanit, lora, quicksand, barlow, jost, inter, atkinsonHyperlegible, openDyslexic, }
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/book_status.dart
enum BookStatus { read, inProgress, forLater, unfinished, } extension BookStatusExtension on BookStatus { int get value { switch (this) { case BookStatus.read: return 0; case BookStatus.inProgress: return 1; case BookStatus.forLater: return 2; case BookStatus.unfinished: return 3; default: return 0; } } } BookStatus parseBookStatus(int value) { switch (value) { case 0: return BookStatus.read; case 1: return BookStatus.inProgress; case 2: return BookStatus.forLater; case 3: return BookStatus.unfinished; default: return BookStatus.read; } }
0
mirrored_repositories/openreads/lib/core/constants
mirrored_repositories/openreads/lib/core/constants/enums/sort_type.dart
enum SortType { byTitle, byAuthor, byRating, byPages, byStartDate, byFinishDate, byPublicationYear, byDateAdded, byDateModified, }
0
mirrored_repositories/openreads/lib/core
mirrored_repositories/openreads/lib/core/themes/app_theme.dart
import 'package:flutter/material.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; double get cornerRadius => _cornerRadius!; double? _cornerRadius; bool get readTabFirst => _readTabFirst!; bool? _readTabFirst; Color get dividerColor => _dividerColor!; Color? _dividerColor; Color likeColor = const Color.fromARGB(255, 194, 49, 61); Color ratingColor = const Color.fromARGB(255, 255, 211, 114); Color primaryRed = const Color(0xffB73E3E); class AppTheme { static init(SetThemeState state, BuildContext context) { _cornerRadius = state.cornerRadius; _readTabFirst = state.readTabFirst; _dividerColor = state.showOutlines ? Theme.of(context).colorScheme.onSurface : Colors.transparent; } } class ThemeGetters { static Color getSelectionColor(BuildContext context) => Theme.of(context).colorScheme.primary.withOpacity(0.4); }
0
mirrored_repositories/openreads/lib/core
mirrored_repositories/openreads/lib/core/helpers/helpers.dart
import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:blurhash/blurhash.dart' as blurhash; import 'package:image_cropper/image_cropper.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; Future generateBlurHash(Uint8List bytes, BuildContext context) async { final blurHashStringTmp = await blurhash.BlurHash.encode( bytes, Constants.blurHashX, Constants.blurHashY, ); if (!context.mounted) return; context.read<EditBookCubit>().setBlurHash(blurHashStringTmp); } DateTime? getLatestFinishDate(Book book) { if (book.readings.isEmpty) return null; final readingsWithFinishDate = book.readings.where((e) => e.finishDate != null); if (readingsWithFinishDate.isEmpty) return null; return readingsWithFinishDate .map((e) => e.finishDate) .reduce((value, element) => value!.isAfter(element!) ? value : element); } DateTime? getLatestStartDate(Book book) { if (book.readings.isEmpty) return null; final readingsWithStartDate = book.readings.where((e) => e.startDate != null); if (readingsWithStartDate.isEmpty) return null; return readingsWithStartDate .map((e) => e.startDate) .reduce((value, element) => value!.isAfter(element!) ? value : element); } Future<CroppedFile?> cropImage(BuildContext context, Uint8List cover) async { final colorScheme = Theme.of(context).colorScheme; //write temporary file as ImageCropper requires a file final tmpCoverTimestamp = DateTime.now().millisecondsSinceEpoch; final tmpCoverFile = File( '${appTempDirectory.path}/$tmpCoverTimestamp.jpg', ); await tmpCoverFile.writeAsBytes(cover); return await ImageCropper().cropImage( maxWidth: 1024, maxHeight: 1024, sourcePath: tmpCoverFile.path, compressQuality: 90, uiSettings: [ AndroidUiSettings( toolbarTitle: LocaleKeys.edit_cover.tr(), toolbarColor: Colors.black, statusBarColor: Colors.black, toolbarWidgetColor: Colors.white, backgroundColor: colorScheme.surface, cropGridColor: Colors.black87, activeControlsWidgetColor: colorScheme.primary, cropFrameColor: Colors.black87, lockAspectRatio: false, hideBottomControls: false, ), IOSUiSettings( title: LocaleKeys.edit_cover.tr(), cancelButtonTitle: LocaleKeys.cancel.tr(), doneButtonTitle: LocaleKeys.save.tr(), rotateButtonsHidden: false, rotateClockwiseButtonHidden: true, aspectRatioPickerButtonHidden: false, aspectRatioLockDimensionSwapEnabled: false, ), ], ); }
0
mirrored_repositories/openreads/lib/core
mirrored_repositories/openreads/lib/core/helpers/old_android_http_overrides.dart
import 'dart:io'; class OldAndroidHttpOverrides extends HttpOverrides { @override HttpClient createHttpClient(SecurityContext? context) { return super.createHttpClient(context) ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; } }
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/csv_import_openreads.dart
import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:csv/csv.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/helpers/backup/backup.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/main.dart'; class CSVImportOpenreads { static importCSVLegacyStorage(BuildContext context) async { try { final csvPath = await BackupGeneral.openFilePicker( context, allowedExtensions: ['.csv'], ); if (csvPath == null) return; final csvBytes = await File(csvPath).readAsBytes(); // ignore: use_build_context_synchronously final books = await _parseCSV(context, csvBytes); final importedBooksIDs = await bookCubit.importAdditionalBooks(books); // ignore: use_build_context_synchronously BackupGeneral.showRestoreMissingCoversDialog( bookIDs: importedBooksIDs, context: context, ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future importCSV(BuildContext context) async { try { final csvBytes = await BackupGeneral.pickFileAndGetContent(); if (csvBytes == null) return; // ignore: use_build_context_synchronously final books = await _parseCSV(context, csvBytes); final importedBooksIDs = await bookCubit.importAdditionalBooks(books); // ignore: use_build_context_synchronously BackupGeneral.showRestoreMissingCoversDialog( bookIDs: importedBooksIDs, context: context, ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future<List<Book>> _parseCSV( BuildContext context, Uint8List csvBytes, ) async { final books = List<Book>.empty(growable: true); final csvString = utf8.decode(csvBytes); final csv = const CsvToListConverter().convert(csvString, eol: '\r\n'); for (var i = 0; i < csv.length; i++) { // Skip first row with headers if (i == 0) continue; // ignore: use_build_context_synchronously final book = _parseBook(context, i, csv); if (book != null) { books.add(book); } } return books; } static Book? _parseBook(BuildContext context, int i, List<List> csv) { if (!context.mounted) return null; try { return Book( title: _getField(i, csv, 'title'), subtitle: _getField(i, csv, 'subtitle'), author: _getField(i, csv, 'author'), description: _getField(i, csv, 'description'), status: _getStatus(i, csv), favourite: _getBoolField(i, csv, 'favourite'), deleted: _getBoolField(i, csv, 'deleted'), rating: _getRating(i, csv), pages: _getPages(i, csv), publicationYear: _getPublicationYear(i, csv), isbn: _getISBN(i, csv), olid: _getOLID(i, csv), tags: _getTags(i, csv), myReview: _getField(i, csv, 'my_review'), notes: _getField(i, csv, 'notes'), bookFormat: _getBookFormat(i, csv), readings: _getReadingDates(i, csv), dateAdded: _getDate(i, csv, 'date_added') ?? DateTime.now(), dateModified: _getDate(i, csv, 'date_modified') ?? DateTime.now(), ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); return null; } } static String? _getISBN(int i, List<List<dynamic>> csv) { final isbn = csv[i][csv[0].indexOf('isbn')].toString(); if (isbn.isNotEmpty) { return isbn; } else { return null; } } static String? _getOLID(int i, List<List<dynamic>> csv) { final olid = csv[i][csv[0].indexOf('olid')].toString(); if (olid.isNotEmpty) { return olid; } else { return null; } } static String _getField(int i, List<List<dynamic>> csv, String field) { return csv[i][csv[0].indexOf(field)].toString(); } static bool _getBoolField(int i, List<List<dynamic>> csv, String field) { return csv[i][csv[0].indexOf(field)].toString() == 'true'; } static List<Reading> _getReadingDates( int i, List<List<dynamic>> csv, ) { List<Reading> readingsList = List<Reading>.empty(growable: true); final index = csv[0].indexOf('readings'); if (index == -1) { return readingsList; } final readingsListString = csv[i][index].toString(); final List<String> readingStrings = readingsListString.split(';'); if (readingStrings.isEmpty) { return readingsList; } readingsList = List<Reading>.from( readingStrings.map((e) { final reading = Reading.fromString(e); if (reading.startDate == null && reading.finishDate == null && reading.customReadingTime == null) { return null; } else { return reading; } }).where((reading) => reading != null), ); return readingsList; } static int? _getRating(int i, List<List<dynamic>> csv) { final rating = double.tryParse( csv[i][csv[0].indexOf('rating')].toString(), ); if (rating == null) { return null; } else { return (rating * 10).toInt(); } } static int? _getPages(int i, List<List<dynamic>> csv) { final pagesField = csv[i][csv[0].indexOf('pages')].toString(); return pagesField.isNotEmpty ? int.tryParse(pagesField) : null; } static int? _getPublicationYear(int i, List<List<dynamic>> csv) { final publicationYearField = csv[i][csv[0].indexOf('publication_year')].toString(); return publicationYearField.isNotEmpty ? int.tryParse(publicationYearField) : null; } static BookStatus _getStatus(int i, List<List<dynamic>> csv) { final statusField = csv[i][csv[0].indexOf('status')].toString(); return statusField == 'in_progress' ? BookStatus.inProgress : statusField == 'planned' ? BookStatus.forLater : statusField == 'abandoned' ? BookStatus.unfinished : BookStatus.read; } static String? _getTags(int i, List<List<dynamic>> csv) { final bookselvesField = csv[i][csv[0].indexOf('tags')].toString(); if (bookselvesField.isNotEmpty) { return bookselvesField; } else { return null; } } static DateTime? _getDate(int i, List<List<dynamic>> csv, String field) { final dateReadField = csv[i][csv[0].indexOf(field)].toString(); DateTime? dateRead; if (dateReadField.isNotEmpty) { try { dateRead = DateTime.parse(dateReadField); } catch (e) { dateRead = null; } } return dateRead; } static BookFormat _getBookFormat(int i, List<List<dynamic>> csv) { final bookFormat = csv[i][csv[0].indexOf('book_format')].toString(); if (bookFormat == 'paperback') { return BookFormat.paperback; } else if (bookFormat == 'hardcover') { return BookFormat.hardcover; } else if (bookFormat == 'ebook') { return BookFormat.ebook; } else if (bookFormat == 'audiobook') { return BookFormat.audiobook; } else { return BookFormat.paperback; } } }
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/csv_export.dart
import 'dart:convert'; import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:csv/csv.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:shared_storage/shared_storage.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/helpers/backup/backup.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/main.dart'; class CSVExport { static exportCSVLegacyStorage(BuildContext context) async { final csv = await _prepareCSVExport(); if (csv == null) return; // ignore: use_build_context_synchronously final exportPath = await BackupGeneral.openFolderPicker(context); if (exportPath == null) return; final fileName = await _prepareCSVExportFileName(); final filePath = '$exportPath/$fileName'; try { createFileAsBytes( Uri(path: filePath), mimeType: 'text/csv', displayName: fileName, bytes: Uint8List.fromList(utf8.encode(csv)), ); BackupGeneral.showInfoSnackbar(LocaleKeys.export_successful.tr()); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future exportCSV() async { final csvString = await _prepareCSVExport(); if (csvString == null) return; final csv = Uint8List.fromList(utf8.encode(csvString)); final fileName = await _prepareCSVExportFileName(); try { if (Platform.isAndroid) { final selectedUriDir = await openDocumentTree(); if (selectedUriDir == null) return; createFileAsBytes( selectedUriDir, mimeType: 'text/csv', displayName: fileName, bytes: csv, ); } else if (Platform.isIOS) { String? selectedDirectory = await FilePicker.platform.getDirectoryPath(); if (selectedDirectory == null) return; File('$selectedDirectory/$fileName').writeAsBytesSync(csv); } BackupGeneral.showInfoSnackbar(LocaleKeys.export_successful.tr()); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future<String?> _prepareCSVExport() async { try { await bookCubit.getAllBooks(getAuthors: false, getTags: false); final books = await bookCubit.allBooks.first; final rows = List<List<String>>.empty(growable: true); final firstRow = [ ('title'), ('subtitle'), ('author'), ('description'), ('status'), ('favourite'), ('deleted'), ('rating'), ('pages'), ('publication_year'), ('isbn'), ('olid'), ('tags'), ('my_review'), ('notes'), ('book_format'), ('readings'), ('date_added'), ('date_modified'), ]; rows.add(firstRow); for (var book in books) { final newRow = List<String>.empty(growable: true); newRow.add(book.title); newRow.add(book.subtitle ?? ''); newRow.add(book.author); newRow.add(book.description ?? ''); newRow.add( book.status == BookStatus.read ? 'finished' : book.status == BookStatus.inProgress ? 'in_progress' : book.status == BookStatus.forLater ? 'planned' : book.status == BookStatus.unfinished ? 'abandoned' : 'unknown', ); newRow.add(book.favourite.toString()); newRow.add(book.deleted.toString()); newRow.add(book.rating != null ? (book.rating! / 10).toString() : ''); newRow.add(book.pages != null ? book.pages.toString() : ''); newRow.add(book.publicationYear != null ? book.publicationYear.toString() : ''); newRow.add(book.isbn ?? ''); newRow.add(book.olid ?? ''); newRow.add(book.tags ?? ''); newRow.add(book.myReview ?? ''); newRow.add(book.notes ?? ''); newRow.add(book.bookFormat == BookFormat.paperback ? 'paperback' : book.bookFormat == BookFormat.hardcover ? 'hardcover' : book.bookFormat == BookFormat.ebook ? 'ebook' : book.bookFormat == BookFormat.audiobook ? 'audiobook' : ''); newRow.add( book.readings.isNotEmpty ? book.readings.map((reading) => reading.toString()).join(';') : '', ); newRow.add(book.dateAdded.toIso8601String()); newRow.add(book.dateModified.toIso8601String()); rows.add(newRow); } return const ListToCsvConverter().convert( rows, textDelimiter: '"', textEndDelimiter: '"', ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); return null; } } static Future<String> _prepareCSVExportFileName() async { final date = DateTime.now(); final exportDate = '${date.year}_${date.month}_${date.day}-${date.hour}_${date.minute}_${date.second}'; return 'Openreads-$exportDate.csv'; } }
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/backup_import.dart
import 'dart:convert'; import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:archive/archive_io.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/logic/cubit/backup_progress_cubit.dart'; import 'package:openreads/ui/books_screen/books_screen.dart'; import 'package:shared_storage/shared_storage.dart'; import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart' as path; import 'package:blurhash_dart/blurhash_dart.dart' as blurhash_dart; import 'package:image/image.dart' as img; import 'package:openreads/core/helpers/backup/backup.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/challenge_bloc/challenge_bloc.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/book_from_backup_v3.dart'; import 'package:openreads/model/year_from_backup_v3.dart'; import 'package:openreads/model/yearly_challenge.dart'; class BackupImport { static restoreLocalBackupLegacyStorage(BuildContext context) async { final tmpDir = appTempDirectory.absolute; _deleteTmpData(tmpDir); try { final archivePath = await BackupGeneral.openFilePicker(context); if (archivePath == null) return; if (archivePath.contains('Openreads-4-')) { // ignore: use_build_context_synchronously await _restoreBackupVersion4( context, archivePath: archivePath, tmpPath: tmpDir, ); } else if (archivePath.contains('openreads_3_')) { // ignore: use_build_context_synchronously await _restoreBackupVersion3( context, archivePath: archivePath, tmpPath: tmpDir, ); } else { // Because file name is not always possible to read // backups v5 is recognized by the info.txt file final infoFileVersion = _checkInfoFileVersion(File(archivePath).readAsBytesSync(), tmpDir); if (infoFileVersion == 5) { // ignore: use_build_context_synchronously await _restoreBackupVersion5( context, File(archivePath).readAsBytesSync(), tmpDir, ); } else { BackupGeneral.showInfoSnackbar(LocaleKeys.backup_not_valid.tr()); return; } } BackupGeneral.showInfoSnackbar(LocaleKeys.restore_successfull.tr()); if (context.mounted) { Navigator.of(context).pop(); Navigator.of(context).pop(); } } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future restoreLocalBackup(BuildContext context) async { final tmpDir = appTempDirectory.absolute; _deleteTmpData(tmpDir); Uint8List? backupFile; Uri? fileLocation; if (Platform.isAndroid) { fileLocation = await BackupGeneral.pickFileAndroid(); if (fileLocation != null) { backupFile = await getDocumentContent(fileLocation); } } else if (Platform.isIOS) { FilePickerResult? result = await FilePicker.platform.pickFiles(); if (result != null) { File file = File(result.files.single.path!); backupFile = file.readAsBytesSync(); fileLocation = file.uri; } } else { return; } if (backupFile == null || fileLocation == null) { return; } // Backups v3 and v4 are recognized by their file name if (fileLocation.path.contains('Openreads-4-')) { // ignore: use_build_context_synchronously await _restoreBackupVersion4( context, archiveFile: backupFile, tmpPath: tmpDir, ); } else if (fileLocation.path.contains('openreads_3_')) { // ignore: use_build_context_synchronously await _restoreBackupVersion3( context, archiveFile: backupFile, tmpPath: tmpDir, ); } else { // Because file name is not always possible to read // backups v5 is recognized by the info.txt file final infoFileVersion = _checkInfoFileVersion(backupFile, tmpDir); if (infoFileVersion == 5) { // ignore: use_build_context_synchronously await _restoreBackupVersion5(context, backupFile, tmpDir); } else { BackupGeneral.showInfoSnackbar(LocaleKeys.backup_not_valid.tr()); return; } } BackupGeneral.showInfoSnackbar(LocaleKeys.restore_successfull.tr()); if (context.mounted) { Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => const BooksScreen()), (Route<dynamic> route) => false, ); } } static _restoreBackupVersion5( BuildContext context, Uint8List? archiveBytes, Directory tmpPath, ) async { if (archiveBytes == null) { return; } final archive = ZipDecoder().decodeBytes(archiveBytes); extractArchiveToDisk(archive, tmpPath.path); var booksData = File('${tmpPath.path}/books.backup').readAsStringSync(); // First backups of v2 used ||||| as separation between books, // That caused problems because this is as well a separator for tags // Now @@@@@ is a separator for books but some backups may need below line booksData = booksData.replaceAll('}|||||{', '}@@@@@{'); final bookStrings = booksData.split('@@@@@'); await bookCubit.removeAllBooks(); for (var bookString in bookStrings) { try { final newBook = Book.fromJSON(jsonDecode(bookString)); File? coverFile; if (newBook.hasCover) { coverFile = File('${tmpPath.path}/${newBook.id}.jpg'); // Making sure cover is not stored in the Book object newBook.cover = null; } bookCubit.addBook( newBook, refreshBooks: false, cover: coverFile?.readAsBytesSync(), ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } bookCubit.getAllBooksByStatus(); bookCubit.getAllBooks(); // No changes in challenges since v4 so we can use the v4 method // ignore: use_build_context_synchronously await _restoreChallengeTargetsV4(context, tmpPath); } static _restoreBackupVersion4( BuildContext context, { String? archivePath, Uint8List? archiveFile, required Directory tmpPath, }) async { late Uint8List archiveBytes; if (archivePath != null) { archiveBytes = File(archivePath).readAsBytesSync(); } else if (archiveFile != null) { archiveBytes = archiveFile; } else { return; } final archive = ZipDecoder().decodeBytes(archiveBytes); extractArchiveToDisk(archive, tmpPath.path); var booksData = File('${tmpPath.path}/books.backup').readAsStringSync(); // First backups of v2 used ||||| as separation between books, // That caused problems because this is as well a separator for tags // Now @@@@@ is a separator for books but some backups may need below line booksData = booksData.replaceAll('}|||||{', '}@@@@@{'); final books = booksData.split('@@@@@'); final booksCount = books.length; int restoredBooks = 0; context .read<BackupProgressCubit>() .updateString('$restoredBooks/$booksCount ${LocaleKeys.restored.tr()}'); await bookCubit.removeAllBooks(); for (var book in books) { try { final newBook = Book.fromJSON(jsonDecode(book)); Uint8List? cover; if (newBook.cover != null) { cover = newBook.cover; newBook.hasCover = true; newBook.cover = null; } bookCubit.addBook( newBook, refreshBooks: false, cover: cover, ); restoredBooks++; // ignore: use_build_context_synchronously context.read<BackupProgressCubit>().updateString( '$restoredBooks/$booksCount ${LocaleKeys.restored.tr()}'); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } await Future.delayed(const Duration(milliseconds: 500)); bookCubit.getAllBooksByStatus(); bookCubit.getAllBooks(); // ignore: use_build_context_synchronously await _restoreChallengeTargetsV4(context, tmpPath); } static _restoreBackupVersion3( BuildContext context, { String? archivePath, Uint8List? archiveFile, required Directory tmpPath, }) async { late Uint8List archiveBytes; try { if (archivePath != null) { archiveBytes = File(archivePath).readAsBytesSync(); } else if (archiveFile != null) { archiveBytes = archiveFile; } else { return; } final archive = ZipDecoder().decodeBytes(archiveBytes); extractArchiveToDisk(archive, tmpPath.path); final booksDB = await openDatabase(path.join(tmpPath.path, 'books.sql')); final result = await booksDB.query("Book"); final List<BookFromBackupV3> books = result.isNotEmpty ? result.map((item) => BookFromBackupV3.fromJson(item)).toList() : []; final booksCount = books.length; int restoredBooks = 0; // ignore: use_build_context_synchronously context.read<BackupProgressCubit>().updateString( '$restoredBooks/$booksCount ${LocaleKeys.restored.tr()}'); await bookCubit.removeAllBooks(); for (var book in books) { // ignore: use_build_context_synchronously await _addBookFromBackupV3(context, book); restoredBooks += 1; // ignore: use_build_context_synchronously context.read<BackupProgressCubit>().updateString( '$restoredBooks/$booksCount ${LocaleKeys.restored.tr()}'); } bookCubit.getAllBooksByStatus(); bookCubit.getAllBooks(); // ignore: use_build_context_synchronously await _restoreChallengeTargetsFromBackup3(context, tmpPath); await Future.delayed(const Duration(seconds: 2)); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static _restoreChallengeTargetsFromBackup3( BuildContext context, Directory tmpPath) async { if (!context.mounted) return; if (!File(path.join(tmpPath.path, 'years.sql')).existsSync()) return; final booksDB = await openDatabase(path.join(tmpPath.path, 'years.sql')); final result = await booksDB.query("Year"); final List<YearFromBackupV3>? years = result.isNotEmpty ? result.map((item) => YearFromBackupV3.fromJson(item)).toList() : null; if (!context.mounted) return; BlocProvider.of<ChallengeBloc>(context).add( const RemoveAllChallengesEvent(), ); String newChallenges = ''; if (years == null) return; for (var year in years) { if (newChallenges.isEmpty) { if (year.year != null) { final newJson = json .encode(YearlyChallenge( year: int.parse(year.year!), books: year.yearChallengeBooks, pages: year.yearChallengePages, ).toJSON()) .toString(); newChallenges = [ newJson, ].join('|||||'); } } else { final splittedNewChallenges = newChallenges.split('|||||'); final newJson = json .encode(YearlyChallenge( year: int.parse(year.year!), books: year.yearChallengeBooks, pages: year.yearChallengePages, ).toJSON()) .toString(); splittedNewChallenges.add(newJson); newChallenges = splittedNewChallenges.join('|||||'); } } BlocProvider.of<ChallengeBloc>(context).add( RestoreChallengesEvent( challenges: newChallenges, ), ); } static Future<void> _addBookFromBackupV3( BuildContext context, BookFromBackupV3 book) async { final blurHash = await compute(_generateBlurHash, book.bookCoverImg); final newBook = Book.fromBookFromBackupV3(book, blurHash); Uint8List? cover; if (newBook.cover != null) { cover = newBook.cover; newBook.hasCover = true; newBook.cover = null; } bookCubit.addBook( newBook, refreshBooks: false, cover: cover, ); } static String? _generateBlurHash(Uint8List? cover) { if (cover == null) return null; return blurhash_dart.BlurHash.encode( img.decodeImage(cover)!, numCompX: Constants.blurHashX, numCompY: Constants.blurHashY, ).hash; } static _restoreChallengeTargetsV4( BuildContext context, Directory tmpPath, ) async { if (!context.mounted) return; if (File('${tmpPath.path}/challenges.backup').existsSync()) { final challengesData = File('${tmpPath.path}/challenges.backup').readAsStringSync(); BlocProvider.of<ChallengeBloc>(context).add( const RemoveAllChallengesEvent(), ); BlocProvider.of<ChallengeBloc>(context).add( RestoreChallengesEvent( challenges: challengesData, ), ); } else { BlocProvider.of<ChallengeBloc>(context).add( const RemoveAllChallengesEvent(), ); } } // Open the info.txt file and check the backup version static int? _checkInfoFileVersion(Uint8List? backupFile, Directory tmpDir) { if (backupFile == null) return null; final archive = ZipDecoder().decodeBytes(backupFile); extractArchiveToDisk(archive, tmpDir.path); final infoFile = File('${tmpDir.path}/info.txt'); if (!infoFile.existsSync()) return null; final infoFileContent = infoFile.readAsStringSync(); final infoFileContentSplitted = infoFileContent.split('\n'); if (infoFileContentSplitted.isEmpty) return null; final infoFileVersion = infoFileContentSplitted[1].split(': ')[1]; return int.tryParse(infoFileVersion); } static _deleteTmpData(Directory tmpDir) { if (File('${tmpDir.path}/books.backup').existsSync()) { File('${tmpDir.path}/books.backup').deleteSync(); } if (File('${tmpDir.path}/challenges.backup').existsSync()) { File('${tmpDir.path}/challenges.backup').deleteSync(); } } }
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/csv_import_goodreads.dart
import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:csv/csv.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/helpers/backup/backup.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/main.dart'; class CSVImportGoodreads { static importCSVLegacyStorage(BuildContext context) async { try { final csvPath = await BackupGeneral.openFilePicker( context, allowedExtensions: ['.csv'], ); if (csvPath == null) return; final csvBytes = await File(csvPath).readAsBytes(); // ignore: use_build_context_synchronously final books = await _parseCSV(context, csvBytes); final importedBooksIDs = await bookCubit.importAdditionalBooks(books); // ignore: use_build_context_synchronously BackupGeneral.showRestoreMissingCoversDialog( bookIDs: importedBooksIDs, context: context, ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future importCSV(BuildContext context) async { try { final csvBytes = await BackupGeneral.pickFileAndGetContent(); if (csvBytes == null) return; // ignore: use_build_context_synchronously final books = await _parseCSV(context, csvBytes); final importedBooksIDs = await bookCubit.importAdditionalBooks(books); // ignore: use_build_context_synchronously BackupGeneral.showRestoreMissingCoversDialog( bookIDs: importedBooksIDs, context: context, ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future<List<Book>> _parseCSV( BuildContext context, Uint8List csvBytes, ) async { final books = List<Book>.empty(growable: true); final csvString = utf8.decode(csvBytes); final csv = const CsvToListConverter().convert(csvString, eol: '\n'); final headers = csv[0]; // Get propositions for which exclusive shelf is "not finished" final notFinishedShelfPropositions = _getNotFinishedShelfPropositions(csv); String? notFinishedShelf; // If there is only one proposition for "not finished" shelf // and it is one of the most popular ones, then use it notFinishedShelf = _getDefaultNotFinishedShelf( notFinishedShelfPropositions, ); // show dialog to choose which shelf is "not finished" if (notFinishedShelfPropositions.isNotEmpty && notFinishedShelf == null) { notFinishedShelf = await _askUserForNotFinshedShelf( context, notFinishedShelfPropositions, ); } for (var i = 0; i < csv.length; i++) { // Skip first row with headers if (i == 0) continue; // ignore: use_build_context_synchronously final book = _parseBook( context, i, csv: csv, headers: headers, notFinishedShelf: notFinishedShelf, ); if (book != null) { books.add(book); } } return books; } static List<String> _getNotFinishedShelfPropositions( List<List<dynamic>> csv, ) { final headers = csv[0]; final notFinishedShelfPropositions = List<String>.empty(growable: true); for (var i = 0; i < csv.length; i++) { if (i == 0) continue; final exclusiveShelf = csv[i][headers.indexOf('Exclusive Shelf')]; // If the exclusive shelf is one of the default ones, then skip if (exclusiveShelf == "read" || exclusiveShelf == "currently-reading" || exclusiveShelf == "to-read") { continue; } if (!notFinishedShelfPropositions.contains(exclusiveShelf)) { notFinishedShelfPropositions.add(exclusiveShelf); } } return notFinishedShelfPropositions; } static String? _getDefaultNotFinishedShelf( List<String> notFinishedShelfPropositions, ) { if (notFinishedShelfPropositions.length == 1) { if (notFinishedShelfPropositions[0] == 'abandoned') { return 'abandoned'; } else if (notFinishedShelfPropositions[0] == 'did-not-finish') { return 'did-not-finish'; } } return null; } static Future<String?> _askUserForNotFinshedShelf( BuildContext context, List<String> notFinishedShelfPropositions, ) async { if (!context.mounted) return null; return await showDialog<String>( context: context, builder: (context) { return AlertDialog( title: Text( LocaleKeys.choose_not_finished_shelf.tr(), ), content: SingleChildScrollView( child: ListBody( children: notFinishedShelfPropositions .map( (e) => ListTile( title: Text(e), onTap: () => Navigator.of(context).pop(e), ), ) .toList(), ), ), ); }, ); } static Book? _parseBook( BuildContext context, int i, { required List<List> csv, required List headers, required String? notFinishedShelf, }) { if (!context.mounted) return null; try { return Book( title: _getTitle(i, csv, headers), author: _getAuthor(i, csv, headers), isbn: _getISBN(i, csv, headers), rating: _getRating(i, csv, headers), pages: _getPages(i, csv, headers), publicationYear: _getPublicationYear(i, csv, headers), myReview: _getMyReview(i, csv, headers), status: _getStatus(i, csv, headers, notFinishedShelf: notFinishedShelf), tags: _getTags(i, csv, headers, notFinishedShelf: notFinishedShelf), readings: _getReadingDates(i, csv, headers), bookFormat: _getBookFormat(i, csv, headers), dateAdded: _getDateAdded(i, csv, headers), dateModified: DateTime.now(), ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); return null; } } static String? _getISBN(int i, List<List<dynamic>> csv, List headers) { // Example ISBN fields: // ="0300259360" // ="" final isbn10 = csv[i][headers.indexOf('ISBN')] .toString() .replaceAll("\"", "") .replaceAll("=", ""); // Example ISBN13 fields: // ="9780300259360" // ="" final isbn13 = csv[i][headers.indexOf('ISBN13')] .toString() .replaceAll("\"", "") .replaceAll("=", ""); if (isbn13.isNotEmpty) { return isbn13; } else if (isbn10.isNotEmpty) { return isbn10; } else { return null; } } static String _getAuthor(int i, List<List<dynamic>> csv, List headers) { String author = csv[i][headers.indexOf('Author')].toString(); if (csv[i][headers.indexOf('Additional Authors')].toString().isNotEmpty) { author += ', ${csv[i][headers.indexOf('Additional Authors')]}'; } return author; } static String _getTitle(int i, List<List<dynamic>> csv, List headers) { return csv[i][headers.indexOf('Title')].toString(); } static int? _getRating(int i, List<List<dynamic>> csv, List headers) { // Example My Rating fields: // 0 // 5 final rating = int.parse( csv[i][headers.indexOf('My Rating')].toString(), ) * 10; return rating != 0 ? rating : null; } static int? _getPages(int i, List<List<dynamic>> csv, List headers) { // Example Number of Pages fields: // 336 final pagesField = csv[i][headers.indexOf('Number of Pages')].toString(); return pagesField.isNotEmpty ? int.parse(pagesField) : null; } static int? _getPublicationYear( int i, List<List<dynamic>> csv, List headers) { // Example Year Published fields: // 2021 final publicationYearField = csv[i][headers.indexOf('Year Published')].toString(); return publicationYearField.isNotEmpty ? int.parse(publicationYearField) : null; } static String? _getMyReview(int i, List<List<dynamic>> csv, List headers) { // Example My Review fields: // https://example.com/some_url // Lorem ipsum dolor sit amet final myReview = csv[i][headers.indexOf('My Review')].toString(); return myReview.isNotEmpty ? myReview : null; } static BookStatus _getStatus( int i, List<List<dynamic>> csv, List headers, { String? notFinishedShelf, }) { // Default Exclusive Shelf fields: // read // currently-reading // to-read // Custom Exclusive Shelf fields: // abandoned // did-not-finish final exclusiveShelfField = csv[i][headers.indexOf('Exclusive Shelf')].toString(); return exclusiveShelfField == 'currently-reading' ? BookStatus.inProgress : exclusiveShelfField == 'to-read' ? BookStatus.forLater : notFinishedShelf != null && exclusiveShelfField == notFinishedShelf ? BookStatus.unfinished : BookStatus.read; } static String? _getTags( int i, List<List<dynamic>> csv, List headers, { String? notFinishedShelf, }) { // Example Bookshelves fields: // read // currently-reading // to-read // lorem ipsum final bookselvesField = csv[i][headers.indexOf('Bookshelves')].toString(); List<String>? bookshelves = bookselvesField.isNotEmpty ? bookselvesField.split(',').map((e) => e.trim()).toList() : null; if (bookshelves != null) { if (bookshelves.contains('read')) { bookshelves.remove('read'); } if (bookshelves.contains('currently-reading')) { bookshelves.remove('currently-reading'); } if (bookshelves.contains('to-read')) { bookshelves.remove('to-read'); } if (notFinishedShelf != null && bookshelves.contains(notFinishedShelf)) { bookshelves.remove(notFinishedShelf); } if (bookshelves.isEmpty) { bookshelves = null; } } return bookshelves?.join('|||||'); } static List<Reading> _getReadingDates( int i, List<List<dynamic>> csv, List headers) { // Example Date Read fields: // 2021/04/06 // 2022/04/27 final dateReadField = csv[i][headers.indexOf('Date Read')].toString(); final readingDates = List<Reading>.empty(growable: true); if (dateReadField.isNotEmpty) { final splittedDate = dateReadField.split('/'); if (splittedDate.length == 3) { final year = int.parse(splittedDate[0]); final month = int.parse(splittedDate[1]); final day = int.parse(splittedDate[2]); final dateRead = DateTime(year, month, day); readingDates.add(Reading(startDate: dateRead)); } } return readingDates; } static DateTime _getDateAdded(int i, List<List<dynamic>> csv, List headers) { // Example Date Added fields: // 2021/04/06 // 2022/04/27 final dateReadField = csv[i][headers.indexOf('Date Added')].toString(); if (dateReadField.isNotEmpty) { final splittedDate = dateReadField.split('/'); if (splittedDate.length == 3) { final year = int.parse(splittedDate[0]); final month = int.parse(splittedDate[1]); final day = int.parse(splittedDate[2]); return DateTime(year, month, day); } } return DateTime.now(); } static BookFormat _getBookFormat( int i, List<List<dynamic>> csv, List headers) { // Example Binding fields: // Audible Audio // Audio Cassette // Audio CD // Audiobook // Board Book // Chapbook // ebook // Hardcover // Kindle Edition // Mass Market Paperback // Nook // Paperback final bindingField = csv[i][headers.indexOf('Binding')].toString(); late BookFormat bookFormat; if (bindingField == 'Audible Audio' || bindingField == 'Audio Cassette' || bindingField == 'Audio CD' || bindingField == 'Audiobook') { bookFormat = BookFormat.audiobook; } else if (bindingField == 'Kindle Edition' || bindingField == 'Nook' || bindingField == 'ebook') { bookFormat = BookFormat.ebook; } else if (bindingField == 'Mass Market Paperback' || bindingField == 'Paperback' || bindingField == 'Chapbook') { bookFormat = BookFormat.paperback; } else if (bindingField == 'Hardcover' || bindingField == 'Board Book') { bookFormat = BookFormat.hardcover; } else { bookFormat = BookFormat.paperback; } return bookFormat; } }
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/backup.dart
export 'backup_export.dart'; export 'backup_general.dart'; export 'backup_import.dart'; export 'csv_export.dart'; export 'csv_import_goodreads.dart'; export 'csv_import_openreads.dart'; export 'csv_import_bookwyrm.dart';
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/csv_import_bookwyrm.dart
import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:csv/csv.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/helpers/backup/backup.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/main.dart'; class CSVImportBookwyrm { static importCSVLegacyStorage(BuildContext context) async { try { final csvPath = await BackupGeneral.openFilePicker( context, allowedExtensions: ['.csv'], ); if (csvPath == null) return; final csvBytes = await File(csvPath).readAsBytes(); // ignore: use_build_context_synchronously final books = await _parseCSV(context, csvBytes); final importedBooksIDs = await bookCubit.importAdditionalBooks(books); // ignore: use_build_context_synchronously BackupGeneral.showRestoreMissingCoversDialog( bookIDs: importedBooksIDs, context: context, ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future importCSV(BuildContext context) async { try { final csvBytes = await BackupGeneral.pickFileAndGetContent(); if (csvBytes == null) return; // ignore: use_build_context_synchronously final books = await _parseCSV(context, csvBytes); final importedBooksIDs = await bookCubit.importAdditionalBooks(books); // ignore: use_build_context_synchronously BackupGeneral.showRestoreMissingCoversDialog( bookIDs: importedBooksIDs, context: context, ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future<List<Book>> _parseCSV( BuildContext context, Uint8List csvBytes, ) async { final books = List<Book>.empty(growable: true); final csvString = utf8.decode(csvBytes); final csv = const CsvToListConverter().convert(csvString, eol: '\r\n'); for (var i = 0; i < csv.length; i++) { // Skip first row with headers if (i == 0) continue; // ignore: use_build_context_synchronously final book = _parseBook( context, i, csv, ); if (book != null) { books.add(book); } } return books; } static Book? _parseBook( BuildContext context, int i, List<List> csv, ) { if (!context.mounted) return null; try { return Book( title: _getTitle(i, csv), author: _getAuthor(i, csv), isbn: _getISBN(i, csv), olid: _getOLID(i, csv), rating: _getRating(i, csv), myReview: _getMyReview(i, csv), status: BookStatus.read, readings: List<Reading>.empty(growable: true), dateAdded: DateTime.now(), dateModified: DateTime.now(), ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); return null; } } static String? _getISBN(int i, List<List<dynamic>> csv) { // Example isbn_10 fields: // 1848872275 // 067088040X final isbn10 = csv[i][csv[0].indexOf('isbn_10')].toString(); // Example isbn_13 fields: // 9780670880409 final isbn13 = csv[i][csv[0].indexOf('isbn_13')].toString(); if (isbn13.isNotEmpty) { return isbn13; } else if (isbn10.isNotEmpty) { return isbn10; } else { return null; } } static String? _getOLID(int i, List<List<dynamic>> csv) { // Example openlibrary_key fields: // OL32367826M final olid = csv[i][csv[0].indexOf('openlibrary_key')].toString(); return olid.isNotEmpty ? olid : null; } static String _getAuthor(int i, List<List<dynamic>> csv) { String author = csv[i][csv[0].indexOf('author_text')].toString(); return author; } static String _getTitle(int i, List<List<dynamic>> csv) { return csv[i][csv[0].indexOf('title')].toString(); } static int? _getRating(int i, List<List<dynamic>> csv) { // Example rating fields: // 0 // 5 final rating = int.tryParse( csv[i][csv[0].indexOf('rating')].toString(), ); return rating != null && rating != 0 ? rating * 10 : null; } static String? _getMyReview(int i, List<List<dynamic>> csv) { final myReview = csv[i][csv[0].indexOf('review_content')].toString(); return myReview.isNotEmpty ? myReview : null; } }
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/backup_general.dart
import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:filesystem_picker/filesystem_picker.dart'; import 'package:openreads/main.dart'; import 'package:openreads/ui/books_screen/books_screen.dart'; import 'package:openreads/ui/settings_screen/download_missing_covers_screen.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:shared_storage/shared_storage.dart'; class BackupGeneral { static showInfoSnackbar(String message) { final snackBar = SnackBar(content: Text(message)); snackbarKey.currentState?.showSnackBar(snackBar); } static Future<bool> requestStoragePermission(BuildContext context) async { if (await Permission.storage.isPermanentlyDenied) { // ignore: use_build_context_synchronously _openSystemSettings(context); return false; } else if (await Permission.storage.status.isDenied) { if (await Permission.storage.request().isGranted) { return true; } else { // ignore: use_build_context_synchronously _openSystemSettings(context); return false; } } else if (await Permission.storage.status.isGranted) { return true; } return false; } static Future<String?> openFolderPicker(BuildContext context) async { if (!context.mounted) return null; return await FilesystemPicker.open( context: context, title: LocaleKeys.choose_backup_folder.tr(), pickText: LocaleKeys.save_file_to_this_folder.tr(), fsType: FilesystemType.folder, rootDirectory: Directory('/storage/emulated/0/'), contextActions: [ FilesystemPickerNewFolderContextAction( icon: Icon( Icons.create_new_folder, color: Theme.of(context).colorScheme.primary, size: 24, ), ), ], theme: FilesystemPickerTheme( backgroundColor: Theme.of(context).colorScheme.surface, pickerAction: FilesystemPickerActionThemeData( foregroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(context).colorScheme.surface, ), fileList: FilesystemPickerFileListThemeData( iconSize: 24, upIconSize: 24, checkIconSize: 24, folderTextStyle: const TextStyle(fontSize: 16), ), topBar: FilesystemPickerTopBarThemeData( backgroundColor: Theme.of(context).colorScheme.surface, titleTextStyle: const TextStyle(fontSize: 18), elevation: 0, shadowColor: Colors.transparent, ), ), ); } static Future<String?> openFilePicker( BuildContext context, { List<String> allowedExtensions = const ['.backup', '.zip', '.png'], }) async { if (!context.mounted) return null; return await FilesystemPicker.open( context: context, title: LocaleKeys.choose_backup_file.tr(), pickText: LocaleKeys.use_this_file.tr(), fsType: FilesystemType.file, rootDirectory: Directory('/storage/emulated/0/'), fileTileSelectMode: FileTileSelectMode.wholeTile, allowedExtensions: allowedExtensions, theme: FilesystemPickerTheme( backgroundColor: Theme.of(context).colorScheme.surface, fileList: FilesystemPickerFileListThemeData( iconSize: 24, upIconSize: 24, checkIconSize: 24, folderTextStyle: const TextStyle(fontSize: 16), ), topBar: FilesystemPickerTopBarThemeData( titleTextStyle: const TextStyle(fontSize: 18), shadowColor: Colors.transparent, foregroundColor: Theme.of(context).colorScheme.onSurface, ), ), ); } static _openSystemSettings(BuildContext context) { if (!context.mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( LocaleKeys.need_storage_permission.tr(), ), action: SnackBarAction( label: LocaleKeys.open_settings.tr(), onPressed: () { if (context.mounted) { openAppSettings(); } }, ), ), ); } static Future<Uri?> pickFileAndroid() async { final selectedUris = await openDocument(multiple: false); if (selectedUris == null || selectedUris.isEmpty) return null; return selectedUris[0]; } static Future<Uint8List?> pickFileAndGetContent() async { if (Platform.isAndroid) { final fileLocation = await pickFileAndroid(); if (fileLocation != null) { return await getDocumentContent(fileLocation); } } else if (Platform.isIOS) { FilePickerResult? result = await FilePicker.platform.pickFiles(); if (result != null) { File file = File(result.files.single.path!); return file.readAsBytesSync(); } } return null; } static void showRestoreMissingCoversDialog({ required BuildContext context, required List<int> bookIDs, }) { showDialog( context: context, builder: (context) { return Builder(builder: (context) { return AlertDialog( title: Text( LocaleKeys.import_successful.tr(), ), content: Text(LocaleKeys.try_downloading_covers.tr()), actionsAlignment: MainAxisAlignment.spaceBetween, actions: [ FilledButton.tonal( onPressed: () { Navigator.of(context).pop(); Navigator.push( context, MaterialPageRoute( builder: (context) => DownloadMissingCoversScreen( bookIDs: bookIDs, ), ), ); }, child: Text(LocaleKeys.yes.tr()), ), FilledButton.tonal( onPressed: () { Navigator.of(context).pop(); Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => const BooksScreen(), ), (route) => false, ); }, child: Text(LocaleKeys.no.tr()), ), ], ); }); }, ); } }
0
mirrored_repositories/openreads/lib/core/helpers
mirrored_repositories/openreads/lib/core/helpers/backup/backup_export.dart
import 'dart:convert'; import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:archive/archive.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:shared_storage/shared_storage.dart'; import 'package:openreads/core/helpers/backup/backup.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/challenge_bloc/challenge_bloc.dart'; import 'package:openreads/main.dart'; class BackupExport { static createLocalBackupLegacyStorage(BuildContext context) async { final tmpBackupPath = await prepareTemporaryBackup(context); if (tmpBackupPath == null) return; try { // ignore: use_build_context_synchronously final backupPath = await BackupGeneral.openFolderPicker(context); final fileName = await _prepareBackupFileName(); final filePath = '$backupPath/$fileName'; File(filePath).writeAsBytesSync(File(tmpBackupPath).readAsBytesSync()); BackupGeneral.showInfoSnackbar(LocaleKeys.backup_successfull.tr()); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future createLocalBackup(BuildContext context) async { final tmpBackupPath = await prepareTemporaryBackup(context); if (tmpBackupPath == null) return; final fileName = await _prepareBackupFileName(); try { if (Platform.isAndroid) { final selectedUriDir = await openDocumentTree(); if (selectedUriDir == null) { return; } createFileAsBytes( selectedUriDir, mimeType: '', displayName: fileName, bytes: File(tmpBackupPath).readAsBytesSync(), ); } else if (Platform.isIOS) { String? selectedDirectory = await FilePicker.platform.getDirectoryPath(); if (selectedDirectory == null) return; File('$selectedDirectory/$fileName').writeAsBytesSync( File(tmpBackupPath).readAsBytesSync(), ); } BackupGeneral.showInfoSnackbar(LocaleKeys.backup_successfull.tr()); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); } } static Future<String?> prepareTemporaryBackup(BuildContext context) async { try { await bookCubit.getAllBooks(getTags: false, getAuthors: false); final books = await bookCubit.allBooks.first; final listOfBookJSONs = List<String>.empty(growable: true); final coverFiles = List<File>.empty(growable: true); for (var book in books) { // Making sure no covers are stored as JSON final bookWithCoverNull = book.copyWithNullCover(); listOfBookJSONs.add(jsonEncode(bookWithCoverNull.toJSON())); // Creating a list of current cover files if (book.hasCover) { // Check if cover file exists, if not then skip if (!File('${appDocumentsDirectory.path}/${book.id}.jpg') .existsSync()) { continue; } final coverFile = File( '${appDocumentsDirectory.path}/${book.id}.jpg', ); coverFiles.add(coverFile); } await Future.delayed(const Duration(milliseconds: 50)); } // ignore: use_build_context_synchronously final challengeTargets = await _getChallengeTargets(context); // ignore: use_build_context_synchronously return await _writeTempBackupFile( listOfBookJSONs, challengeTargets, coverFiles, ); } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); return null; } } static Future<String?> _getChallengeTargets(BuildContext context) async { if (!context.mounted) return null; final state = BlocProvider.of<ChallengeBloc>(context).state; if (state is SetChallengeState) { return state.yearlyChallenges; } return null; } // Current backup version: 5 static Future<String?> _writeTempBackupFile( List<String> listOfBookJSONs, String? challengeTargets, List<File>? coverFiles, ) async { final data = listOfBookJSONs.join('@@@@@'); final fileName = await _prepareBackupFileName(); final tmpFilePath = '${appTempDirectory.path}/$fileName'; try { // Saving books to temp file File('${appTempDirectory.path}/books.backup').writeAsStringSync(data); // Reading books temp file to memory final booksBytes = File('${appTempDirectory.path}/books.backup').readAsBytesSync(); final archivedBooks = ArchiveFile( 'books.backup', booksBytes.length, booksBytes, ); // Prepare main archive final archive = Archive(); archive.addFile(archivedBooks); if (challengeTargets != null) { // Saving challenges to temp file File('${appTempDirectory.path}/challenges.backup') .writeAsStringSync(challengeTargets); // Reading challenges temp file to memory final challengeTargetsBytes = File('${appTempDirectory.path}/challenges.backup') .readAsBytesSync(); final archivedChallengeTargets = ArchiveFile( 'challenges.backup', challengeTargetsBytes.length, challengeTargetsBytes, ); archive.addFile(archivedChallengeTargets); } // Adding covers to the backup file if (coverFiles != null && coverFiles.isNotEmpty) { for (var coverFile in coverFiles) { final coverBytes = coverFile.readAsBytesSync(); final archivedCover = ArchiveFile( coverFile.path.split('/').last, coverBytes.length, coverBytes, ); archive.addFile(archivedCover); } } // Add info file final info = await _prepareBackupInfo(); final infoBytes = utf8.encode(info); final archivedInfo = ArchiveFile( 'info.txt', infoBytes.length, infoBytes, ); archive.addFile(archivedInfo); final encodedArchive = ZipEncoder().encode(archive); if (encodedArchive == null) return null; File(tmpFilePath).writeAsBytesSync(encodedArchive); return tmpFilePath; } catch (e) { BackupGeneral.showInfoSnackbar(e.toString()); return null; } } static Future<String> _getAppVersion() async { PackageInfo packageInfo = await PackageInfo.fromPlatform(); return packageInfo.version; } static Future<String> _prepareBackupFileName() async { final date = DateTime.now(); final backupDate = '${date.year}_${date.month}_${date.day}-${date.hour}_${date.minute}_${date.second}'; return 'Openreads-$backupDate.backup'; } static Future<String> _prepareBackupInfo() async { final appVersion = await _getAppVersion(); return 'App version: $appVersion\nBackup version: 5'; } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/challenge_bloc/challenge_event.dart
part of 'challenge_bloc.dart'; abstract class ChallengeEvent extends Equatable { const ChallengeEvent(); } class ChangeChallengeEvent extends ChallengeEvent { final int year; final int? books; final int? pages; const ChangeChallengeEvent({ required this.year, required this.books, required this.pages, }); @override List<Object?> get props => [year, books, pages]; } class RestoreChallengesEvent extends ChallengeEvent { final String? challenges; const RestoreChallengesEvent({ required this.challenges, }); @override List<Object?> get props => [challenges]; } class RemoveAllChallengesEvent extends ChallengeEvent { const RemoveAllChallengesEvent(); @override List<Object?> get props => []; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/challenge_bloc/challenge_state.dart
part of 'challenge_bloc.dart'; abstract class ChallengeState extends Equatable { const ChallengeState(); } class SetChallengeState extends ChallengeState { final String? yearlyChallenges; const SetChallengeState({ this.yearlyChallenges, }); @override List<Object?> get props => [yearlyChallenges]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/challenge_bloc/challenge_bloc.dart
import 'dart:convert'; import 'package:equatable/equatable.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:openreads/model/yearly_challenge.dart'; part 'challenge_state.dart'; part 'challenge_event.dart'; class ChallengeBloc extends HydratedBloc<ChallengeEvent, ChallengeState> { String? _yearlyChallenges; ChallengeBloc() : super(const SetChallengeState()) { on<RemoveAllChallengesEvent>((event, emit) { _yearlyChallenges = null; emit(SetChallengeState(yearlyChallenges: _yearlyChallenges)); }); on<RestoreChallengesEvent>((event, emit) { _yearlyChallenges = event.challenges; emit(SetChallengeState(yearlyChallenges: _yearlyChallenges)); }); on<ChangeChallengeEvent>((event, emit) { if (_yearlyChallenges == null) { final newJson = json .encode(YearlyChallenge( year: event.year, books: event.books, pages: event.pages, ).toJSON()) .toString(); _yearlyChallenges = [ newJson, ].join('|||||'); } else { final splittedReadingChallenges = _yearlyChallenges!.split('|||||'); splittedReadingChallenges.removeWhere((element) { final decodedReadingChallenge = YearlyChallenge.fromJSON( jsonDecode(element), ); return decodedReadingChallenge.year == event.year; }); splittedReadingChallenges.add(json .encode(YearlyChallenge( year: event.year, books: event.books, pages: event.pages, ).toJSON()) .toString()); _yearlyChallenges = splittedReadingChallenges.join('|||||'); } emit(SetChallengeState(yearlyChallenges: _yearlyChallenges)); }); } @override ChallengeState? fromJson(Map<String, dynamic> json) { final yearlyChallenges = json['reading_challenges'] as String?; _yearlyChallenges = yearlyChallenges; return SetChallengeState( yearlyChallenges: _yearlyChallenges, ); } @override Map<String, dynamic>? toJson(ChallengeState state) { if (state is SetChallengeState) { return { 'reading_challenges': state.yearlyChallenges, }; } else { return { 'reading_challenges': null, }; } } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/welcome_bloc/welcome_bloc.dart
import 'package:equatable/equatable.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; part 'welcome_state.dart'; part 'welcome_event.dart'; class WelcomeBloc extends HydratedBloc<WelcomeEvent, WelcomeState> { WelcomeBloc() : super(ShowWelcomeState()) { on<ChangeWelcomeEvent>((event, emit) { if (event.showWelcome) { emit(ShowWelcomeState()); } else { emit(HideWelcomeState()); } }); } @override WelcomeState? fromJson(Map<String, dynamic> json) { final storedValue = json['welcome_state'] as int; switch (storedValue) { case 0: return HideWelcomeState(); default: return ShowWelcomeState(); } } @override Map<String, dynamic>? toJson(WelcomeState state) { if (state is ShowWelcomeState) { return {'welcome_state': 1}; } else { return {'welcome_state': 0}; } } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/welcome_bloc/welcome_event.dart
part of 'welcome_bloc.dart'; abstract class WelcomeEvent extends Equatable { const WelcomeEvent(); } class ChangeWelcomeEvent extends WelcomeEvent { const ChangeWelcomeEvent(this.showWelcome); final bool showWelcome; @override List<Object?> get props => [showWelcome]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/welcome_bloc/welcome_state.dart
part of 'welcome_bloc.dart'; abstract class WelcomeState extends Equatable { const WelcomeState(); } class ShowWelcomeState extends WelcomeState { @override List<Object> get props => []; } class HideWelcomeState extends WelcomeState { @override List<Object> get props => []; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/theme_bloc/theme_state.dart
part of 'theme_bloc.dart'; abstract class ThemeState extends Equatable { const ThemeState(); } class ChangingThemeState extends ThemeState { const ChangingThemeState(); @override List<Object?> get props => []; } class SetThemeState extends ThemeState { final ThemeMode themeMode; final bool showOutlines; final double cornerRadius; final Color primaryColor; final String? fontFamily; final bool readTabFirst; final bool useMaterialYou; final bool amoledDark; const SetThemeState({ required this.themeMode, required this.showOutlines, required this.cornerRadius, required this.primaryColor, required this.fontFamily, required this.readTabFirst, required this.useMaterialYou, required this.amoledDark, }); SetThemeState copyWith({ ThemeMode? themeMode, bool? showOutlines, double? cornerRadius, Color? primaryColor, String? fontFamily, bool? readTabFirst, bool? useMaterialYou, bool? amoledDark, }) { return SetThemeState( themeMode: themeMode ?? this.themeMode, showOutlines: showOutlines ?? this.showOutlines, cornerRadius: cornerRadius ?? this.cornerRadius, primaryColor: primaryColor ?? this.primaryColor, fontFamily: fontFamily ?? this.fontFamily, readTabFirst: readTabFirst ?? this.readTabFirst, useMaterialYou: useMaterialYou ?? this.useMaterialYou, amoledDark: amoledDark ?? this.amoledDark, ); } @override List<Object?> get props => [ themeMode, showOutlines, cornerRadius, primaryColor, fontFamily, readTabFirst, useMaterialYou, amoledDark, ]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/theme_bloc/theme_bloc.dart
import 'dart:io'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; part 'theme_state.dart'; part 'theme_event.dart'; class ThemeBloc extends HydratedBloc<ThemeEvent, ThemeState> { String? fontFamily = 'Nunito'; ThemeBloc() : super(SetThemeState( themeMode: ThemeMode.system, showOutlines: false, cornerRadius: 5, primaryColor: const Color(0xff3FA796), fontFamily: 'Nunito', readTabFirst: true, useMaterialYou: Platform.isAndroid ? true : false, amoledDark: false, )) { on<ChangeThemeEvent>((event, emit) { fontFamily = event.fontFamily; emit(const ChangingThemeState()); emit(SetThemeState( themeMode: event.themeMode, showOutlines: event.showOutlines, cornerRadius: event.cornerRadius, primaryColor: event.primaryColor, fontFamily: fontFamily, readTabFirst: event.readTabFirst, useMaterialYou: event.useMaterialYou, amoledDark: event.amoledDark, )); }); on<ChangeAccentEvent>((event, emit) { if (state is SetThemeState) { final themeState = state as SetThemeState; emit(const ChangingThemeState()); emit(themeState.copyWith( primaryColor: event.primaryColor, useMaterialYou: event.useMaterialYou, )); } }); } @override ThemeState? fromJson(Map<String, dynamic> json) { final themeState = json['theme_state'] as int?; final showOutlines = json['show_outlines'] as bool?; final cornerRadius = json['corner_radius'] as double?; final primaryColor = json['primary_color'] as int?; final fontFamily = json['font_family'] as String?; final readTabFirst = json['read_tab_first'] as bool?; final useMaterialYou = json['use_material_you'] as bool?; final amoledDark = json['amoled_dark'] as bool?; switch (themeState) { case 1: return SetThemeState( themeMode: ThemeMode.light, showOutlines: showOutlines ?? false, cornerRadius: cornerRadius ?? 5, primaryColor: Color(primaryColor ?? 0xff2146C7), fontFamily: fontFamily ?? 'Nunito', readTabFirst: readTabFirst ?? true, useMaterialYou: useMaterialYou ?? true, amoledDark: amoledDark ?? false, ); case 2: return SetThemeState( themeMode: ThemeMode.dark, showOutlines: showOutlines ?? false, cornerRadius: cornerRadius ?? 5, primaryColor: Color(primaryColor ?? 0xff2146C7), fontFamily: fontFamily ?? 'Nunito', readTabFirst: readTabFirst ?? true, useMaterialYou: useMaterialYou ?? true, amoledDark: amoledDark ?? false, ); default: return SetThemeState( themeMode: ThemeMode.system, showOutlines: showOutlines ?? false, cornerRadius: cornerRadius ?? 5, primaryColor: Color(primaryColor ?? 0xff2146C7), fontFamily: fontFamily ?? 'Nunito', readTabFirst: readTabFirst ?? true, useMaterialYou: useMaterialYou ?? true, amoledDark: amoledDark ?? false, ); } } @override Map<String, dynamic>? toJson(ThemeState state) { if (state is SetThemeState) { switch (state.themeMode) { case ThemeMode.light: return { 'theme_state': 1, 'show_outlines': state.showOutlines, 'corner_radius': state.cornerRadius, 'primary_color': state.primaryColor.value, 'font_family': state.fontFamily, 'read_tab_first': state.readTabFirst, 'use_material_you': state.useMaterialYou, 'amoled_dark': state.amoledDark, }; case ThemeMode.dark: return { 'theme_state': 2, 'show_outlines': state.showOutlines, 'corner_radius': state.cornerRadius, 'primary_color': state.primaryColor.value, 'font_family': state.fontFamily, 'read_tab_first': state.readTabFirst, 'use_material_you': state.useMaterialYou, 'amoled_dark': state.amoledDark, }; case ThemeMode.system: return { 'theme_state': 0, 'show_outlines': state.showOutlines, 'corner_radius': state.cornerRadius, 'primary_color': state.primaryColor.value, 'font_family': state.fontFamily, 'read_tab_first': state.readTabFirst, 'use_material_you': state.useMaterialYou, 'amoled_dark': state.amoledDark, }; } } else { return { 'theme_state': 0, 'show_outlines': false, 'corner_radius': 5, 'primary_color': null, 'font_family': null, 'read_tab_first': null, 'use_material_you': null, 'locale': null, 'amoled_dark': false, }; } } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/theme_bloc/theme_event.dart
part of 'theme_bloc.dart'; abstract class ThemeEvent extends Equatable { const ThemeEvent(); } class ChangeThemeEvent extends ThemeEvent { final ThemeMode themeMode; final bool showOutlines; final double cornerRadius; final Color primaryColor; final String? fontFamily; final bool readTabFirst; final bool useMaterialYou; final bool amoledDark; const ChangeThemeEvent({ required this.themeMode, required this.showOutlines, required this.cornerRadius, required this.primaryColor, required this.fontFamily, required this.readTabFirst, required this.useMaterialYou, required this.amoledDark, }); @override List<Object?> get props => [ themeMode, showOutlines, cornerRadius, primaryColor, fontFamily, readTabFirst, useMaterialYou, amoledDark, ]; } class ChangeAccentEvent extends ThemeEvent { final Color? primaryColor; final bool useMaterialYou; const ChangeAccentEvent({ required this.primaryColor, required this.useMaterialYou, }); @override List<Object?> get props => [ primaryColor, useMaterialYou, ]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/open_lib_bloc/open_lib_state.dart
part of 'open_lib_bloc.dart'; abstract class OpenLibState extends Equatable { const OpenLibState(); } class OpenLibReadyState extends OpenLibState { @override List<Object> get props => []; } class OpenLibLoadingState extends OpenLibState { @override List<Object> get props => []; } class OpenLibLoadedState extends OpenLibState { final List<OLSearchResultDoc>? docs; final int? numFound; final bool? numFoundExact; const OpenLibLoadedState(this.docs, this.numFound, this.numFoundExact); @override List<Object?> get props => [docs, numFound, numFoundExact]; } class OpenLibNoInternetState extends OpenLibState { @override List<Object?> get props => []; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/open_lib_bloc/open_lib_bloc.dart
import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/resources/connectivity_service.dart'; import 'package:openreads/resources/open_library_service.dart'; import 'package:openreads/model/ol_search_result.dart'; part 'open_lib_event.dart'; part 'open_lib_state.dart'; class OpenLibBloc extends Bloc<OpenLibEvent, OpenLibState> { final OpenLibraryService _openLibraryService; final ConnectivityService _connectivityService; OpenLibBloc( this._openLibraryService, this._connectivityService, ) : super(OpenLibLoadingState()) { _connectivityService.connectivityStream.stream.listen((event) { if (event == ConnectivityResult.none) { add(NoInternetEvent()); } else { add(ReadyEvent()); } }); on<LoadApiEvent>((event, emit) async { emit(OpenLibLoadingState()); // final result = await _openLibraryService.getResults( // event.query, // event.offset, // ); // emit(OpenLibLoadedState( // result.docs, // result.numFound, // result.numFoundExact, // )); }); on<ReadyEvent>((event, emit) { emit(OpenLibReadyState()); }); on<NoInternetEvent>((event, emit) { emit(OpenLibNoInternetState()); }); } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/open_lib_bloc/open_lib_event.dart
part of 'open_lib_bloc.dart'; abstract class OpenLibEvent extends Equatable { const OpenLibEvent(); } class LoadApiEvent extends OpenLibEvent { final String query; final int offset; const LoadApiEvent(this.query, this.offset); @override List<Object?> get props => [query]; } class ReadyEvent extends OpenLibEvent { @override List<Object?> get props => []; } class NoInternetEvent extends OpenLibEvent { @override List<Object?> get props => []; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/stats_bloc/stats_event.dart
part of 'stats_bloc.dart'; abstract class StatsEvent extends Equatable { const StatsEvent(); @override List<Object> get props => []; } class StatsLoad extends StatsEvent { final List<Book> books; const StatsLoad( this.books, ); @override List<Object> get props => [books]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/stats_bloc/stats_state.dart
part of 'stats_bloc.dart'; abstract class StatsState extends Equatable { const StatsState(); @override List<Object> get props => []; } class StatsLoading extends StatsState {} class StatsLoaded extends StatsState { final List<int> years; final List<Book> finishedBooks; final List<Book> inProgressBooks; final List<Book> forLaterBooks; final List<Book> unfinishedBooks; final List<BookReadStat> finishedBooksByMonthAllTypes; final List<BookReadStat> finishedBooksByMonthPaperbackBooks; final List<BookReadStat> finishedBooksByMonthHardcoverBooks; final List<BookReadStat> finishedBooksByMonthEbooks; final List<BookReadStat> finishedBooksByMonthAudiobooks; final List<BookReadStat> finishedPagesByMonthAllTypes; final List<BookReadStat> finishedPagesByMonthPaperbackBooks; final List<BookReadStat> finishedPagesByMonthHardcoverBooks; final List<BookReadStat> finishedPagesByMonthEbooks; final List<BookReadStat> finishedPagesByMonthAudiobooks; final int finishedBooksAll; final int finishedPagesAll; final List<BookYearlyStat> averageRating; final List<BookYearlyStat> averagePages; final List<BookYearlyStat> averageReadingTime; final List<BookYearlyStat> longestBook; final List<BookYearlyStat> shortestBook; final List<BookYearlyStat> fastestBook; final List<BookYearlyStat> slowestBook; const StatsLoaded({ required this.years, required this.finishedBooks, required this.inProgressBooks, required this.forLaterBooks, required this.unfinishedBooks, required this.finishedBooksByMonthAllTypes, required this.finishedBooksByMonthPaperbackBooks, required this.finishedBooksByMonthHardcoverBooks, required this.finishedBooksByMonthEbooks, required this.finishedBooksByMonthAudiobooks, required this.finishedPagesByMonthAllTypes, required this.finishedPagesByMonthPaperbackBooks, required this.finishedPagesByMonthHardcoverBooks, required this.finishedPagesByMonthEbooks, required this.finishedPagesByMonthAudiobooks, required this.finishedBooksAll, required this.finishedPagesAll, required this.averageRating, required this.averagePages, required this.averageReadingTime, required this.longestBook, required this.shortestBook, required this.fastestBook, required this.slowestBook, }); @override List<Object> get props => [ years, finishedBooks, inProgressBooks, forLaterBooks, unfinishedBooks, finishedBooksByMonthAllTypes, finishedBooksByMonthPaperbackBooks, finishedBooksByMonthHardcoverBooks, finishedBooksByMonthEbooks, finishedBooksByMonthAudiobooks, finishedPagesByMonthAllTypes, finishedPagesByMonthPaperbackBooks, finishedPagesByMonthHardcoverBooks, finishedPagesByMonthEbooks, finishedPagesByMonthAudiobooks, finishedBooksAll, finishedPagesAll, averageRating, averagePages, averageReadingTime, longestBook, shortestBook, fastestBook, slowestBook, ]; } class StatsError extends StatsState { final String msg; const StatsError( this.msg, ); @override List<Object> get props => [msg]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/stats_bloc/stats_bloc.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/book_read_stat.dart'; import 'package:openreads/model/book_yearly_stat.dart'; import 'package:openreads/model/reading_time.dart'; part 'stats_event.dart'; part 'stats_state.dart'; class StatsBloc extends Bloc<StatsEvent, StatsState> { StatsBloc() : super(StatsLoading()) { on<StatsLoad>((event, emit) { final allBooks = event.books; final finishedBooks = _filterBooksByStatus(allBooks, BookStatus.read); if (finishedBooks.isEmpty) { emit(StatsError(LocaleKeys.add_books_and_come_back.tr())); return; } final years = _calculateYears(finishedBooks); final inProgressBooks = _filterBooksByStatus( allBooks, BookStatus.inProgress, ); final forLaterBooks = _filterBooksByStatus( allBooks, BookStatus.forLater, ); final unfinishedBooks = _filterBooksByStatus( allBooks, BookStatus.unfinished, ); final finishedBooksByMonthAllTypes = _getFinishedBooksByMonth(finishedBooks, null, years); final finishedBooksByMonthPaperbackBooks = _getFinishedBooksByMonth(finishedBooks, BookFormat.paperback, years); final finishedBooksByMonthHardcoverBooks = _getFinishedBooksByMonth(finishedBooks, BookFormat.hardcover, years); final finishedBooksByMonthEbooks = _getFinishedBooksByMonth(finishedBooks, BookFormat.ebook, years); final finishedBooksByMonthAudiobooks = _getFinishedBooksByMonth(finishedBooks, BookFormat.audiobook, years); final finishedPagesByMonthAllTypes = _getFinishedPagesByMonth(finishedBooks, null, years); final finishedPagesByMonthPaperbackBooks = _getFinishedPagesByMonth(finishedBooks, BookFormat.paperback, years); final finishedPagesByMonthHardcoverBooks = _getFinishedPagesByMonth(finishedBooks, BookFormat.hardcover, years); final finishedPagesByMonthEbooks = _getFinishedPagesByMonth(finishedBooks, BookFormat.ebook, years); final finishedPagesByMonthAudiobooks = _getFinishedPagesByMonth(finishedBooks, BookFormat.audiobook, years); final averageRating = _getAverageRating(finishedBooks, years); final averagePages = _getAveragePages(finishedBooks, years); final averageReadingTime = _getAverageReadingTime(finishedBooks, years); final longestBook = _getLongestBook(finishedBooks, years); final shortestBook = _getShortestBook(finishedBooks, years); final fastestBook = _getFastestReadBook(finishedBooks, years); final slowestBook = _getSlowestReadBooks(finishedBooks, years); final allFinishedBooks = _countFinishedBooks(finishedBooks); final allFinishedPages = _countFinishedPages(finishedBooks); emit(StatsLoaded( years: years, finishedBooks: finishedBooks, inProgressBooks: inProgressBooks, forLaterBooks: forLaterBooks, unfinishedBooks: unfinishedBooks, finishedBooksByMonthAllTypes: finishedBooksByMonthAllTypes, finishedBooksByMonthPaperbackBooks: finishedBooksByMonthPaperbackBooks, finishedBooksByMonthHardcoverBooks: finishedBooksByMonthHardcoverBooks, finishedBooksByMonthEbooks: finishedBooksByMonthEbooks, finishedBooksByMonthAudiobooks: finishedBooksByMonthAudiobooks, finishedPagesByMonthAllTypes: finishedPagesByMonthAllTypes, finishedPagesByMonthPaperbackBooks: finishedPagesByMonthPaperbackBooks, finishedPagesByMonthHardcoverBooks: finishedPagesByMonthHardcoverBooks, finishedPagesByMonthEbooks: finishedPagesByMonthEbooks, finishedPagesByMonthAudiobooks: finishedPagesByMonthAudiobooks, finishedBooksAll: allFinishedBooks, finishedPagesAll: allFinishedPages, averageRating: averageRating, averagePages: averagePages, averageReadingTime: averageReadingTime, longestBook: longestBook, shortestBook: shortestBook, fastestBook: fastestBook, slowestBook: slowestBook, )); }); } List<BookYearlyStat> _getSlowestReadBooks(List<Book> books, List<int> years) { List<BookYearlyStat> bookYearlyStats = List<BookYearlyStat>.empty( growable: true, ); // Calculate stats for all time final slowestBook = _getSlowestReadBookInYear(books, null); if (slowestBook != null) { bookYearlyStats.add(slowestBook); } // Calculate stats for each year for (var year in years) { final slowestBookInAYear = _getSlowestReadBookInYear(books, year); if (slowestBookInAYear != null) { bookYearlyStats.add(slowestBookInAYear); } } return bookYearlyStats; } BookYearlyStat? _getSlowestReadBookInYear(List<Book> books, int? year) { int? slowestReadTimeInMs; String? slowestReadBookString; Book? slowestReadBook; for (Book book in books) { int? readTimeInMs; for (final reading in book.readings) { if (year != null && reading.finishDate?.year != year) { continue; } if (reading.customReadingTime != null) { readTimeInMs = reading.customReadingTime!.milliSeconds; } else if (reading.startDate != null && reading.finishDate != null) { // Reading duration should be at least 1 day final readTimeinDays = reading.finishDate!.difference(reading.startDate!).inDays + 1; readTimeInMs = ReadingTime.toMilliSeconds(readTimeinDays, 0, 0).milliSeconds; } else { continue; } if (slowestReadTimeInMs == null) { slowestReadTimeInMs = readTimeInMs; slowestReadBookString = '${book.title} - ${book.author}'; slowestReadBook = book; } else { if (readTimeInMs > slowestReadTimeInMs) { slowestReadTimeInMs = readTimeInMs; slowestReadBookString = '${book.title} - ${book.author}'; slowestReadBook = book; } } } } if (slowestReadTimeInMs == null) { return null; } else { return BookYearlyStat( title: slowestReadBookString, value: ReadingTime.fromMilliSeconds(slowestReadTimeInMs).toString(), year: year, book: slowestReadBook, ); } } List<BookYearlyStat> _getFastestReadBook(List<Book> books, List<int> years) { List<BookYearlyStat> bookYearlyStats = List<BookYearlyStat>.empty( growable: true, ); // Calculate stats for all time final fastestBook = _getFastestReadBookInYear(books, null); if (fastestBook != null) { bookYearlyStats.add(fastestBook); } // Calculate stats for each year for (var year in years) { final fastestBookInAYear = _getFastestReadBookInYear(books, year); if (fastestBookInAYear != null) { bookYearlyStats.add(fastestBookInAYear); } } return bookYearlyStats; } BookYearlyStat? _getFastestReadBookInYear(List<Book> books, int? year) { int? fastestReadTimeInMs; String? fastestReadBookString; Book? fastestReadBook; for (Book book in books) { int? readTimeInMs; for (final reading in book.readings) { if (year != null && reading.finishDate?.year != year) { continue; } if (reading.customReadingTime != null) { readTimeInMs = reading.customReadingTime!.milliSeconds; } else if (reading.startDate != null && reading.finishDate != null) { // Reading duration should be at least 1 day final readTimeinDays = reading.finishDate!.difference(reading.startDate!).inDays + 1; readTimeInMs = ReadingTime.toMilliSeconds(readTimeinDays, 0, 0).milliSeconds; } else { continue; } if (fastestReadTimeInMs == null) { fastestReadTimeInMs = readTimeInMs; fastestReadBookString = '${book.title} - ${book.author}'; fastestReadBook = book; } else { if (readTimeInMs < fastestReadTimeInMs) { fastestReadTimeInMs = readTimeInMs; fastestReadBookString = '${book.title} - ${book.author}'; fastestReadBook = book; } } } } if (fastestReadTimeInMs == null) { return null; } else { return BookYearlyStat( title: fastestReadBookString, value: ReadingTime.fromMilliSeconds(fastestReadTimeInMs).toString(), year: year, book: fastestReadBook, ); } } List<BookYearlyStat> _getShortestBook(List<Book> books, List<int> years) { List<BookYearlyStat> bookYearlyStats = List<BookYearlyStat>.empty( growable: true, ); // Calculate stats for all time final shortestBook = _getShortestBookInYear(books, null); if (shortestBook != null) { bookYearlyStats.add(shortestBook); } // Calculate stats for each year for (var year in years) { final shortestBookInAYear = _getShortestBookInYear(books, year); if (shortestBookInAYear != null) { bookYearlyStats.add(shortestBookInAYear); } } return bookYearlyStats; } BookYearlyStat? _getShortestBookInYear(List<Book> books, int? year) { int? shortestBookPages; String? shortestBookString; Book? shortestBook; for (Book book in books) { if (book.pages == null || book.pages! == 0) continue; if (book.readings.isEmpty) { if (shortestBookPages == null || book.pages! < shortestBookPages) { shortestBookPages = book.pages!; shortestBookString = '${book.title} - ${book.author}'; shortestBook = book; } } else { for (final reading in book.readings) { if (year != null && reading.finishDate?.year != year) { continue; } if (shortestBookPages == null || book.pages! < shortestBookPages) { shortestBookPages = book.pages!; shortestBookString = '${book.title} - ${book.author}'; shortestBook = book; } } } } if (shortestBookPages == null) { return null; } else { return BookYearlyStat( book: shortestBook, title: shortestBookString, value: shortestBookPages.toString(), year: year, ); } } List<BookYearlyStat> _getLongestBook(List<Book> books, List<int> years) { List<BookYearlyStat> bookYearlyStats = List<BookYearlyStat>.empty( growable: true, ); // Calculate stats for all time final longestBook = _getLongestBookInYear(books, null); if (longestBook != null) { bookYearlyStats.add(longestBook); } // Calculate stats for each year for (var year in years) { final longestBookInAYear = _getLongestBookInYear(books, year); if (longestBookInAYear != null) { bookYearlyStats.add(longestBookInAYear); } } return bookYearlyStats; } BookYearlyStat? _getLongestBookInYear(List<Book> books, int? year) { int? longestBookPages; String? longestBookString; Book? longestBook; for (Book book in books) { if (book.pages == null || book.pages! == 0) continue; if (book.readings.isEmpty) { if (longestBookPages == null || book.pages! > longestBookPages) { longestBookPages = book.pages!; longestBookString = '${book.title} - ${book.author}'; longestBook = book; } } else { for (final reading in book.readings) { if (year != null && reading.finishDate?.year != year) { continue; } if (longestBookPages == null || book.pages! > longestBookPages) { longestBookPages = book.pages!; longestBookString = '${book.title} - ${book.author}'; longestBook = book; } } } } if (longestBookPages == null) { return null; } else { return BookYearlyStat( book: longestBook, title: longestBookString, value: longestBookPages.toString(), year: year, ); } } List<BookYearlyStat> _getAverageReadingTime( List<Book> books, List<int> years, ) { List<BookYearlyStat> bookYearlyStats = List<BookYearlyStat>.empty( growable: true, ); // Calculate stats for all time bookYearlyStats.add( BookYearlyStat(value: _getAverageReadingTimeInYear(books, null)), ); // Calculate stats for each year for (var year in years) { final averageReadingTimeInAYear = _getAverageReadingTimeInYear( books, year, ); bookYearlyStats.add( BookYearlyStat( year: year, value: averageReadingTimeInAYear, ), ); } return bookYearlyStats; } String _getAverageReadingTimeInYear(List<Book> books, int? year) { int readTimeInMilliSeconds = 0; int countedBooks = 0; for (Book book in books) { for (final reading in book.readings) { if (year != null && reading.finishDate?.year != year) { continue; } if (reading.customReadingTime != null) { readTimeInMilliSeconds += reading.customReadingTime!.milliSeconds; countedBooks += 1; } else if (reading.startDate != null && reading.finishDate != null) { // Reading duration should be at least 1 day final readTimeinDays = reading.finishDate!.difference(reading.startDate!).inDays + 1; final timeDifference = ReadingTime.toMilliSeconds(readTimeinDays, 0, 0).milliSeconds; readTimeInMilliSeconds += timeDifference; countedBooks += 1; } } } if (readTimeInMilliSeconds == 0 || countedBooks == 0) { return ''; } else { int avgTime = readTimeInMilliSeconds ~/ countedBooks; return ReadingTime.fromMilliSeconds(avgTime).toString(); } } List<BookYearlyStat> _getAveragePages(List<Book> books, List<int> years) { List<BookYearlyStat> bookYearlyStats = List<BookYearlyStat>.empty( growable: true, ); // Calculate stats for all time bookYearlyStats.add( BookYearlyStat(value: _getAveragePagesInYear(books, null)), ); // Calculate stats for each year for (var year in years) { bookYearlyStats.add( BookYearlyStat( year: year, value: _getAveragePagesInYear(books, year), ), ); } return bookYearlyStats; } String _getAveragePagesInYear(List<Book> books, int? year) { int finishedPages = 0; int countedBooks = 0; for (Book book in books) { if (book.pages == null) continue; if (book.readings.isEmpty) { finishedPages += book.pages!; countedBooks += 1; } else { for (final reading in book.readings) { if (year != null && reading.finishDate?.year != year) { continue; } finishedPages += book.pages!; countedBooks += 1; } } } if (countedBooks == 0) { return '0'; } else { return (finishedPages / countedBooks).toStringAsFixed(0); } } List<BookYearlyStat> _getAverageRating(List<Book> books, List<int> years) { List<BookYearlyStat> bookYearlyStats = List<BookYearlyStat>.empty( growable: true, ); // Calculate stats for all time bookYearlyStats.add( BookYearlyStat(value: _getAverageRatingInYear(books, null)), ); // Calculate stats for each year for (var year in years) { bookYearlyStats.add( BookYearlyStat( year: year, value: _getAverageRatingInYear(books, year), ), ); } return bookYearlyStats; } String _getAverageRatingInYear(List<Book> books, int? year) { double sumRating = 0; int countedBooks = 0; for (Book book in books) { if (book.rating == null) continue; if (year == null && book.readings.isEmpty) { sumRating += book.rating! / 10; countedBooks += 1; } else { for (final reading in book.readings) { if (year != null && reading.finishDate?.year != year) { continue; } sumRating += book.rating! / 10; countedBooks += 1; } } } if (countedBooks == 0) { return '0'; } else { return (sumRating / countedBooks).toStringAsFixed(1); } } List<BookReadStat> _getFinishedPagesByMonth( List<Book> books, BookFormat? bookType, List<int> years, ) { List<BookReadStat> bookReadStats = List<BookReadStat>.empty(growable: true); // Calculate stats for all time bookReadStats.add( BookReadStat( values: _getFinishedPagesInSpecificMonths(books, bookType, null), ), ); // Calculate stats for each year for (var year in years) { bookReadStats.add( BookReadStat( year: year, values: _getFinishedPagesInSpecificMonths(books, bookType, year), ), ); } return bookReadStats; } List<int> _getFinishedPagesInSpecificMonths( List<Book> books, BookFormat? bookType, int? year, ) { List<int> finishedPagesByMonth = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (Book book in books) { if (bookType != null && book.bookFormat != bookType) { continue; } for (final reading in book.readings) { if (reading.finishDate != null && book.pages != null) { if (year == null || reading.finishDate!.year == year) { final finishMonth = reading.finishDate!.month; finishedPagesByMonth[finishMonth - 1] += book.pages!; } } } } return finishedPagesByMonth; } List<BookReadStat> _getFinishedBooksByMonth( List<Book> books, BookFormat? bookType, List<int> years, ) { List<BookReadStat> bookReadStats = List<BookReadStat>.empty(growable: true); // Calculate stats for all time bookReadStats.add( BookReadStat( values: _getFinishedBooksInSpecificMonths(books, bookType, null), ), ); // Calculate stats for each year for (var year in years) { bookReadStats.add( BookReadStat( year: year, values: _getFinishedBooksInSpecificMonths( books, bookType, year, ), ), ); } return bookReadStats; } List<int> _getFinishedBooksInSpecificMonths( List<Book> books, BookFormat? bookType, int? year, ) { List<int> finishedBooksByMonth = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (Book book in books) { if (bookType != null && book.bookFormat != bookType) { continue; } for (final reading in book.readings) { if (reading.finishDate != null) { if (year == null || reading.finishDate!.year == year) { final finishMonth = reading.finishDate!.month; finishedBooksByMonth[finishMonth - 1] += 1; } } } } return finishedBooksByMonth; } List<Book> _filterBooksByStatus(List<Book> books, BookStatus status) { final filteredBooks = List<Book>.empty(growable: true); for (var book in books) { if (book.status == status) { filteredBooks.add(book); } } return filteredBooks; } int _countFinishedBooks(List<Book> books) { int finishedBooks = 0; for (var book in books) { if (book.readings.isEmpty) { finishedBooks += 1; } else { for (final reading in book.readings) { if (reading.finishDate != null) { finishedBooks += 1; } } } } return finishedBooks; } int _countFinishedPages(List<Book> books) { int finishedPages = 0; for (var book in books) { if (book.pages != null) { if (book.readings.isEmpty) { finishedPages += book.pages!; } else { for (final reading in book.readings) { if (reading.finishDate != null) { finishedPages += book.pages!; } } } } } return finishedPages; } List<int> _calculateYears(List<Book> books) { final years = List<int>.empty(growable: true); for (var book in books) { for (final reading in book.readings) { if (reading.finishDate != null) { final year = reading.finishDate!.year; if (!years.contains(year)) { years.add(year); } } } } // Sorting years in descending order years.sort((a, b) { return b.compareTo(a); }); return years; } }
0