Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Bookmark server sync, inactive card playback, detail sheet bookmarks

Nathan Poulsona8f5567a0546
diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dart
index 608cc368..90619593 100644
--- a/lib/screens/bookmarks_screen.dart
+++ b/lib/screens/bookmarks_screen.dart
@@ -33,7 +33,9 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
Future<void> _loadSort() async {
_sort = await PlayerSettings.getBookmarkSort();
+ // Show local bookmarks immediately, then sync with server
_load();
+ _syncAll();
}
Future<void> _load() async {
@@ -41,6 +43,57 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
if (mounted) setState(() { _allBookmarks = all; _loading = false; });
}
+ Future<void> _syncAll() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final user = await api.getMe();
+ if (user == null || !mounted) return;
+ final itemIds = <String>{};
+ // Bookmarks on the user object (keyed by libraryItemId)
+ final userBookmarks = user['bookmarks'] as List<dynamic>?;
+ if (userBookmarks != null) {
+ for (final b in userBookmarks) {
+ if (b is Map<String, dynamic>) {
+ final itemId = b['libraryItemId'] as String? ?? '';
+ if (itemId.isNotEmpty) itemIds.add(itemId);
+ }
+ }
+ }
+ // Also check mediaProgress for bookmarks
+ final progressList = user['mediaProgress'] as List<dynamic>? ?? [];
+ for (final p in progressList) {
+ if (p is! Map<String, dynamic>) continue;
+ final bookmarks = p['bookmarks'] as List?;
+ if (bookmarks != null && bookmarks.isNotEmpty) {
+ final itemId = p['libraryItemId'] as String? ?? '';
+ if (itemId.isNotEmpty) itemIds.add(itemId);
+ }
+ }
+ // Also include items we have local bookmarks for
+ final local = await BookmarkService().getAllBookmarks();
+ itemIds.addAll(local.keys);
+ // Group server bookmarks by itemId for efficient sync
+ final serverByItem = <String, List<Map<String, dynamic>>>{};
+ if (userBookmarks != null) {
+ for (final b in userBookmarks) {
+ if (b is Map<String, dynamic>) {
+ final id = b['libraryItemId'] as String? ?? '';
+ if (id.isNotEmpty) {
+ serverByItem.putIfAbsent(id, () => []).add(b);
+ }
+ }
+ }
+ }
+ // Sync each item with pre-loaded server data
+ for (final itemId in itemIds) {
+ if (!mounted) break;
+ await BookmarkService().syncBookmarks(itemId, api,
+ preloadedServerBookmarks: serverByItem[itemId] ?? []);
+ }
+ // Reload after sync
+ if (mounted) _load();
+ }
+
String _selKey(String itemId, String bookmarkId) => '$itemId::$bookmarkId';
void _toggleSelect(String itemId, String bookmarkId) {
@@ -116,7 +169,7 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
for (final entry in grouped.entries) {
for (final bmId in entry.value) {
- await BookmarkService().deleteBookmark(itemId: entry.key, bookmarkId: bmId);
+ await BookmarkService().deleteBookmark(itemId: entry.key, bookmarkId: bmId, api: context.read<AuthProvider>().apiService);
}
}
@@ -146,29 +199,78 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
return itemId.length > 12 ? '${itemId.substring(0, 12)}…' : itemId;
}
+ Future<void> _editBookmark(String itemId, Bookmark bookmark) async {
+ final titleC = TextEditingController(text: bookmark.title);
+ final noteC = TextEditingController(text: bookmark.note ?? '');
+ final result = await showDialog<Map<String, String>>(context: context, builder: (ctx) => AlertDialog(
+ title: const Text('Edit Bookmark'),
+ content: Column(mainAxisSize: MainAxisSize.min, children: [
+ TextField(controller: titleC, decoration: const InputDecoration(labelText: 'Title', border: OutlineInputBorder())),
+ const SizedBox(height: 12),
+ TextField(controller: noteC, maxLines: 3, decoration: const InputDecoration(labelText: 'Note (optional)', border: OutlineInputBorder(), alignLabelWithHint: true)),
+ ]),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(ctx, {'title': titleC.text, 'note': noteC.text}), child: const Text('Save')),
+ ],
+ ));
+ if (result != null && result['title']!.isNotEmpty) {
+ await BookmarkService().updateBookmark(
+ itemId: itemId, bookmarkId: bookmark.id,
+ title: result['title']!, note: result['note']?.isNotEmpty == true ? result['note'] : null,
+ api: context.read<AuthProvider>().apiService,
+ );
+ _load();
+ }
+ }
+
Future<void> _jumpToBookmark(String itemId, Bookmark bookmark, String bookTitle) async {
- final confirmed = await showDialog<bool>(
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final action = await showDialog<String>(
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',
- ),
+ title: Text(bookmark.title, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ content: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
+ if (bookmark.note != null && bookmark.note!.isNotEmpty) ...[
+ Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text(bookmark.note!, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant, height: 1.4)),
+ ),
+ const SizedBox(height: 12),
+ ],
+ Text('${bookmark.formattedPosition} in $bookTitle',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ ]),
actions: [
TextButton(
- onPressed: () => Navigator.pop(ctx, false),
- child: const Text('Cancel'),
+ onPressed: () => Navigator.pop(ctx),
+ child: const Text('Close'),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, 'edit'),
+ child: const Text('Edit'),
),
FilledButton(
- onPressed: () => Navigator.pop(ctx, true),
+ onPressed: () => Navigator.pop(ctx, 'jump'),
child: const Text('Jump'),
),
],
),
);
- if (confirmed != true || !mounted) return;
+ if (action == 'edit') {
+ await _editBookmark(itemId, bookmark);
+ return;
+ }
+
+ if (action != 'jump' || !mounted) return;
// Read providers before async gaps
final lib = context.read<LibraryProvider>();
@@ -178,6 +280,7 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
// If the same book is already loaded, just seek
if (player.currentItemId == itemId) {
await player.seekTo(Duration(seconds: bookmark.positionSeconds.round()));
+ if (!player.isPlaying) player.play();
if (mounted) Navigator.pop(context);
AppShell.goToAbsorbingGlobal();
return;
@@ -223,6 +326,7 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
totalDuration: duration,
chapters: chapters,
startTime: bookmark.positionSeconds,
+ forceStartTime: true,
);
if (error != null && mounted) showErrorSnackBar(context, error);
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 7f64c471..797af619 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -909,6 +909,75 @@ class ApiService {
return null;
}
+ // ─── Bookmark Endpoints ───────────────────────────────────
+
+ /// Get bookmarks for an item from the server.
+ /// Uses GET /api/me/item/:id which includes bookmarks in the response.
+ Future<List<Map<String, dynamic>>?> getServerBookmarks(String itemId) async {
+ try {
+ // Try mediaProgress first
+ final progress = await getItemProgress(itemId);
+ if (progress != null) {
+ final bookmarks = progress['bookmarks'] as List<dynamic>?;
+ if (bookmarks != null && bookmarks.isNotEmpty) {
+ return bookmarks.cast<Map<String, dynamic>>();
+ }
+ }
+ // Fall back to user object - bookmarks may be stored there
+ final user = await getMe();
+ if (user != null) {
+ final bookmarks = user['bookmarks'] as List<dynamic>?;
+ if (bookmarks != null) {
+ // Filter to bookmarks for this item
+ return bookmarks
+ .whereType<Map<String, dynamic>>()
+ .where((b) => b['libraryItemId'] == itemId)
+ .toList();
+ }
+ }
+ return [];
+ } catch (e) { debugPrint('getServerBookmarks error: $e'); }
+ return null;
+ }
+
+ /// Create a bookmark on the server.
+ /// POST /api/me/item/:id/bookmark body: { time, title }
+ Future<bool> createBookmark(String itemId, {required double time, required String title}) async {
+ try {
+ final r = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/me/item/$itemId/bookmark'),
+ body: jsonEncode({'time': time, 'title': title}),
+ );
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('createBookmark error: $e'); }
+ return false;
+ }
+
+ /// Update a bookmark on the server.
+ /// PATCH /api/me/item/:id/bookmark body: { time, title }
+ Future<bool> updateBookmark(String itemId, {required double time, required String title}) async {
+ try {
+ final r = await _authPatch(
+ Uri.parse('$_cleanBaseUrl/api/me/item/$itemId/bookmark'),
+ body: jsonEncode({'time': time, 'title': title}),
+ );
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('updateBookmark error: $e'); }
+ return false;
+ }
+
+ /// Delete a bookmark on the server.
+ /// DELETE /api/me/item/:id/bookmark/:time
+ Future<bool> deleteBookmark(String itemId, {required double time}) async {
+ try {
+ final r = await _authDelete(
+ Uri.parse('$_cleanBaseUrl/api/me/item/$itemId/bookmark/$time'),
+ );
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('deleteBookmark error: $e'); }
+ return false;
+ }
+
/// Get a single series with its books (paginated).
/// If [onPageLoaded] is provided, it's called after each page with the
/// cumulative results and total so the UI can show books as they arrive.
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index ba018961..56c1995f 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -642,6 +642,7 @@ class AudioPlayerService extends ChangeNotifier {
double _totalDuration = 0;
List<dynamic> _chapters = [];
ApiService? _api;
+ ApiService? get currentApi => _api;
String? _playbackSessionId;
bool _isOfflineMode = false;
StreamSubscription? _syncSub;
@@ -1123,6 +1124,7 @@ class AudioPlayerService extends ChangeNotifier {
required double totalDuration,
required List<dynamic> chapters,
double startTime = 0,
+ bool forceStartTime = false,
String? episodeId,
String? episodeTitle,
}) async {
@@ -1166,9 +1168,9 @@ class AudioPlayerService extends ChangeNotifier {
// Notify rolling download listener that a new item is playing
_onPlayStartedCallback?.call(progressKey);
- // Check for local saved position
+ // Check for local saved position (skip if startTime was forced)
final localPos = await _progressSync.getSavedPosition(progressKey);
- if (localPos > 0 && startTime == 0) {
+ if (localPos > 0 && startTime == 0 && !forceStartTime) {
startTime = localPos;
debugPrint('[Player] Resuming from local position: ${startTime}s');
}
@@ -1197,7 +1199,7 @@ class AudioPlayerService extends ChangeNotifier {
final String? result;
if (_downloadService.isDownloaded(progressKey)) {
result = await _playFromLocal(progressKey, title, author, coverUrl,
- totalDuration, chapters, startTime);
+ totalDuration, chapters, startTime, forceStartTime);
} else {
// Check manual offline — don't stream from server
final prefs = await SharedPreferences.getInstance();
@@ -1209,7 +1211,7 @@ class AudioPlayerService extends ChangeNotifier {
}
// Stream from server
result = await _playFromServer(api, itemId, title, author, coverUrl,
- totalDuration, chapters, startTime);
+ totalDuration, chapters, startTime, forceStartTime);
}
_isLoadingNewItem = false;
@@ -1296,8 +1298,9 @@ class AudioPlayerService extends ChangeNotifier {
String? coverUrl,
double totalDuration,
List<dynamic> chapters,
- double startTime,
- ) async {
+ double startTime, [
+ bool forceStartTime = false,
+ ]) async {
debugPrint('[Player] Playing from local files: $title');
_isOfflineMode = false; // We still sync to server if possible
_playbackSessionId = null;
@@ -1484,8 +1487,9 @@ class AudioPlayerService extends ChangeNotifier {
String? coverUrl,
double totalDuration,
List<dynamic> chapters,
- double startTime,
- ) async {
+ double startTime, [
+ bool forceStartTime = false,
+ ]) async {
debugPrint('[Player] Streaming from server: $title');
_isOfflineMode = false;
@@ -1533,10 +1537,13 @@ class AudioPlayerService extends ChangeNotifier {
// Compare server position vs local.
// Usually the furthest position wins, but if local is ahead we also
// check timestamps to catch stale local saves.
+ // Skip all of this when startTime was forced (bookmark/chapter jump).
final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
final pKey = _currentEpisodeId != null ? '$itemId-$_currentEpisodeId' : itemId;
final localTs = await _progressSync.getSavedTimestamp(pKey);
- if (serverPos > startTime + 1.0) {
+ if (forceStartTime) {
+ debugPrint('[Player] Forced start time: ${startTime}s — skipping server/local position comparison');
+ } else if (serverPos > startTime + 1.0) {
debugPrint('[Player] Server position is ahead: server=${serverPos}s vs local=${startTime}s — using server');
startTime = serverPos;
} else if (startTime > 0) {
diff --git a/lib/services/bookmark_service.dart b/lib/services/bookmark_service.dart
index 81ff3d21..31e9dc91 100644
--- a/lib/services/bookmark_service.dart
+++ b/lib/services/bookmark_service.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
+import 'api_service.dart';
import 'scoped_prefs.dart';
import 'user_account_service.dart';
@@ -20,6 +21,12 @@ class Bookmark {
this.note,
});
+ /// Combined text for syncing to ABS server (which only has a single "title" field).
+ String get serverTitle {
+ if (note != null && note!.isNotEmpty) return '$title - $note';
+ return title;
+ }
+
Map<String, dynamic> toJson() => {
'id': id,
'pos': positionSeconds,
@@ -30,14 +37,32 @@ class Bookmark {
factory Bookmark.fromJson(Map<String, dynamic> json) {
return Bookmark(
- id: json['id'] as String,
- positionSeconds: (json['pos'] as num).toDouble(),
- created: DateTime.fromMillisecondsSinceEpoch(json['ts'] as int),
+ id: json['id'] as String? ?? '${DateTime.now().millisecondsSinceEpoch}',
+ positionSeconds: (json['pos'] as num?)?.toDouble() ?? (json['time'] as num?)?.toDouble() ?? 0,
+ created: json['ts'] != null
+ ? DateTime.fromMillisecondsSinceEpoch(json['ts'] as int)
+ : json['createdAt'] != null
+ ? DateTime.fromMillisecondsSinceEpoch((json['createdAt'] as num).toInt())
+ : DateTime.now(),
title: json['title'] as String? ?? 'Bookmark',
note: json['note'] as String?,
);
}
+ /// Create from ABS server bookmark format: { title, time, createdAt }
+ /// Server only has "title" - we put it into the note body since we don't
+ /// know what part is the title vs note.
+ factory Bookmark.fromServer(Map<String, dynamic> json) {
+ return Bookmark(
+ id: '${(json['createdAt'] as num?)?.toInt() ?? DateTime.now().millisecondsSinceEpoch}',
+ positionSeconds: (json['time'] as num?)?.toDouble() ?? 0,
+ created: json['createdAt'] != null
+ ? DateTime.fromMillisecondsSinceEpoch((json['createdAt'] as num).toInt())
+ : DateTime.now(),
+ title: json['title'] as String? ?? 'Bookmark',
+ );
+ }
+
String get formattedPosition {
final h = positionSeconds ~/ 3600;
final m = (positionSeconds % 3600) ~/ 60;
@@ -49,18 +74,16 @@ class Bookmark {
}
}
-/// Stores per-book bookmarks in SharedPreferences.
+/// Stores per-book bookmarks in SharedPreferences with server sync.
class BookmarkService {
static final BookmarkService _instance = BookmarkService._();
factory BookmarkService() => _instance;
BookmarkService._();
static const int _maxBookmarksPerBook = 100;
-
static const _keyPrefix = 'bookmarks_';
/// Get all bookmarks for a book.
- /// [sort] is 'newest' (by creation time, newest first) or 'position' (by book position).
Future<List<Bookmark>> getBookmarks(String itemId, {String sort = 'newest'}) async {
final stored = await ScopedPrefs.getStringList('$_keyPrefix$itemId');
@@ -87,6 +110,7 @@ class BookmarkService {
required double positionSeconds,
required String title,
String? note,
+ ApiService? api,
}) async {
final bookmark = Bookmark(
id: '${DateTime.now().millisecondsSinceEpoch}',
@@ -98,16 +122,20 @@ class BookmarkService {
final key = '$_keyPrefix$itemId';
final existing = (await ScopedPrefs.getStringList(key)).toList();
-
existing.add(jsonEncode(bookmark.toJson()));
- // Trim to max
if (existing.length > _maxBookmarksPerBook) {
existing.removeRange(0, existing.length - _maxBookmarksPerBook);
}
await ScopedPrefs.setStringList(key, existing);
debugPrint('[Bookmarks] Added "${bookmark.title}" at ${bookmark.formattedPosition}');
+
+ // Push to server
+ if (api != null) {
+ await api.createBookmark(itemId, time: positionSeconds, title: bookmark.serverTitle);
+ }
+
return bookmark;
}
@@ -117,10 +145,13 @@ class BookmarkService {
required String bookmarkId,
String? title,
String? note,
+ ApiService? api,
}) async {
final key = '$_keyPrefix$itemId';
final stored = await ScopedPrefs.getStringList(key);
+ double? time;
+ String? serverTitle;
final updated = <String>[];
for (final json in stored) {
try {
@@ -128,6 +159,8 @@ class BookmarkService {
if (bm.id == bookmarkId) {
if (title != null) bm.title = title;
bm.note = note ?? bm.note;
+ time = bm.positionSeconds;
+ serverTitle = bm.serverTitle;
updated.add(jsonEncode(bm.toJson()));
} else {
updated.add(json);
@@ -138,22 +171,31 @@ class BookmarkService {
}
await ScopedPrefs.setStringList(key, updated);
+
+ // Update on server
+ if (api != null && time != null && serverTitle != null) {
+ await api.updateBookmark(itemId, time: time, title: serverTitle);
+ }
}
/// Delete a bookmark.
Future<void> deleteBookmark({
required String itemId,
required String bookmarkId,
+ ApiService? api,
}) async {
final key = '$_keyPrefix$itemId';
final stored = await ScopedPrefs.getStringList(key);
+ double? time;
final updated = <String>[];
for (final json in stored) {
try {
final bm = Bookmark.fromJson(jsonDecode(json));
if (bm.id != bookmarkId) {
updated.add(json);
+ } else {
+ time = bm.positionSeconds;
}
} catch (_) {
updated.add(json);
@@ -162,10 +204,67 @@ class BookmarkService {
await ScopedPrefs.setStringList(key, updated);
debugPrint('[Bookmarks] Deleted bookmark $bookmarkId');
+
+ // Delete on server
+ if (api != null && time != null) {
+ await api.deleteBookmark(itemId, time: time);
+ }
+ }
+
+ /// Sync bookmarks for a specific item with the server.
+ /// Merges local and server bookmarks by position (time).
+ /// If [preloadedServerBookmarks] is provided, uses that instead of fetching.
+ Future<void> syncBookmarks(String itemId, ApiService api, {List<Map<String, dynamic>>? preloadedServerBookmarks}) async {
+ try {
+ final serverBookmarks = preloadedServerBookmarks ?? await api.getServerBookmarks(itemId);
+ if (serverBookmarks == null) return; // offline or error
+
+ final localBookmarks = await getBookmarks(itemId);
+
+ // Build position-based lookup (with 1s tolerance)
+ bool posMatch(double a, double b) => (a - b).abs() < 1.0;
+
+ // Find server bookmarks not in local
+ for (final sb in serverBookmarks) {
+ final serverBm = Bookmark.fromServer(sb);
+ final localMatch = localBookmarks.where((lb) => posMatch(lb.positionSeconds, serverBm.positionSeconds)).firstOrNull;
+ if (localMatch == null) {
+ // Server has it, local doesn't - add locally
+ final key = '$_keyPrefix$itemId';
+ final existing = (await ScopedPrefs.getStringList(key)).toList();
+ existing.add(jsonEncode(serverBm.toJson()));
+ await ScopedPrefs.setStringList(key, existing);
+ debugPrint('[Bookmarks] Synced from server: "${serverBm.title}" at ${serverBm.formattedPosition}');
+ } else if (serverBm.title != localMatch.serverTitle && serverBm.created.isAfter(localMatch.created)) {
+ // Server is newer - update local note body with server content
+ localMatch.note = serverBm.title;
+ await _saveAll(itemId, localBookmarks);
+ debugPrint('[Bookmarks] Updated from server: "${serverBm.title}"');
+ }
+ }
+
+ // Find local bookmarks not on server - push them
+ final refreshedLocal = await getBookmarks(itemId);
+ for (final lb in refreshedLocal) {
+ final serverMatch = serverBookmarks.where((sb) =>
+ posMatch((sb['time'] as num?)?.toDouble() ?? 0, lb.positionSeconds)).firstOrNull;
+ if (serverMatch == null) {
+ await api.createBookmark(itemId, time: lb.positionSeconds, title: lb.serverTitle);
+ debugPrint('[Bookmarks] Pushed to server: "${lb.serverTitle}" at ${lb.formattedPosition}');
+ }
+ }
+ } catch (e) {
+ debugPrint('[Bookmarks] Sync error: $e');
+ }
+ }
+
+ /// Save all bookmarks for an item (used internally after batch updates).
+ Future<void> _saveAll(String itemId, List<Bookmark> bookmarks) async {
+ final key = '$_keyPrefix$itemId';
+ await ScopedPrefs.setStringList(key, bookmarks.map((b) => jsonEncode(b.toJson())).toList());
}
/// Get all bookmarks across all books for the current account, keyed by itemId.
- /// [sort] is 'newest' (by creation time, newest first) or 'position' (by book position).
Future<Map<String, List<Bookmark>>> getAllBookmarks({String sort = 'newest'}) async {
final prefs = await SharedPreferences.getInstance();
final scope = UserAccountService().activeScopeKey;
@@ -192,7 +291,6 @@ class BookmarkService {
}
}
- // Sort book groups by most recent bookmark when in newest mode
if (sort == 'newest') {
final sorted = Map.fromEntries(
result.entries.toList()..sort((a, b) => b.value.first.created.compareTo(a.value.first.created)),
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index 93f8be43..2592bdf0 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -1263,6 +1263,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
isCastingThis: _isCastingThis,
displaySpeed: _speedAdjustedTime ? (_isActive ? widget.player.speed : _savedSpeed) : 1.0,
player: widget.player,
+ itemId: _itemId,
);
}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index bcc00014..f96ad8bd 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -20,6 +20,7 @@ import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import 'card_buttons.dart';
import '../services/api_service.dart';
+import '../services/bookmark_service.dart';
import '../services/download_service.dart';
import '../services/progress_sync_service.dart';
import '../services/metadata_override_service.dart';
@@ -61,6 +62,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
String? _asin;
bool _isLoading = true;
bool _chaptersExpanded = false;
+ bool _bookmarksExpanded = false;
+ List<Bookmark> _bookmarks = [];
bool _isAbsorbing = false;
bool _hasLocalOverride = false;
bool _showGoodreads = false;
@@ -71,6 +74,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
@override void initState() {
super.initState();
_loadItem();
+ _loadBookmarks();
PlayerSettings.getShowGoodreadsButton().then((v) { if (mounted) setState(() => _showGoodreads = v); });
ScopedPrefs.getStringList('saved_ebooks').then((list) {
if (mounted && list.contains(widget.itemId)) {
@@ -79,6 +83,11 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
});
}
+ Future<void> _loadBookmarks() async {
+ final bm = await BookmarkService().getBookmarks(widget.itemId, sort: 'position');
+ if (mounted) setState(() => _bookmarks = bm);
+ }
+
Future<void> _loadItem() async {
final auth = context.read<AuthProvider>();
final lib = context.read<LibraryProvider>();
@@ -512,6 +521,24 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
Text(_fmtDur(((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),
]));
})]],
+ if (_bookmarks.isNotEmpty) ...[const SizedBox(height: 16),
+ GestureDetector(onTap: () => setState(() => _bookmarksExpanded = !_bookmarksExpanded),
+ child: Row(children: [
+ Text('Bookmarks (${_bookmarks.length})', style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ const Spacer(), Icon(_bookmarksExpanded ? Icons.expand_less : Icons.expand_more, color: cs.onSurface.withValues(alpha: 0.3), size: 20)])),
+ if (_bookmarksExpanded) ...[const SizedBox(height: 8),
+ ..._bookmarks.map((bm) {
+ final hasNote = bm.note != null && bm.note!.isNotEmpty;
+ return Padding(padding: const EdgeInsets.symmetric(vertical: 3),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ SizedBox(width: 56, child: Text(bm.formattedPosition, style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3)))),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(bm.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6))),
+ if (hasNote)
+ Text(bm.note!, maxLines: 2, overflow: TextOverflow.ellipsis, style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.35))),
+ ])),
+ ]));
+ })]],
// Secondary actions are in the More sheet now.
]);
}
diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dart
index 9a7961eb..5af1ac87 100644
--- a/lib/widgets/card_buttons.dart
+++ b/lib/widgets/card_buttons.dart
@@ -1,5 +1,9 @@
import 'dart:io';
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/chromecast_service.dart';
@@ -260,7 +264,19 @@ class CardBookmarkButtonInline extends StatefulWidget {
class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
int _count = 0;
- @override void initState() { super.initState(); _loadCount(); }
+ @override void initState() { super.initState(); _syncThenLoadCount(); }
+
+ Future<void> _syncThenLoadCount() async {
+ // Show local count immediately
+ _loadCount();
+ // Then sync with server and update
+ final api = AudioPlayerService().currentApi;
+ if (api != null) {
+ await BookmarkService().syncBookmarks(widget.itemId, api);
+ _loadCount();
+ }
+ }
+
Future<void> _loadCount() async {
final c = await BookmarkService().getCount(widget.itemId);
if (mounted) setState(() => _count = c);
@@ -270,7 +286,7 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
final cs = Theme.of(context).colorScheme;
final cp = widget.compact;
final lg = widget.large;
- final enabled = widget.isActive || _isCasting;
+ final active = widget.isActive || _isCasting;
final iconSz = cp ? 13.0 : (lg ? 22.0 : 18.0);
final fontSize = cp ? 10.0 : (lg ? 14.0 : 12.0);
final vPad = cp ? 6.0 : (lg ? 12.0 : 8.0);
@@ -278,8 +294,8 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
final sh = widget.short;
final label = cp ? (_count > 0 ? '$_count' : 'Bookmark') : sh ? 'Bookmarks' : (_count > 0 ? 'Bookmarks ($_count)' : 'Bookmark');
return Pressable(
- onTap: enabled ? () => _showBookmarks(context) : () => showInactiveToast(context),
- onLongPress: enabled ? () => _quickAdd(context) : null,
+ onTap: () => _showBookmarks(context),
+ onLongPress: active ? () => _quickAdd(context) : null,
child: Container(
padding: EdgeInsets.symmetric(vertical: vPad),
decoration: BoxDecoration(
@@ -288,17 +304,14 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
),
child: cp
- ? Center(child: Icon(Icons.bookmark_outline_rounded, size: iconSz,
- color: enabled ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24)))
+ ? Center(child: Icon(Icons.bookmark_outline_rounded, size: iconSz, color: cs.onSurfaceVariant))
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
- Icon(Icons.bookmark_outline_rounded, size: iconSz,
- color: enabled ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24)),
+ Icon(Icons.bookmark_outline_rounded, size: iconSz, color: cs.onSurfaceVariant),
const SizedBox(width: 8),
Flexible(child: Text(label, overflow: TextOverflow.ellipsis, style: TextStyle(
- color: enabled ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24),
- fontSize: fontSize, fontWeight: FontWeight.w500))),
+ color: cs.onSurfaceVariant, fontSize: fontSize, fontWeight: FontWeight.w500))),
],
),
),
@@ -323,7 +336,7 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
final e = (m['end'] as num?)?.toDouble() ?? 0;
if (pos >= s && pos < e) { chTitle = m['title'] as String?; break; }
}
- await BookmarkService().addBookmark(itemId: widget.itemId, positionSeconds: pos, title: chTitle ?? 'Bookmark');
+ await BookmarkService().addBookmark(itemId: widget.itemId, positionSeconds: pos, title: chTitle ?? 'Bookmark', api: AudioPlayerService().currentApi);
_loadCount();
if (ctx.mounted) {
ScaffoldMessenger.of(ctx).showSnackBar(SnackBar(duration: const Duration(seconds: 2), content: const Text('Bookmark added'), behavior: SnackBarBehavior.floating,
@@ -540,6 +553,11 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
@override void initState() { super.initState(); _loadSort(); }
Future<void> _loadSort() async {
_sort = await PlayerSettings.getBookmarkSort();
+ // Sync first, then load
+ final api = AudioPlayerService().currentApi;
+ if (api != null) {
+ await BookmarkService().syncBookmarks(widget.itemId, api);
+ }
_load();
}
Future<void> _load() async {
@@ -600,14 +618,29 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
final bm = _bookmarks![i];
final hasNote = bm.note != null && bm.note!.isNotEmpty;
return InkWell(
- onTap: () {
- final seekDur = Duration(seconds: bm.positionSeconds.round());
- if (_isCasting) {
- ChromecastService().seekTo(seekDur);
+ onTap: () async {
+ final confirmed = await showDialog<bool>(context: ctx, builder: (dlg) => AlertDialog(
+ title: const Text('Jump to bookmark?'),
+ content: Text('"${bm.title}" at ${bm.formattedPosition}'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(dlg, false), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(dlg, true), child: const Text('Jump')),
+ ],
+ ));
+ if (confirmed != true || !ctx.mounted) return;
+ final isActive = widget.player.currentItemId == widget.itemId;
+ Navigator.pop(ctx); // Close bookmark sheet first
+ if (isActive || _isCasting) {
+ final seekDur = Duration(seconds: bm.positionSeconds.round());
+ if (_isCasting) {
+ ChromecastService().seekTo(seekDur);
+ } else {
+ await widget.player.seekTo(seekDur);
+ if (!widget.player.isPlaying) widget.player.play();
+ }
} else {
- widget.player.seekTo(seekDur);
+ await _startPlaybackAt(bm.positionSeconds);
}
- Navigator.pop(ctx);
},
onLongPress: () => _editBookmark(bm),
child: Padding(
@@ -640,7 +673,16 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
const SizedBox(width: 8),
GestureDetector(
onTap: () async {
- await BookmarkService().deleteBookmark(itemId: widget.itemId, bookmarkId: bm.id);
+ final confirmed = await showDialog<bool>(context: context, builder: (dlg) => AlertDialog(
+ title: const Text('Delete bookmark?'),
+ content: Text('"${bm.title}" at ${bm.formattedPosition}'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(dlg, false), child: const Text('Cancel')),
+ TextButton(onPressed: () => Navigator.pop(dlg, true), child: Text('Delete', style: TextStyle(color: Colors.red.shade300))),
+ ],
+ ));
+ if (confirmed != true) return;
+ await BookmarkService().deleteBookmark(itemId: widget.itemId, bookmarkId: bm.id, api: AudioPlayerService().currentApi);
_load();
},
child: Padding(
@@ -661,6 +703,29 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
return cast.isCasting && cast.castingItemId == widget.itemId;
}
+ Future<void> _startPlaybackAt(double positionSeconds) async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final lib = context.read<LibraryProvider>();
+ final player = widget.player;
+ final fullItem = await api.getLibraryItem(widget.itemId);
+ if (fullItem == null) 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(widget.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: widget.itemId,
+ title: title, author: author, coverUrl: coverUrl,
+ totalDuration: duration, chapters: chapters,
+ startTime: positionSeconds, forceStartTime: true,
+ );
+ AppShell.goToAbsorbingGlobal();
+ }
+
Future<void> _addBookmark() async {
final cast = ChromecastService();
final pos = _isCasting
@@ -695,7 +760,7 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
));
if (result != null && result['title']!.isNotEmpty) {
final note = result['note']?.isNotEmpty == true ? result['note'] : null;
- await BookmarkService().addBookmark(itemId: widget.itemId, positionSeconds: pos, title: result['title']!, note: note);
+ await BookmarkService().addBookmark(itemId: widget.itemId, positionSeconds: pos, title: result['title']!, note: note, api: AudioPlayerService().currentApi);
_load();
}
}
@@ -719,6 +784,7 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
await BookmarkService().updateBookmark(
itemId: widget.itemId, bookmarkId: bm.id,
title: result['title']!, note: result['note']?.isNotEmpty == true ? result['note'] : null,
+ api: AudioPlayerService().currentApi,
);
_load();
}
diff --git a/lib/widgets/card_chapters_sheet.dart b/lib/widgets/card_chapters_sheet.dart
index 16465bdf..2af26184 100644
--- a/lib/widgets/card_chapters_sheet.dart
+++ b/lib/widgets/card_chapters_sheet.dart
@@ -1,4 +1,8 @@
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/chromecast_service.dart';
import 'absorbing_shared.dart';
@@ -14,6 +18,7 @@ void showChaptersSheet({
required bool isCastingThis,
required double displaySpeed,
required AudioPlayerService player,
+ String? itemId,
}) {
if (chapters.isEmpty) return;
@@ -80,15 +85,49 @@ void showChaptersSheet({
const SizedBox(width: 8),
Text(fmtDur((end - start) / displaySpeed), style: tt.labelSmall?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant)),
]),
- onTap: isPlaybackActive ? () {
- final seekDur = Duration(seconds: start.round());
- if (isCastingThis) {
- cast.seekTo(seekDur);
- } else {
- player.seekTo(seekDur);
+ onTap: () async {
+ if (isPlaybackActive) {
+ // Active card - jump directly
+ final seekDur = Duration(seconds: start.round());
+ if (isCastingThis) {
+ cast.seekTo(seekDur);
+ } else {
+ player.seekTo(seekDur);
+ }
+ Navigator.pop(ctx);
+ } else if (itemId != null) {
+ // Inactive card - confirm then start playback
+ final confirmed = await showDialog<bool>(context: ctx, builder: (dlg) => AlertDialog(
+ title: const Text('Play from chapter?'),
+ content: Text('Start playing from "$chTitle"?'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(dlg, false), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(dlg, true), child: const Text('Play')),
+ ],
+ ));
+ if (confirmed != true || !ctx.mounted) return;
+ Navigator.pop(ctx); // Close chapter sheet first
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final lib = context.read<LibraryProvider>();
+ final fullItem = await api.getLibraryItem(itemId);
+ if (fullItem == null) 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 dur = (media['duration'] is num) ? (media['duration'] as num).toDouble() : 0.0;
+ final chs = (media['chapters'] as List<dynamic>?) ?? [];
+ await player.playItem(
+ api: api, itemId: itemId,
+ title: title, author: author, coverUrl: coverUrl,
+ totalDuration: dur, chapters: chs,
+ startTime: start, forceStartTime: true,
+ );
+ AppShell.goToAbsorbingGlobal();
}
- Navigator.pop(ctx);
- } : null,
+ },
);
},
)),
diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dart
index e6635217..149d8229 100644
--- a/lib/widgets/expanded_card.dart
+++ b/lib/widgets/expanded_card.dart
@@ -1299,6 +1299,7 @@ class _ExpandedCardState extends State<ExpandedCard> {
isCastingThis: _isCastingThis,
displaySpeed: _speedAdjustedTime && _isActive ? widget.player.speed : 1.0,
player: widget.player,
+ itemId: _itemId,
);
}