A cross platform Audiobookshelf client for Android and iOS
Dart
Add All Bookmarks screen, backup bookmarks/headers, per-account scoping
Nathan Poulson762d47304cba
diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dartnew file mode 100644index 00000000..1936c607--- /dev/null+++ b/lib/screens/bookmarks_screen.dart@@ -0,0 +1,564 @@+import 'dart:io';+import 'package:cached_network_image/cached_network_image.dart';+import 'package:flutter/material.dart';+import 'package:provider/provider.dart';+import '../providers/auth_provider.dart';+import '../providers/library_provider.dart';+import '../screens/app_shell.dart';+import '../services/audio_player_service.dart';+import '../services/bookmark_service.dart';+import '../services/download_service.dart';+import '../widgets/absorb_page_header.dart';++class BookmarksScreen extends StatefulWidget {+ const BookmarksScreen({super.key});+ @override+ State<BookmarksScreen> createState() => _BookmarksScreenState();+}++class _BookmarksScreenState extends State<BookmarksScreen> {+ bool _loading = true;+ Map<String, List<Bookmark>> _allBookmarks = {};+ bool _selecting = false;+ // Selected bookmarks as "itemId::bookmarkId" keys+ final Set<String> _selected = {};++ @override+ void initState() {+ super.initState();+ _load();+ }++ Future<void> _load() async {+ final all = await BookmarkService().getAllBookmarks();+ if (mounted) setState(() { _allBookmarks = all; _loading = false; });+ }++ String _selKey(String itemId, String bookmarkId) => '$itemId::$bookmarkId';++ void _toggleSelect(String itemId, String bookmarkId) {+ setState(() {+ final key = _selKey(itemId, bookmarkId);+ if (_selected.contains(key)) {+ _selected.remove(key);+ if (_selected.isEmpty) _selecting = false;+ } else {+ _selected.add(key);+ }+ });+ }++ void _toggleBookGroup(String itemId, List<Bookmark> bookmarks) {+ setState(() {+ final keys = bookmarks.map((b) => _selKey(itemId, b.id)).toSet();+ final allSelected = keys.every(_selected.contains);+ if (allSelected) {+ _selected.removeAll(keys);+ if (_selected.isEmpty) _selecting = false;+ } else {+ _selected.addAll(keys);+ }+ });+ }++ void _enterSelection(String itemId, String bookmarkId) {+ setState(() {+ _selecting = true;+ _selected.add(_selKey(itemId, bookmarkId));+ });+ }++ void _exitSelection() {+ setState(() {+ _selecting = false;+ _selected.clear();+ });+ }++ Future<void> _deleteSelected() async {+ if (_selected.isEmpty) return;++ final count = _selected.length;+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ icon: const Icon(Icons.delete_outline_rounded),+ title: Text('Delete $count bookmark${count == 1 ? '' : 's'}?'),+ content: const Text('This cannot be undone.'),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ child: const Text('Delete'),+ ),+ ],+ ),+ );++ if (confirmed != true || !mounted) return;++ // Group selections by itemId+ final grouped = <String, List<String>>{};+ for (final key in _selected) {+ final parts = key.split('::');+ grouped.putIfAbsent(parts[0], () => []).add(parts[1]);+ }++ for (final entry in grouped.entries) {+ for (final bmId in entry.value) {+ await BookmarkService().deleteBookmark(itemId: entry.key, bookmarkId: bmId);+ }+ }++ _exitSelection();+ await _load();++ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: Text('Deleted $count bookmark${count == 1 ? '' : 's'}'),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ }+ }++ /// Best-effort title lookup — no API calls.+ String _resolveTitle(String itemId) {+ final cache = context.read<LibraryProvider>().absorbingItemCache[itemId];+ if (cache != null) {+ final media = cache['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final title = metadata['title'] as String?;+ if (title != null && title.isNotEmpty) return title;+ }+ final dl = DownloadService().getInfo(itemId);+ if (dl.title != null && dl.title!.isNotEmpty) return dl.title!;+ return itemId.length > 12 ? '${itemId.substring(0, 12)}…' : itemId;+ }++ Future<void> _jumpToBookmark(String itemId, Bookmark bookmark, String bookTitle) async {+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ icon: const Icon(Icons.bookmark_rounded),+ title: const Text('Jump to bookmark?'),+ content: Text(+ '"${bookmark.title}" at ${bookmark.formattedPosition}\nin $bookTitle',+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ child: const Text('Jump'),+ ),+ ],+ ),+ );++ if (confirmed != true || !mounted) return;++ // Read providers before async gaps+ final lib = context.read<LibraryProvider>();+ final api = context.read<AuthProvider>().apiService;+ final player = AudioPlayerService();++ // If the same book is already loaded, just seek+ if (player.currentItemId == itemId) {+ await player.seekTo(Duration(seconds: bookmark.positionSeconds.round()));+ if (mounted) Navigator.pop(context);+ AppShell.goToAbsorbingGlobal();+ return;+ }++ // Otherwise load the book from API+ if (api == null) {+ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(const SnackBar(+ content: Text('Not connected to server'),+ behavior: SnackBarBehavior.floating,+ ));+ }+ return;+ }++ final fullItem = await api.getLibraryItem(itemId);+ if (fullItem == null) {+ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(const SnackBar(+ content: Text('Could not load book'),+ behavior: SnackBarBehavior.floating,+ ));+ }+ return;+ }++ final media = fullItem['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final title = metadata['title'] as String? ?? '';+ final author = metadata['authorName'] as String? ?? '';+ final coverUrl = lib.getCoverUrl(itemId);+ final duration = (media['duration'] is num)+ ? (media['duration'] as num).toDouble() : 0.0;+ final chapters = (media['chapters'] as List<dynamic>?) ?? [];++ await player.playItem(+ api: api,+ itemId: itemId,+ title: title,+ author: author,+ coverUrl: coverUrl,+ totalDuration: duration,+ chapters: chapters,+ startTime: bookmark.positionSeconds,+ );++ if (mounted) Navigator.pop(context);+ AppShell.goToAbsorbingGlobal();+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;++ return Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: SafeArea(+ child: _loading+ ? const Center(child: CircularProgressIndicator())+ : Column(+ children: [+ // Header+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),+ child: Row(children: [+ const Expanded(child: AbsorbPageHeader(title: 'All Bookmarks', padding: EdgeInsets.zero)),+ if (_selecting)+ IconButton(+ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),+ tooltip: 'Cancel selection',+ onPressed: _exitSelection,+ )+ else ...[+ if (_allBookmarks.isNotEmpty)+ IconButton(+ icon: Icon(Icons.checklist_rounded, color: cs.onSurfaceVariant),+ tooltip: 'Select',+ onPressed: () => setState(() => _selecting = true),+ ),+ IconButton(+ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),+ onPressed: () => Navigator.pop(context),+ ),+ ],+ ]),+ ),+ const SizedBox(height: 12),++ // Content+ if (_allBookmarks.isEmpty)+ Expanded(+ child: Center(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(Icons.bookmark_border_rounded, size: 48, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),+ const SizedBox(height: 12),+ Text('No bookmarks yet', style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),+ ],+ ),+ ),+ )+ else+ Expanded(+ child: ListView.builder(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),+ itemCount: _allBookmarks.length,+ itemBuilder: (ctx, i) {+ final lib = context.read<LibraryProvider>();+ final itemId = _allBookmarks.keys.elementAt(i);+ final bookmarks = _allBookmarks[itemId]!;+ final title = _resolveTitle(itemId);+ final coverUrl = lib.getCoverUrl(itemId, width: 400);+ return _BookGroup(+ itemId: itemId,+ title: title,+ coverUrl: coverUrl,+ mediaHeaders: lib.mediaHeaders,+ bookmarks: bookmarks,+ cs: cs,+ tt: tt,+ selecting: _selecting,+ selected: _selected,+ onToggle: _toggleSelect,+ onToggleGroup: () => _toggleBookGroup(itemId, bookmarks),+ onLongPress: _enterSelection,+ onJump: (id, bm) => _jumpToBookmark(id, bm, title),+ );+ },+ ),+ ),++ // Bottom delete bar+ if (_selecting && _selected.isNotEmpty)+ Container(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),+ decoration: BoxDecoration(+ color: cs.surfaceContainerHigh,+ border: Border(top: BorderSide(color: cs.outlineVariant.withValues(alpha: 0.3))),+ ),+ child: SafeArea(+ top: false,+ child: Row(children: [+ Text(+ '${_selected.length} selected',+ style: tt.bodyMedium?.copyWith(color: cs.onSurface),+ ),+ const Spacer(),+ FilledButton.tonalIcon(+ icon: const Icon(Icons.delete_outline_rounded, size: 18),+ label: const Text('Delete'),+ style: FilledButton.styleFrom(+ backgroundColor: cs.errorContainer,+ foregroundColor: cs.onErrorContainer,+ ),+ onPressed: _deleteSelected,+ ),+ ]),+ ),+ ),+ ],+ ),+ ),+ );+ }+}++class _BookGroup extends StatelessWidget {+ final String itemId;+ final String title;+ final String? coverUrl;+ final Map<String, String> mediaHeaders;+ final List<Bookmark> bookmarks;+ final ColorScheme cs;+ final TextTheme tt;+ final bool selecting;+ final Set<String> selected;+ final void Function(String itemId, String bookmarkId) onToggle;+ final VoidCallback onToggleGroup;+ final void Function(String itemId, String bookmarkId) onLongPress;+ final void Function(String itemId, Bookmark bookmark) onJump;++ const _BookGroup({+ required this.itemId,+ required this.title,+ this.coverUrl,+ this.mediaHeaders = const {},+ required this.bookmarks,+ required this.cs,+ required this.tt,+ required this.selecting,+ required this.selected,+ required this.onToggle,+ required this.onToggleGroup,+ required this.onLongPress,+ required this.onJump,+ });++ String _selKey(String bmId) => '$itemId::$bmId';++ @override+ Widget build(BuildContext context) {+ final groupKeys = bookmarks.map((b) => _selKey(b.id)).toSet();+ final allSelected = selecting && groupKeys.every(selected.contains);++ return Padding(+ padding: const EdgeInsets.only(bottom: 12),+ child: Card(+ elevation: 0,+ color: cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),+ child: Padding(+ padding: const EdgeInsets.all(14),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ // Book header with cover + title+ GestureDetector(+ onTap: selecting ? onToggleGroup : null,+ child: Row(children: [+ if (selecting)+ Padding(+ padding: const EdgeInsets.only(right: 10),+ child: Icon(+ allSelected ? Icons.check_circle_rounded : Icons.circle_outlined,+ size: 22,+ color: allSelected ? cs.primary : cs.onSurfaceVariant.withValues(alpha: 0.5),+ ),+ ),+ ClipRRect(+ borderRadius: BorderRadius.circular(6),+ child: SizedBox(+ width: 40,+ height: 40,+ child: _buildCover(),+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Text(+ title,+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ Text(+ '${bookmarks.length}',+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ]),+ ),+ const SizedBox(height: 8),+ // Bookmark rows+ for (var j = 0; j < bookmarks.length; j++) ...[+ if (j > 0) Divider(height: 1, indent: selecting ? 32 : 28, endIndent: 0, color: cs.outlineVariant.withValues(alpha: 0.3)),+ _BookmarkRow(+ itemId: itemId,+ bookmark: bookmarks[j],+ cs: cs,+ tt: tt,+ selecting: selecting,+ isSelected: selected.contains(_selKey(bookmarks[j].id)),+ onToggle: onToggle,+ onLongPress: onLongPress,+ onJump: onJump,+ ),+ ],+ ],+ ),+ ),+ ),+ );+ }++ Widget _buildCover() {+ if (coverUrl == null || coverUrl!.isEmpty) return _coverPlaceholder();++ if (coverUrl!.startsWith('/')) {+ final file = File(coverUrl!);+ if (file.existsSync()) {+ return Image.file(file, fit: BoxFit.cover,+ errorBuilder: (_, __, ___) => _coverPlaceholder());+ }+ return _coverPlaceholder();+ }++ return CachedNetworkImage(+ imageUrl: coverUrl!,+ fit: BoxFit.cover,+ httpHeaders: mediaHeaders,+ placeholder: (_, __) => _coverPlaceholder(),+ errorWidget: (_, __, ___) => _coverPlaceholder(),+ );+ }++ Widget _coverPlaceholder() {+ return Container(+ color: cs.surfaceContainerHighest,+ child: Center(+ child: Icon(Icons.headphones_rounded, size: 20,+ color: cs.onSurfaceVariant.withValues(alpha: 0.4)),+ ),+ );+ }+}++class _BookmarkRow extends StatelessWidget {+ final String itemId;+ final Bookmark bookmark;+ final ColorScheme cs;+ final TextTheme tt;+ final bool selecting;+ final bool isSelected;+ final void Function(String itemId, String bookmarkId) onToggle;+ final void Function(String itemId, String bookmarkId) onLongPress;+ final void Function(String itemId, Bookmark bookmark) onJump;++ const _BookmarkRow({+ required this.itemId,+ required this.bookmark,+ required this.cs,+ required this.tt,+ required this.selecting,+ required this.isSelected,+ required this.onToggle,+ required this.onLongPress,+ required this.onJump,+ });++ @override+ Widget build(BuildContext context) {+ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: selecting ? () => onToggle(itemId, bookmark.id) : () => onJump(itemId, bookmark),+ onLongPress: !selecting ? () => onLongPress(itemId, bookmark.id) : null,+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(+ children: [+ if (selecting)+ Padding(+ padding: const EdgeInsets.only(right: 10),+ child: Icon(+ isSelected ? Icons.check_circle_rounded : Icons.circle_outlined,+ size: 20,+ color: isSelected ? cs.primary : cs.onSurfaceVariant.withValues(alpha: 0.4),+ ),+ )+ else+ Icon(Icons.bookmark_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.6)),+ const SizedBox(width: 10),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ bookmark.title,+ style: tt.bodyMedium,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ if (bookmark.note != null && bookmark.note!.isNotEmpty)+ Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(+ bookmark.note!,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ],+ ),+ ),+ const SizedBox(width: 8),+ Text(+ bookmark.formattedPosition,+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant,+ fontFeatures: [const FontFeature.tabularFigures()],+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex e59faedb..d944b86a 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -18,6 +18,7 @@ import '../services/log_service.dart';import '../screens/login_screen.dart';import '../screens/app_shell.dart';import '../screens/admin_screen.dart';+import '../screens/bookmarks_screen.dart';import '../main.dart' show themeNotifier, parseThemeMode;import '../widgets/absorb_page_header.dart';import '../widgets/absorb_slider.dart';@@ -1269,6 +1270,28 @@ class _SettingsScreenState extends State<SettingsScreen> {),),+ const SizedBox(height: 10),++ // ── All Bookmarks ──+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Card(+ elevation: 0,+ color: cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),+ child: ListTile(+ leading: Icon(Icons.bookmarks_rounded, color: cs.primary),+ title: const Text('All Bookmarks'),+ subtitle: Text('View bookmarks across all books',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),+ onTap: () => Navigator.push(context,+ MaterialPageRoute(builder: (_) => const BookmarksScreen())),+ ),+ ),+ ),+const SizedBox(height: 24),// ── Accounts ──@@ -1817,6 +1840,9 @@ class _SettingsScreenState extends State<SettingsScreen> {final accounts = data['accounts'] as List<dynamic>?;final hasAccounts = accounts != null && accounts.isNotEmpty;+ final bookmarks = data['bookmarks'] as Map<String, dynamic>?;+ final hasBookmarks = bookmarks != null && bookmarks.isNotEmpty;+ final hasCustomHeaders = data['customHeaders'] != null;final createdAt = data['createdAt'] as String?;final appVersion = data['appVersion'] as String?;@@ -1844,20 +1870,19 @@ class _SettingsScreenState extends State<SettingsScreen> {const SizedBox(height: 12),Text(details, style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12)),],- if (hasAccounts) ...[+ if (hasAccounts || hasBookmarks || hasCustomHeaders) ...[const SizedBox(height: 12),- Container(- padding: const EdgeInsets.all(10),- decoration: BoxDecoration(- color: cs.primaryContainer.withValues(alpha: 0.15),- borderRadius: BorderRadius.circular(8),- ),- child: Row(children: [- Icon(Icons.people_rounded, size: 16, color: cs.primary),- const SizedBox(width: 8),- Text('Includes ${accounts.length} saved account(s)',- style: TextStyle(fontSize: 12, color: cs.primary)),- ]),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ if (hasAccounts)+ _restoreChip(Icons.people_rounded, '${accounts.length} account(s)', cs),+ if (hasBookmarks)+ _restoreChip(Icons.bookmark_rounded, 'Bookmarks for ${bookmarks.length} book(s)', cs),+ if (hasCustomHeaders)+ _restoreChip(Icons.vpn_key_rounded, 'Custom headers', cs),+ ],),],],@@ -1904,6 +1929,21 @@ class _SettingsScreenState extends State<SettingsScreen> {}}+ Widget _restoreChip(IconData icon, String label, ColorScheme cs) {+ return Container(+ padding: const EdgeInsets.all(10),+ decoration: BoxDecoration(+ color: cs.primaryContainer.withValues(alpha: 0.15),+ borderRadius: BorderRadius.circular(8),+ ),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(icon, size: 16, color: cs.primary),+ const SizedBox(width: 8),+ Text(label, style: TextStyle(fontSize: 12, color: cs.primary)),+ ]),+ );+ }+/// Stop any active playback and sync progress to the server before/// switching users, adding an account, or signing out.Future<void> _stopAndSyncPlayback() async {diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dartindex 4f0ed541..cf5d5e76 100644--- a/lib/services/backup_service.dart+++ b/lib/services/backup_service.dart@@ -1,6 +1,8 @@+import 'dart:convert';import 'package:shared_preferences/shared_preferences.dart';import 'package:package_info_plus/package_info_plus.dart';import 'audio_player_service.dart';+import 'scoped_prefs.dart';import 'sleep_timer_service.dart';import 'user_account_service.dart';@@ -82,13 +84,32 @@ class BackupService {// Offline modefinal offlineMode = prefs.getBool('manual_offline_mode') ?? false;- // Accounts (optional)+ // Bookmarks for current account (always included — not sensitive)+ final bookmarks = <String, List<String>>{};+ final scope = UserAccountService().activeScopeKey;+ final bmPrefix = scope.isNotEmpty ? '$scope:bookmarks_' : 'bookmarks_';+ for (final key in prefs.getKeys()) {+ if (key.startsWith(bmPrefix)) {+ final itemId = key.substring(bmPrefix.length);+ final list = prefs.getStringList(key);+ if (list != null && list.isNotEmpty) bookmarks[itemId] = list;+ }+ }++ // Accounts & custom headers (optional — contain auth data)List<Map<String, dynamic>>? accounts;+ Map<String, String>? customHeaders;if (includeAccounts) {accounts = UserAccountService().accounts.map((a) => a.toJson()).toList();+ final headersJson = prefs.getString('custom_headers');+ if (headersJson != null) {+ try {+ customHeaders = Map<String, String>.from(jsonDecode(headersJson) as Map);+ } catch (_) {}+ }}return {@@ -101,7 +122,9 @@ class BackupService {'equalizer': equalizer,'bookSpeeds': bookSpeeds,'offlineMode': offlineMode,+ 'bookmarks': bookmarks,'accounts': accounts,+ 'customHeaders': customHeaders,};}@@ -189,6 +212,15 @@ class BackupService {await prefs.setBool('manual_offline_mode', data['offlineMode'] as bool);}+ // Bookmarks (import into current account scope)+ final bookmarks = data['bookmarks'] as Map<String, dynamic>?;+ if (bookmarks != null) {+ for (final entry in bookmarks.entries) {+ final list = (entry.value as List<dynamic>).cast<String>();+ await ScopedPrefs.setStringList('bookmarks_${entry.key}', list);+ }+ }+// Accountsfinal accounts = data['accounts'] as List<dynamic>?;if (accounts != null) {@@ -197,5 +229,11 @@ class BackupService {await UserAccountService().saveAccount(SavedAccount.fromJson(map));}}++ // Custom headers+ final customHeaders = data['customHeaders'] as Map<String, dynamic>?;+ if (customHeaders != null) {+ await prefs.setString('custom_headers', jsonEncode(customHeaders));+ }}}diff --git a/lib/services/bookmark_service.dart b/lib/services/bookmark_service.dartindex df872ce9..0dbb655e 100644--- a/lib/services/bookmark_service.dart+++ b/lib/services/bookmark_service.dart@@ -1,6 +1,8 @@import 'dart:convert';import 'package:flutter/foundation.dart';import 'package:shared_preferences/shared_preferences.dart';+import 'scoped_prefs.dart';+import 'user_account_service.dart';/// A single bookmark in an audiobook.class Bookmark {@@ -55,12 +57,11 @@ class BookmarkService {static const int _maxBookmarksPerBook = 100;- String _key(String itemId) => 'bookmarks_$itemId';+ static const _keyPrefix = 'bookmarks_';/// Get all bookmarks for a book, sorted by position.Future<List<Bookmark>> getBookmarks(String itemId) async {- final prefs = await SharedPreferences.getInstance();- final stored = prefs.getStringList(_key(itemId)) ?? [];+ final stored = await ScopedPrefs.getStringList('$_keyPrefix$itemId');final bookmarks = <Bookmark>[];for (final json in stored) {@@ -90,9 +91,8 @@ class BookmarkService {note: note,);- final prefs = await SharedPreferences.getInstance();- final key = _key(itemId);- final existing = prefs.getStringList(key) ?? [];+ final key = '$_keyPrefix$itemId';+ final existing = (await ScopedPrefs.getStringList(key)).toList();existing.add(jsonEncode(bookmark.toJson()));@@ -101,7 +101,7 @@ class BookmarkService {existing.removeRange(0, existing.length - _maxBookmarksPerBook);}- await prefs.setStringList(key, existing);+ await ScopedPrefs.setStringList(key, existing);debugPrint('[Bookmarks] Added "${bookmark.title}" at ${bookmark.formattedPosition}');return bookmark;}@@ -113,9 +113,8 @@ class BookmarkService {String? title,String? note,}) async {- final prefs = await SharedPreferences.getInstance();- final key = _key(itemId);- final stored = prefs.getStringList(key) ?? [];+ final key = '$_keyPrefix$itemId';+ final stored = await ScopedPrefs.getStringList(key);final updated = <String>[];for (final json in stored) {@@ -133,7 +132,7 @@ class BookmarkService {}}- await prefs.setStringList(key, updated);+ await ScopedPrefs.setStringList(key, updated);}/// Delete a bookmark.@@ -141,9 +140,8 @@ class BookmarkService {required String itemId,required String bookmarkId,}) async {- final prefs = await SharedPreferences.getInstance();- final key = _key(itemId);- final stored = prefs.getStringList(key) ?? [];+ final key = '$_keyPrefix$itemId';+ final stored = await ScopedPrefs.getStringList(key);final updated = <String>[];for (final json in stored) {@@ -157,19 +155,43 @@ class BookmarkService {}}- await prefs.setStringList(key, updated);+ await ScopedPrefs.setStringList(key, updated);debugPrint('[Bookmarks] Deleted bookmark $bookmarkId');}+ /// Get all bookmarks across all books for the current account, keyed by itemId.+ Future<Map<String, List<Bookmark>>> getAllBookmarks() async {+ final prefs = await SharedPreferences.getInstance();+ final scope = UserAccountService().activeScopeKey;+ final scopedPrefix = scope.isNotEmpty ? '$scope:$_keyPrefix' : _keyPrefix;+ final result = <String, List<Bookmark>>{};++ for (final key in prefs.getKeys()) {+ if (!key.startsWith(scopedPrefix)) continue;+ final itemId = key.substring(scopedPrefix.length);+ final stored = prefs.getStringList(key) ?? [];+ final bookmarks = <Bookmark>[];+ for (final json in stored) {+ try {+ bookmarks.add(Bookmark.fromJson(jsonDecode(json)));+ } catch (_) {}+ }+ if (bookmarks.isNotEmpty) {+ bookmarks.sort((a, b) => a.positionSeconds.compareTo(b.positionSeconds));+ result[itemId] = bookmarks;+ }+ }++ return result;+ }+/// Get bookmark count for a book.Future<int> getCount(String itemId) async {- final prefs = await SharedPreferences.getInstance();- return (prefs.getStringList(_key(itemId)) ?? []).length;+ return (await ScopedPrefs.getStringList('$_keyPrefix$itemId')).length;}/// Clear all bookmarks for a book.Future<void> clearBookmarks(String itemId) async {- final prefs = await SharedPreferences.getInstance();- await prefs.remove(_key(itemId));+ await ScopedPrefs.remove('$_keyPrefix$itemId');}}diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 7918069c..8d456d11 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -675,12 +675,19 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {await api.markFinished(widget.itemId, duration);await ProgressSyncService().deleteLocal(widget.itemId);if (context.mounted) {+ final lib = context.read<LibraryProvider>();await _loadItem();- await context.read<LibraryProvider>().refresh();+ await lib.refresh();+ final mode = await PlayerSettings.getWhenFinished();+ if (mode == 'auto_remove') {+ await lib.removeFromAbsorbing(widget.itemId);+ }if (mounted) setState(() {});- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- duration: const Duration(seconds: 3), content: const Text('Marked as finished — nice work!'),- behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ if (context.mounted) {+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ duration: const Duration(seconds: 3), content: const Text('Marked as finished — nice work!'),+ behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ }}} catch (_) {if (context.mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dartindex 824f77df..79f78068 100644--- a/lib/widgets/series_books_sheet.dart+++ b/lib/widgets/series_books_sheet.dart@@ -64,6 +64,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {List<Map<String, dynamic>> _books = [];bool _isLoading = true;bool _isDownloadingAll = false;+ bool _isMarkingAll = false;@overridevoid initState() {@@ -173,6 +174,123 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {if (mounted) setState(() => _isLoading = false);}+ bool get _allFinished {+ final lib = context.read<LibraryProvider>();+ if (_books.isEmpty) return false;+ for (final book in _books) {+ final bookId = book['id'] as String? ?? '';+ if (lib.getProgressData(bookId)?['isFinished'] != true) return false;+ }+ return true;+ }++ Future<void> _markAllFinished() async {+ final auth = context.read<AuthProvider>();+ final api = auth.apiService;+ if (api == null) return;+ final lib = context.read<LibraryProvider>();++ setState(() => _isMarkingAll = true);++ for (final book in _books) {+ final bookId = book['id'] as String? ?? '';+ if (bookId.isEmpty) continue;+ if (lib.getProgressData(bookId)?['isFinished'] == true) continue;+ final media = book['media'] as Map<String, dynamic>? ?? {};+ final duration = (media['duration'] is num)+ ? (media['duration'] as num).toDouble()+ : 0.0;+ await api.markFinished(bookId, duration);+ lib.markFinishedLocally(bookId, skipRefresh: true);+ }++ if (mounted) {+ lib.refresh();+ setState(() => _isMarkingAll = false);+ }+ }++ Future<void> _markAllNotFinished() async {+ final auth = context.read<AuthProvider>();+ final api = auth.apiService;+ if (api == null) return;+ final lib = context.read<LibraryProvider>();++ setState(() => _isMarkingAll = true);++ for (final book in _books) {+ final bookId = book['id'] as String? ?? '';+ if (bookId.isEmpty) continue;+ if (lib.getProgressData(bookId)?['isFinished'] != true) continue;+ final media = book['media'] as Map<String, dynamic>? ?? {};+ final duration = (media['duration'] is num)+ ? (media['duration'] as num).toDouble()+ : 0.0;+ await api.markNotFinished(bookId, currentTime: 0, duration: duration);+ lib.resetProgressFor(bookId);+ }++ if (mounted) {+ lib.refresh();+ setState(() => _isMarkingAll = false);+ }+ }++ Widget _buildAbsorbButton(ColorScheme cs) {+ final allDone = _allFinished;+ final green = Theme.of(context).brightness == Brightness.dark+ ? Colors.greenAccent : Colors.green.shade700;++ if (_isMarkingAll) {+ return Padding(+ padding: const EdgeInsets.all(12),+ child: SizedBox(+ width: 16, height: 16,+ child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary),+ ),+ );+ }++ return IconButton(+ icon: Icon(+ allDone ? Icons.remove_done_rounded : Icons.done_all_rounded,+ size: 20,+ color: allDone ? green : cs.onSurfaceVariant,+ ),+ tooltip: allDone ? 'Mark all not finished' : 'Fully absorb series',+ visualDensity: VisualDensity.compact,+ onPressed: () async {+ if (allDone) {+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: const Text('Mark All Not Finished?'),+ content: Text('This will clear the finished status for all ${_books.length} books in this series.'),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Unmark All')),+ ],+ ),+ );+ if (confirmed == true) _markAllNotFinished();+ } else {+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: const Text('Fully Absorb Series?'),+ content: Text('This will mark all ${_books.length} books in this series as finished.'),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')),+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Fully Absorb')),+ ],+ ),+ );+ if (confirmed == true) _markAllFinished();+ }+ },+ );+ }+Future<void> _downloadAll() async {final auth = context.read<AuthProvider>();final api = auth.apiService;@@ -238,6 +356,8 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),),+ if (_books.isNotEmpty)+ _buildAbsorbButton(cs),],),),diff --git a/pubspec.yaml b/pubspec.yamlindex 1957f332..9aaedce3 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: A Material 3 Audiobookshelf client for Android.publish_to: 'none'-version: 1.7.28+34+version: 1.7.29+34environment:sdk: '>=3.1.0 <4.0.0'