diff --git a/.github/actions/validate-ae/action.yml b/.github/actions/validate-ae/action.yml index a73b6b26..12832947 100644 --- a/.github/actions/validate-ae/action.yml +++ b/.github/actions/validate-ae/action.yml @@ -24,7 +24,7 @@ runs: working-directory: app run: | dart analyze lib - flutter test test/add_instance_flow_test.dart test/instance_serialization_test.dart test/bindery_brand_icon_test.dart + flutter test test/add_instance_flow_test.dart test/instance_serialization_test.dart test/bindery_brand_icon_test.dart test/bindery_library_api_test.dart test/bindery_library_screen_test.dart - if: inputs.suite == 'all' || inputs.suite == 'bindery' shell: bash working-directory: packages/core_models diff --git a/app/lib/src/bindery/library_api.dart b/app/lib/src/bindery/library_api.dart new file mode 100644 index 00000000..fd973d00 --- /dev/null +++ b/app/lib/src/bindery/library_api.dart @@ -0,0 +1,111 @@ +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; + +enum BinderyCollection { + author('Authors'), book('Books'), series('Series'); + const BinderyCollection(this.label); + final String label; +} + +class BinderyItem { + BinderyItem(this.kind, this.data) { + if (data['id'] is! int || title.isEmpty) { + throw const FormatException('Invalid Bindery item'); + } + } + final BinderyCollection kind; + final Map data; + int get id => data['id'] as int; + String field(String key) => data[key] is String ? data[key] as String : ''; + String get title => field(kind == BinderyCollection.author ? 'authorName' : 'title'); + String get image => field('imageUrl'); + String get description => field('description'); + String get subtitle { + if (kind == BinderyCollection.author) { + final stats = data['statistics']; + if (stats is Map) return '${stats['availableBookCount'] ?? 0} / ${stats['bookCount'] ?? 0} books available'; + } + if (kind == BinderyCollection.series) return '${books.length} books'; + final author = data['author']; + return [ + if (author is Map && author['authorName'] is String) author['authorName'], + if (field('mediaType').isNotEmpty) field('mediaType'), + if (field('status').isNotEmpty) field('status'), + if (field('status') == 'wanted' && (field('ebookFilePath').isNotEmpty || field('audiobookFilePath').isNotEmpty)) 'Partly available', + ].join(' • '); + } + List get books { + final rows = data['books']; + if (rows is! List) return []; + return rows.map((row) => kind == BinderyCollection.series && row is Map ? row['book'] : row) + .whereType().map((row) => BinderyItem(BinderyCollection.book, Map.from(row))).toList(); + } +} + +class BinderyPage { + BinderyPage.fromJson(BinderyCollection kind, Object? json) { + if (json is! Map || json['items'] is! List || json['total'] is! int || + json['offset'] is! int || json['limit'] is! int) { + throw const FormatException('Invalid Bindery page'); + } + items = (json['items'] as List).map((row) { + if (row is! Map) throw const FormatException('Invalid Bindery row'); + return BinderyItem(kind, Map.from(row)); + }).toList(); + total = json['total'] as int; + offset = json['offset'] as int; + if (offset < 0 || total < 0 || (json['limit'] as int) <= 0) { + throw const FormatException('Invalid Bindery pagination'); + } + } + late final List items; + late final int total; + late final int offset; + int get nextOffset => offset + items.length; + bool get hasMore => items.isNotEmpty && nextOffset < total; +} + +class BinderyLibraryApi { + BinderyLibraryApi(this.dio); + final Dio dio; + Future list(BinderyCollection kind, {int offset = 0, + String search = '', String status = '', String mediaType = '', String monitored = ''}) async { + final response = await dio.get('api/v1/${kind.name}', queryParameters: { + 'limit': 40, 'offset': offset, + if (kind != BinderyCollection.series && search.isNotEmpty) 'search': search, + if (kind == BinderyCollection.book && status.isNotEmpty) 'status': status, + if (kind == BinderyCollection.book && mediaType.isNotEmpty) 'mediaType': mediaType, + if (kind != BinderyCollection.series && monitored.isNotEmpty) 'monitored': monitored, + }); + final page = BinderyPage.fromJson(kind, response.data); + if (page.offset != offset) throw const FormatException('Unexpected Bindery page offset'); + return page; + } + Future detail(BinderyCollection kind, int id) async { + final response = await dio.get('api/v1/${kind.name}/$id'); + final data = response.data; + if (data is! Map) throw const FormatException('Invalid Bindery detail'); + return BinderyItem(kind, Map.from(data)); + } + // Never send instance credentials to an image provider. Only use the + // configured Bindery server's image proxy, with redirects disabled. + static String? imageReference(String raw) { + final uri = Uri.tryParse(raw); + if (uri == null || raw.isEmpty) return null; + if (!uri.hasScheme && !uri.hasAuthority && uri.path.endsWith('/api/v1/images')) { + return uri.queryParameters['url']; + } + if (uri.scheme == 'https' || uri.scheme == 'http' || uri.scheme == 'bindery-cover') return raw; + return null; + } + Future cover(String raw) async { + final reference = imageReference(raw); + if (reference == null || reference.isEmpty) return null; + final response = await dio.get>('api/v1/images', + queryParameters: {'url': reference}, + options: Options(responseType: ResponseType.bytes, followRedirects: false)); + final bytes = response.data; + return bytes == null || bytes.isEmpty ? null : Uint8List.fromList(bytes); + } +} diff --git a/app/lib/src/screens/bindery_foundation_screen.dart b/app/lib/src/screens/bindery_foundation_screen.dart index 9cf0a470..a8e43c82 100644 --- a/app/lib/src/screens/bindery_foundation_screen.dart +++ b/app/lib/src/screens/bindery_foundation_screen.dart @@ -56,10 +56,6 @@ class BinderyFoundationScreen extends ConsumerWidget { ), ), ), - const Padding( - padding: EdgeInsets.all(16), - child: Text('Library browsing and management are coming in later beta updates.'), - ), ], ); } diff --git a/app/lib/src/screens/bindery_home.dart b/app/lib/src/screens/bindery_home.dart new file mode 100644 index 00000000..9430f72d --- /dev/null +++ b/app/lib/src/screens/bindery_home.dart @@ -0,0 +1,66 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_router/core_router.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; + +import 'bindery_library_screen.dart'; + +/// Only implemented destinations are registered. Future milestones extend +/// this list with Activity, Calendar, Discover and Settings. +class BinderyHome extends StatefulWidget { + const BinderyHome({required this.instance, required this.drawer, super.key}); + final Instance instance; + final Widget drawer; + + @override + State createState() => _BinderyHomeState(); +} + +class _BinderyHomeState extends State { + final _scaffold = GlobalKey(); + int _selected = 0; + + @override + Widget build(BuildContext context) { + final destinations = <({NavigationDestination navigation, Widget body})>[ + ( + navigation: const NavigationDestination( + icon: Icon(Icons.library_books_outlined), + selectedIcon: Icon(Icons.library_books), + label: 'Library', + ), + body: BinderyLibraryScreen(key: ValueKey(widget.instance.id), instance: widget.instance), + ), + ]; + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) { + if (didPop) return; + if (_scaffold.currentState?.isDrawerOpen ?? false) { + _scaffold.currentState!.closeDrawer(); + } else if (_selected != 0) { + setState(() => _selected = 0); + } else { + context.goNamed(AtriumRoutes.dashboardName); + } + }, + child: Scaffold( + key: _scaffold, + drawer: widget.drawer, + drawerEdgeDragWidth: 32, + appBar: AppBar(title: Row(children: [ + Flexible(child: Text(widget.instance.name, overflow: TextOverflow.ellipsis)), + const SizedBox(width: Insets.sm), + const BetaBadge(), + ])), + body: IndexedStack(index: _selected, children: destinations.map((d) => d.body).toList()), + bottomNavigationBar: destinations.length < 2 ? null : NavigationBar( + selectedIndex: _selected, + onDestinationSelected: (index) => setState(() => _selected = index), + destinations: destinations.map((d) => d.navigation).toList(), + ), + ), + ); + } +} diff --git a/app/lib/src/screens/bindery_library_screen.dart b/app/lib/src/screens/bindery_library_screen.dart new file mode 100644 index 00000000..67b450a2 --- /dev/null +++ b/app/lib/src/screens/bindery_library_screen.dart @@ -0,0 +1,259 @@ +import 'dart:typed_data'; + +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:core_networking/core_networking.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../bindery/library_api.dart'; +import 'bindery_foundation_screen.dart'; + +final binderyLibraryApiProvider = FutureProvider.autoDispose.family((ref, instance) async { + final dio = await ref.watch(dioFactoryProvider).create(instance); + ref.onDispose(() => dio.close(force: true)); + return BinderyLibraryApi(dio); +}); + +final _coverProvider = FutureProvider.autoDispose.family((ref, args) async { + final api = await ref.watch(binderyLibraryApiProvider(args.$1).future); + return api.cover(args.$2); +}); + +class _Cover extends ConsumerWidget { + const _Cover(this.instance, this.item, {this.width = 48}); + final Instance instance; + final BinderyItem item; + final double width; + @override + Widget build(BuildContext context, WidgetRef ref) { + final placeholder = Icon(item.kind == BinderyCollection.author ? Icons.person_outline : Icons.menu_book_outlined); + final bytes = item.image.isEmpty ? null : ref.watch(_coverProvider((instance, item.image))).value; + return SizedBox(width: width, height: width * 1.45, child: bytes == null + ? placeholder : Image.memory(bytes, cacheWidth: (width * MediaQuery.devicePixelRatioOf(context)).ceil(), fit: BoxFit.contain, errorBuilder: (context, error, stack) => placeholder)); + } +} + +class BinderyLibraryScreen extends ConsumerStatefulWidget { + const BinderyLibraryScreen({required this.instance, super.key}); + final Instance instance; + @override + ConsumerState createState() => _BinderyLibraryScreenState(); +} + +class _BinderyLibraryScreenState extends ConsumerState { + BinderyCollection _kind = BinderyCollection.author; + final _search = TextEditingController(); + String _status = '', _media = '', _monitored = ''; + int _generation = 0; + int _offset = 0; + String _appliedSearch = ''; + bool _grid = false; + bool _busy = true, _more = false, _failed = false; + List _items = []; + @override + void initState() { + super.initState(); + Future.microtask(() { if (mounted) _load(reset: true); }); + } + @override + void dispose() { + _search.dispose(); + super.dispose(); + } + Future _load({bool reset = false}) async { + if (!reset && _busy) return; + final generation = ++_generation; + setState(() { + _busy = true; + _failed = false; + if (reset) { _items = []; _offset = 0; _more = false; } + }); + final kind = _kind; + final offset = _offset; + if (reset) _appliedSearch = _search.text.trim(); + final search = _appliedSearch; + final status = _status, media = _media, monitored = _monitored; + try { + final api = await ref.read(binderyLibraryApiProvider(widget.instance).future); + final page = await api.list(kind, offset: offset, search: search, status: status, mediaType: media, monitored: monitored); + if (!mounted || generation != _generation) return; + setState(() { + final ids = _items.map((item) => item.id).toSet(); + _items.addAll(page.items.where((item) => ids.add(item.id))); + _offset = page.nextOffset; + _more = page.hasMore; + _busy = false; + }); + } catch (_) { + if (!mounted || generation != _generation) return; + setState(() { _busy = false; _failed = true; }); + } + } + Widget _filter(String label, String value, Map choices, ValueChanged change) => + DropdownButton(value: value, hint: Text(label), + items: choices.entries.map((entry) => DropdownMenuItem(value: entry.key, child: Text(entry.value))).toList(), + onChanged: (next) { if (next != null) { setState(() => change(next)); _load(reset: true); } }); + @override + Widget build(BuildContext context) { + // Keep the authenticated client alive while the library route is visible. + ref.watch(binderyLibraryApiProvider(widget.instance)); + return Column(children: [ + Padding(padding: const EdgeInsets.symmetric(horizontal: 12), child: Row(children: [ + Expanded(child: Text('Library', style: Theme.of(context).textTheme.titleLarge)), + IconButton(tooltip: _grid ? 'Switch to list view' : 'Switch to grid view', icon: Icon(_grid ? Icons.view_list : Icons.grid_view), onPressed: () => setState(() => _grid = !_grid)), + IconButton(tooltip: 'Server status', icon: const Icon(Icons.info_outline), onPressed: () => showModalBottomSheet(context: context, showDragHandle: true, builder: (_) => SizedBox(height: 220, child: BinderyFoundationScreen(instance: widget.instance)))), + IconButton(tooltip: 'Refresh library', onPressed: () => _load(reset: true), icon: const Icon(Icons.refresh)), + ])), + Padding(padding: const EdgeInsets.all(8), child: SegmentedButton( + segments: BinderyCollection.values.map((kind) => ButtonSegment(value: kind, label: Text(kind.label))).toList(), + selected: {_kind}, onSelectionChanged: (values) { + setState(() { _kind = values.first; _search.clear(); _status = ''; _media = ''; _monitored = ''; }); + _load(reset: true); + })), + if (_kind != BinderyCollection.series) ...[ + Padding(padding: const EdgeInsets.symmetric(horizontal: 16), child: SearchBar( + controller: _search, textInputAction: TextInputAction.search, + hintText: 'Search ${_kind.label.toLowerCase()}', + elevation: const WidgetStatePropertyAll(0), + onSubmitted: (_) => _load(reset: true), + trailing: [ + IconButton( + tooltip: 'Search', + icon: const Icon(Icons.search), + onPressed: () => _load(reset: true), + ), + IconButton( + tooltip: 'Clear search', + icon: const Icon(Icons.clear), + onPressed: () { + _search.clear(); + _load(reset: true); + }, + ), + ], + )), + Wrap(spacing: 12, children: [ + if (_kind == BinderyCollection.book) ...[ + _filter('Availability', _status, {'': 'All statuses', 'imported': 'In library', 'wanted': 'Wanted', 'skipped': 'Skipped'}, (v) => _status = v), + _filter('Format', _media, {'': 'All formats', 'ebook': 'Ebook', 'audiobook': 'Audiobook'}, (v) => _media = v), + ], + _filter('Monitoring', _monitored, {'': 'All monitoring', 'true': 'Monitored', 'false': 'Unmonitored'}, (v) => _monitored = v), + ]), + ], + Expanded(child: RefreshIndicator(onRefresh: () => _load(reset: true), child: CustomScrollView( + physics: const AlwaysScrollableScrollPhysics(), + slivers: [ + if (_grid) + SliverPadding(padding: const EdgeInsets.all(12), sliver: SliverGrid( + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 160, childAspectRatio: 0.52, mainAxisSpacing: 8, crossAxisSpacing: 8), + delegate: SliverChildBuilderDelegate((context, index) => _GridItem(instance: widget.instance, item: _items[index]), childCount: _items.length), + )) + else + SliverList(delegate: SliverChildBuilderDelegate((context, index) => _ItemTile(instance: widget.instance, item: _items[index]), childCount: _items.length)), + SliverToBoxAdapter(child: Column(children: [ + if (_busy) const Padding(padding: EdgeInsets.all(24), child: Center(child: CircularProgressIndicator())), + if (_failed) Center(child: TextButton(onPressed: () => _load(reset: _items.isEmpty), child: const Text('Unable to load library. Retry'))), + if (!_busy && !_failed && _items.isEmpty) const Padding(padding: EdgeInsets.all(24), child: EmptyView(icon: Icons.menu_book_outlined, title: 'No results', message: 'Try adjusting your search or filters.')), + if (!_busy && !_failed && _more) Center(child: TextButton(onPressed: _load, child: const Text('Load more'))), + ])), + ], + ))), + ]); + } +} + +class _GridItem extends StatelessWidget { + const _GridItem({required this.instance, required this.item}); + final Instance instance; + final BinderyItem item; + @override + Widget build(BuildContext context) => Card( + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () => Navigator.of(context, rootNavigator: true).push(MaterialPageRoute( + builder: (_) => _DetailScreen(instance: instance, item: item))), + child: Padding(padding: const EdgeInsets.all(8), child: Column(children: [ + Expanded(child: Center(child: _Cover(instance, item, width: 112))), + Text(item.title, maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center), + if (item.subtitle.isNotEmpty) Text(item.subtitle, maxLines: 2, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.bodySmall, textAlign: TextAlign.center), + ])), + ), + ); +} + +class _ItemTile extends StatelessWidget { + const _ItemTile({required this.instance, required this.item}); + final Instance instance; + final BinderyItem item; + @override + Widget build(BuildContext context) => Card( + margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + leading: _Cover(instance, item), + title: Text(item.title, maxLines: 2, overflow: TextOverflow.ellipsis), subtitle: Text(item.subtitle), + trailing: const Icon(Icons.chevron_right), + onTap: () => Navigator.of(context, rootNavigator: true).push(MaterialPageRoute( + builder: (_) => _DetailScreen(instance: instance, item: item))), + )); +} + +final _detailProvider = FutureProvider.autoDispose.family((ref, args) async { + final api = await ref.watch(binderyLibraryApiProvider(args.$1).future); + return api.detail(args.$2, args.$3); +}); + +class _DetailScreen extends ConsumerWidget { + const _DetailScreen({required this.instance, required this.item}); + final Instance instance; + final BinderyItem item; + @override + Widget build(BuildContext context, WidgetRef ref) { + final provider = _detailProvider((instance, item.kind, item.id)); + final detail = ref.watch(provider); + return Scaffold(appBar: AppBar(title: Text(item.title), actions: [ + IconButton(tooltip: 'Refresh details', onPressed: () => ref.invalidate(provider), icon: const Icon(Icons.refresh)), + ]), body: detail.when( + skipLoadingOnRefresh: false, + data: (value) => ListView(padding: const EdgeInsets.all(16), children: [ + Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + ClipRRect(borderRadius: BorderRadius.circular(8), child: _Cover(instance, value, width: 104)), + const SizedBox(width: 16), + Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(value.title, style: Theme.of(context).textTheme.headlineSmall), + const SizedBox(height: 8), + Text(value.subtitle, style: Theme.of(context).textTheme.bodyMedium), + ])), + ]), + const SizedBox(height: 16), + Card(child: Padding(padding: const EdgeInsets.all(16), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Details', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + if (value.data['monitored'] is bool) Text(value.data['monitored'] == true ? 'Monitored' : 'Unmonitored'), + if (value.field('releaseDate').isNotEmpty) Text('Released: ${value.field('releaseDate').split('T').first}'), + if (value.field('language').isNotEmpty) Text('Language: ${value.field('language')}'), + if (value.field('narrator').isNotEmpty) Text('Narrator: ${value.field('narrator')}'), + if (value.kind == BinderyCollection.book) ...[ + Text('Ebook: ${value.field('ebookFilePath').isNotEmpty ? 'Available' : 'No tracked ebook path'}'), + Text('Audiobook: ${value.field('audiobookFilePath').isNotEmpty ? 'Available' : 'No tracked audiobook path'}'), + ], + ]))), + if (value.description.isNotEmpty) ...[ + const SizedBox(height: 16), + Text('Description', style: Theme.of(context).textTheme.titleLarge), + const SizedBox(height: 8), + Text(value.description), + ], + const SizedBox(height: 16), + if (value.kind != BinderyCollection.book) ...[ + Text('Books', style: Theme.of(context).textTheme.titleLarge), + if (value.books.isEmpty) const Text('No linked books'), + for (final book in value.books) _ItemTile(instance: instance, item: book), + ], + ]), + loading: () => const Center(child: CircularProgressIndicator()), + error: (_, __) => Center(child: TextButton(onPressed: () => ref.invalidate(provider), child: const Text('Unable to load details. Retry'))), + )); + } +} diff --git a/app/lib/src/screens/dashboard_screen.dart b/app/lib/src/screens/dashboard_screen.dart index b3cd4693..f2257149 100644 --- a/app/lib/src/screens/dashboard_screen.dart +++ b/app/lib/src/screens/dashboard_screen.dart @@ -12,7 +12,6 @@ import 'package:go_router/go_router.dart'; import '../dashboard/dashboard_board.dart'; import '../health_providers.dart'; -import '../service_icon.dart'; import 'reorder_sidebar_screen.dart'; /// Home screen. Services live in the navigation drawer (the sidebar); the @@ -503,9 +502,7 @@ class _HealthAwareTile extends ConsumerWidget { final Health health = asyncHealth.value ?? Health.unknown; return ServiceTile( instance: instance, - serviceIcon: instance.kind == ServiceKind.bindery - ? Center(child: ServiceIcon(kind: instance.kind)) - : null, + health: health, onTap: () { final GoRouter router = GoRouter.of(context); diff --git a/app/lib/src/screens/service_detail_screen.dart b/app/lib/src/screens/service_detail_screen.dart index 4d1791c2..c08633dd 100644 --- a/app/lib/src/screens/service_detail_screen.dart +++ b/app/lib/src/screens/service_detail_screen.dart @@ -1,5 +1,5 @@ import 'package:core_models/core_models.dart'; -import 'bindery_foundation_screen.dart'; +import 'bindery_home.dart'; import 'package:core_profile/core_profile.dart'; import 'package:core_ui/core_ui.dart'; import 'package:flutter/material.dart'; @@ -66,6 +66,16 @@ class _ServiceDetailScreenState extends ConsumerState { if (instance == null) { return const _NotFound(); } + if (instance.kind == ServiceKind.bindery) { + return BinderyHome( + key: ValueKey(instance.id), + instance: instance, + drawer: ServicesDrawer( + instances: ref.watch(activeInstancesProvider), + profile: ref.watch(activeProfileProvider), + ), + ); + } if (instance.kind == ServiceKind.sonarr) { return SonarrHome( instance: instance, @@ -417,7 +427,7 @@ class _ServiceDetailScreenState extends ConsumerState { ServiceKind.cleanuparr => const SizedBox.shrink(), // Owns its own scaffold, handled above. ServiceKind.slskd => const SizedBox.shrink(), - ServiceKind.bindery => BinderyFoundationScreen(instance: instance), + ServiceKind.bindery => const SizedBox.shrink(), }; } } diff --git a/app/test/bindery_library_api_test.dart b/app/test/bindery_library_api_test.dart new file mode 100644 index 00000000..645ea65e --- /dev/null +++ b/app/test/bindery_library_api_test.dart @@ -0,0 +1,62 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import '../lib/src/bindery/library_api.dart'; + +void main() { + test('list sends pagination and supported filters to configured server', () async { + final dio = Dio(BaseOptions(baseUrl: 'https://bindery.example/base/', headers: {'X-Api-Key': 'test-key'})); + addTearDown(() => dio.close()); + dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) { + expect(options.uri.path, '/base/api/v1/book'); + expect(options.headers['X-Api-Key'], 'test-key'); + expect(options.queryParameters, {'limit': 40, 'offset': 40, 'search': 'test', 'status': 'wanted', 'mediaType': 'ebook', 'monitored': 'true'}); + handler.resolve(Response(requestOptions: options, data: {'items': [], 'total': 40, 'offset': 40, 'limit': 40}, statusCode: 200)); + })); + final page = await BinderyLibraryApi(dio).list(BinderyCollection.book, offset: 40, search: 'test', status: 'wanted', mediaType: 'ebook', monitored: 'true'); + expect(page.hasMore, isFalse); + }); + test('cover request stays on configured server and disables redirects', () async { + final dio = Dio(BaseOptions(baseUrl: 'https://bindery.example/base/', headers: {'X-Api-Key': 'test-key'})); + addTearDown(() => dio.close()); + dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) { + expect(options.uri.host, 'bindery.example'); + expect(options.uri.path, '/base/api/v1/images'); + expect(options.queryParameters['url'], 'https://external.example/cover.jpg'); + expect(options.followRedirects, isFalse); + expect(options.headers['X-Api-Key'], 'test-key'); + handler.resolve(Response>(requestOptions: options, data: [1, 2, 3], statusCode: 200)); + })); + expect(await BinderyLibraryApi(dio).cover('https://external.example/cover.jpg'), [1, 2, 3]); + }); + test('wanted book with a tracked format is partly available', () { + final book = BinderyItem(BinderyCollection.book, {'id': 1, 'title': 'Book', 'status': 'wanted', 'ebookFilePath': '/books/book.epub'}); + expect(book.subtitle, contains('Partly available')); + }); + test('author pagination uses returned offset and count', () { + final page = BinderyPage.fromJson(BinderyCollection.author, { + 'items': [{'id': 1, 'authorName': 'Author', 'statistics': {'bookCount': 5, 'availableBookCount': 2}}], + 'total': 3, 'offset': 1, 'limit': 1, + }); + expect(page.nextOffset, 2); + expect(page.hasMore, isTrue); + expect(page.items.single.subtitle, '2 / 5 books available'); + }); + test('empty and malformed pages', () { + expect(BinderyPage.fromJson(BinderyCollection.book, {'items': [], 'total': 0, 'offset': 0, 'limit': 40}).hasMore, isFalse); + expect(() => BinderyPage.fromJson(BinderyCollection.book, ''), throwsFormatException); + expect(() => BinderyPage.fromJson(BinderyCollection.book, {'items': [{}], 'total': 1, 'offset': 0, 'limit': 40}), throwsFormatException); + }); + test('series links unwrap nested books', () { + final series = BinderyItem(BinderyCollection.series, {'id': 1, 'title': 'Series', 'books': [ + {'bookId': 2, 'positionInSeries': '1', 'book': {'id': 2, 'title': 'Book'}}, + {'bookId': 3}, + ]}); + expect(series.books.single.title, 'Book'); + }); + test('image references stay on server proxy', () { + expect(BinderyLibraryApi.imageReference('/base/api/v1/images?url=https%3A%2F%2Fexample.org%2Fcover.jpg'), 'https://example.org/cover.jpg'); + expect(BinderyLibraryApi.imageReference('bindery-cover:abc'), 'bindery-cover:abc'); + expect(BinderyLibraryApi.imageReference('//example.org/api/v1/images?url=x'), isNull); + expect(BinderyLibraryApi.imageReference('/unrelated'), isNull); + }); +} diff --git a/app/test/bindery_library_screen_test.dart b/app/test/bindery_library_screen_test.dart new file mode 100644 index 00000000..1d34f397 --- /dev/null +++ b/app/test/bindery_library_screen_test.dart @@ -0,0 +1,42 @@ +import 'package:core_models/core_models.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import '../lib/src/bindery/library_api.dart'; +import '../lib/src/screens/bindery_home.dart'; +import '../lib/src/screens/bindery_library_screen.dart'; + +void main() { + testWidgets('Library opens directly, supports grid and collection switching', (tester) async { + const instance = Instance(id: 'bindery-test', name: 'Test Bindery', + kind: ServiceKind.bindery, localUrl: 'http://localhost:8787', + externalUrl: '', urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'test')); + final dio = Dio(BaseOptions(baseUrl: 'http://localhost:8787/')); + addTearDown(() => dio.close()); + dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) { + final item = options.path.endsWith('/author') + ? {'id': 1, 'authorName': 'Test Author'} + : {'id': 2, 'title': 'Test Book'}; + handler.resolve(Response(requestOptions: options, data: { + 'items': [item], 'total': 1, 'offset': 0, 'limit': 40, + })); + })); + await tester.pumpWidget(ProviderScope( + overrides: [binderyLibraryApiProvider(instance).overrideWith((ref) async => BinderyLibraryApi(dio))], + child: const MaterialApp(home: BinderyHome(instance: instance, drawer: Drawer())), + )); + await tester.pumpAndSettle(); + expect(find.text('Test Author'), findsOneWidget); + expect(find.byType(NavigationBar), findsNothing); + await tester.tap(find.byTooltip('Switch to grid view')); + await tester.pumpAndSettle(); + expect(find.byType(SliverGrid), findsOneWidget); + await tester.tap(find.text('Books')); + await tester.pumpAndSettle(); + expect(find.text('Test Book'), findsOneWidget); + expect(find.text('Test Author'), findsNothing); + expect(tester.takeException(), isNull); + }); +}