Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Keep podcast bookmarks with their episode and make Listen and Transcribe work on them

Barnabas193f11dcb7ee
diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dart
index 6f9275aa..c51c3981 100644
--- a/lib/screens/bookmarks_screen.dart
+++ b/lib/screens/bookmarks_screen.dart
@@ -17,6 +17,7 @@ import '../widgets/card_buttons.dart';
import '../services/download_service.dart';
import '../services/ebook_annotation_service.dart';
import '../services/ebook_cache.dart';
+import '../utils/episode_key.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/adaptive_modal.dart';
import '../widgets/ebook_router.dart';
@@ -119,7 +120,8 @@ class _BookmarksScreenState extends State<BookmarksScreen>
Future<void> _loadBookSpeeds() async {
_defaultSpeed = await PlayerSettings.getDefaultSpeed();
var changed = false;
- for (final itemId in _allBookmarks.keys) {
+ for (final key in _allBookmarks.keys) {
+ final itemId = splitEpisodeKey(key).itemId;
if (_bookSpeeds.containsKey(itemId)) continue;
final s = await PlayerSettings.getBookSpeed(itemId);
if (s != null) {
@@ -130,8 +132,11 @@ class _BookmarksScreenState extends State<BookmarksScreen>
if (mounted && changed) setState(() {});
}
- double _displaySpeedFor(String itemId) {
+ double _displaySpeedFor(String key) {
if (!_speedAdjustedTime) return 1.0;
+ // Speed is saved per book, and a podcast's per-show, so an episode key has
+ // to come apart before either lookup.
+ final itemId = splitEpisodeKey(key).itemId;
final player = AudioPlayerService();
if (player.currentItemId == itemId) return player.speed;
return _bookSpeeds[itemId] ?? _defaultSpeed;
@@ -193,9 +198,12 @@ class _BookmarksScreenState extends State<BookmarksScreen>
serverByItem.putIfAbsent(id, () => []).add(b);
}
}
- // Sync each item with pre-loaded server data
+ // Sync each item with pre-loaded server data. Podcast episodes are keyed
+ // 'showId-episodeId' and never leave the device, so they have nothing to
+ // merge and an empty server list must not be read as "deleted".
for (final itemId in itemIds) {
if (!mounted) break;
+ if (isEpisodeKey(itemId)) continue;
await BookmarkService().syncBookmarks(itemId, api,
preloadedServerBookmarks: serverByItem[itemId] ?? []);
}
@@ -207,15 +215,34 @@ class _BookmarksScreenState extends State<BookmarksScreen>
// Only need a server fetch when no cache (library/download/title) has it.
final resolved = _resolveTitle(itemId);
if (resolved == null) {
- final item = await api.getLibraryItem(itemId);
+ final ids = splitEpisodeKey(itemId);
+ final item = await api.getLibraryItem(ids.itemId);
if (item != null) {
final media = item['media'] as Map<String, dynamic>? ?? {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
- final title = metadata['title'] as String?;
+ // An episode's group is named after the episode, so the show title
+ // is only the fallback when the episode has gone from the feed.
+ final episodeTitle = ids.episodeId == null
+ ? null
+ : ((media['episodes'] as List<dynamic>?) ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .where((e) => e['id'] == ids.episodeId)
+ .firstOrNull?['title'] as String?;
+ final showTitle = metadata['title'] as String?;
+ final title =
+ (episodeTitle?.isNotEmpty ?? false) ? episodeTitle : showTitle;
if (title != null && title.isNotEmpty) {
_titleCache[itemId] = title;
titleCacheDirty = true;
}
+ // Cache the show under its own id too, so the episode group can name
+ // the feed it came from without a second fetch.
+ if (ids.episodeId != null &&
+ showTitle != null &&
+ showTitle.isNotEmpty) {
+ _titleCache[ids.itemId] = showTitle;
+ titleCacheDirty = true;
+ }
}
} else {
// Promote library/download-resolved titles into our persisted cache
@@ -397,25 +424,51 @@ class _BookmarksScreenState extends State<BookmarksScreen>
/// Returns the book title for [itemId] from any available cache, or null
/// when the title isn't known locally yet. Callers should render a neutral
/// placeholder on null rather than the raw item ID.
- String? _resolveTitle(String itemId) {
- final cached = _titleCache[itemId];
+ String? _resolveTitle(String key) {
+ final cached = _titleCache[key];
if (cached != null && cached.isNotEmpty) return cached;
- final libCache =
- context.read<LibraryProvider>().absorbingItemCache[itemId];
+ // A downloaded podcast episode is stored under the episode key and carries
+ // the episode's own name - better than the show title the caches hold.
+ if (isEpisodeKey(key)) {
+ final ep = DownloadService().getInfo(key);
+ if (ep.title != null && ep.title!.isNotEmpty) return ep.title!;
+ }
+ final libCache = context.read<LibraryProvider>().absorbingItemCache[key];
if (libCache != null) {
final media = libCache['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);
+ final dl = DownloadService().getInfo(key);
if (dl.title != null && dl.title!.isNotEmpty) return dl.title!;
return null;
}
- Future<void> _jumpToBookmark(String itemId, Bookmark bookmark, String bookTitle) async {
+ /// The show a podcast episode belongs to, shown under the episode name so a
+ /// row of episodes from different feeds can be told apart. Null for books.
+ String? _resolveShowTitle(String key) {
+ final ids = splitEpisodeKey(key);
+ if (ids.episodeId == null) return null;
+ final libCache =
+ context.read<LibraryProvider>().absorbingItemCache[ids.itemId];
+ final metadata = (libCache?['media'] as Map<String, dynamic>?)?['metadata']
+ as Map<String, dynamic>?;
+ final title = metadata?['title'] as String?;
+ if (title != null && title.isNotEmpty) return title;
+ final cached = _titleCache[ids.itemId];
+ if (cached != null && cached.isNotEmpty) return cached;
+ final dl = DownloadService().getInfo(key);
+ if (dl.author != null && dl.author!.isNotEmpty) return dl.author;
+ return null;
+ }
+
+ Future<void> _jumpToBookmark(String key, Bookmark bookmark, String bookTitle) async {
final l = AppLocalizations.of(context)!;
final api = context.read<AuthProvider>().apiService;
+ final ids = splitEpisodeKey(key);
+ final itemId = ids.itemId;
+ final episodeId = ids.episodeId;
final result = await showModalBottomSheet<BookmarkDetailResult>(
context: context,
isScrollControlled: true,
@@ -426,6 +479,7 @@ class _BookmarksScreenState extends State<BookmarksScreen>
),
builder: (ctx) => BookmarkDetailSheet(
itemId: itemId,
+ episodeId: episodeId,
bookmark: bookmark,
api: api,
),
@@ -453,8 +507,9 @@ class _BookmarksScreenState extends State<BookmarksScreen>
return;
}
- // Same book already loaded: just seek.
- if (player.currentItemId == itemId) {
+ // Same book or episode already loaded: just seek.
+ if (player.currentItemId == itemId &&
+ (episodeId == null || player.currentEpisodeId == episodeId)) {
await player.seekTo(Duration(seconds: position.round()));
if (!player.isPlaying) player.play();
if (mounted) Navigator.pop(context);
@@ -482,20 +537,45 @@ class _BookmarksScreenState extends State<BookmarksScreen>
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)
+ var author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(key);
+ var duration = (media['duration'] is num)
? (media['duration'] as num).toDouble() : 0.0;
- final chapters = (media['chapters'] as List<dynamic>?) ?? [];
+ var chapters = (media['chapters'] as List<dynamic>?) ?? [];
+
+ // A podcast bookmark's time belongs to one episode, so play that episode.
+ String? episodeTitle;
+ if (episodeId != null) {
+ final ep = ((media['episodes'] as List<dynamic>?) ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .where((e) => e['id'] == episodeId)
+ .firstOrNull;
+ if (ep == null) {
+ if (mounted) {
+ showOverlayToast(context, l.bookmarksCouldNotLoad,
+ icon: Icons.error_outline_rounded);
+ }
+ return;
+ }
+ episodeTitle = ep['title'] as String?;
+ if (author.isEmpty) author = title;
+ duration = (ep['duration'] as num?)?.toDouble() ??
+ ((ep['audioFile'] as Map<String, dynamic>?)?['duration'] as num?)
+ ?.toDouble() ??
+ 0.0;
+ chapters = (ep['chapters'] as List<dynamic>?) ?? const [];
+ }
final error = await player.playItem(
api: api,
itemId: itemId,
- title: title,
+ title: episodeTitle ?? title,
author: author,
coverUrl: coverUrl,
totalDuration: duration,
chapters: chapters,
+ episodeId: episodeId,
+ episodeTitle: episodeTitle,
startTime: position,
forceStartTime: true,
libraryId: fullItem['libraryId'] as String?,
@@ -663,6 +743,7 @@ class _BookmarksScreenState extends State<BookmarksScreen>
return _BookGroup(
itemId: itemId,
title: resolvedTitle,
+ subtitle: _resolveShowTitle(itemId),
coverUrl: coverUrl,
mediaHeaders: lib.mediaHeaders,
bookmarks: bookmarks,
@@ -863,6 +944,8 @@ class _BookmarksScreenState extends State<BookmarksScreen>
class _BookGroup extends StatelessWidget {
final String itemId;
final String? title;
+ /// Show name under a podcast episode's title. Null for books.
+ final String? subtitle;
final String? coverUrl;
final Map<String, String> mediaHeaders;
final List<Bookmark> bookmarks;
@@ -879,6 +962,7 @@ class _BookGroup extends StatelessWidget {
const _BookGroup({
required this.itemId,
required this.title,
+ this.subtitle,
this.coverUrl,
this.mediaHeaders = const {},
required this.bookmarks,
@@ -935,12 +1019,26 @@ class _BookGroup extends StatelessWidget {
borderRadius: BorderRadius.circular(4),
),
)
- : Text(
- title!,
- style: tt.titleSmall
- ?.copyWith(fontWeight: FontWeight.w600),
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
+ : Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ title!,
+ style: tt.titleSmall
+ ?.copyWith(fontWeight: FontWeight.w600),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ if (subtitle != null && subtitle!.isNotEmpty)
+ Text(
+ subtitle!,
+ style: tt.labelSmall
+ ?.copyWith(color: cs.onSurfaceVariant),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
),
),
Text(
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 060bd138..44052bb6 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -27,10 +27,11 @@ import 'session_cache.dart';
import 'home_widget_service.dart';
import 'bookmark_service.dart';
import 'review_service.dart';
+import '../utils/episode_key.dart';
export 'player_settings.dart';
String playbackDownloadKey(String itemId, String? episodeId) =>
- episodeId == null ? itemId : '$itemId-$episodeId';
+ episodeKeyFor(itemId, episodeId);
// ─── AudioHandler (runs in background, controls notification) ───
@@ -951,18 +952,17 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
/// Save a bookmark at the current position, mirroring the in-app car-mode
/// button (chapter title as the label, pushed to the server via the API).
+ /// A podcast episode is bookmarked under its own key, which keeps it on the
+ /// device - ABS bookmarks have nowhere to put an episode id.
Future<bool> _bookmarkCurrentPosition() async {
final svc = _service;
if (svc == null) return false;
- // Podcasts don't support bookmarks - the button stays for a consistent car
- // layout but does nothing on an episode.
- if (svc.currentEpisodeId != null) return false;
final itemId = svc.currentItemId;
if (itemId == null) return false;
final pos = svc.position.inMilliseconds / 1000.0;
final chTitle = svc.currentChapter?['title'] as String?;
await BookmarkService().addBookmark(
- itemId: itemId,
+ itemId: playbackDownloadKey(itemId, svc.currentEpisodeId),
positionSeconds: pos,
title: (chTitle != null && chTitle.isNotEmpty) ? chTitle : 'Bookmark',
api: svc.currentApi,
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 9b825aec..be3cf1f5 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:package_info_plus/package_info_plus.dart';
+import '../utils/episode_key.dart';
import '../widgets/nav_hold_options.dart'
show navHoldTabs, navHoldPrefKey, navHoldMenuPrefKey;
import 'audio_player_service.dart';
@@ -286,6 +287,25 @@ class BackupService {
if (value != null && value.isNotEmpty) metadataOverrides[itemId] = value;
}
+ // Podcast bookmarks (scoped, keyed 'showId-episodeId'). An ABS bookmark
+ // has no episode id, so these never go to the server - the backup is the
+ // only way they reach another device. Book bookmarks are left out: they
+ // round-trip through ABS already.
+ final podcastBookmarks = <String, List<String>>{};
+ final bookmarkPrefix = '${scopePrefix}bookmarks_';
+ for (final key in prefs.getKeys()) {
+ if (!key.startsWith(bookmarkPrefix)) continue;
+ final itemKey = key.substring(bookmarkPrefix.length);
+ if (!isEpisodeKey(itemKey)) continue;
+ final List<String> stored;
+ try {
+ stored = prefs.getStringList(key) ?? const [];
+ } catch (_) {
+ continue; // the pending-create/delete keys are Strings, not lists
+ }
+ if (stored.isNotEmpty) podcastBookmarks[itemKey] = stored;
+ }
+
// Ebook annotations (scoped, keyed by itemId). Highlights, bookmarks and
// their notes live only on-device (ABS has no ebook annotation API), so
// the backup is their only way to survive a reinstall.
@@ -414,6 +434,7 @@ class BackupService {
'librarySettings': librarySettings,
'metadataOverrides': metadataOverrides,
'ebookAnnotations': ebookAnnotations,
+ 'podcastBookmarks': podcastBookmarks,
'ereader': ereader,
if (navHold.isNotEmpty) 'navHold': navHold,
'podcastPrefs': podcastPrefs,
@@ -924,6 +945,40 @@ class BackupService {
}
}
+ // Podcast bookmarks (scoped, keyed 'showId-episodeId'). Merged rather than
+ // overwritten: this device's own episode bookmarks live nowhere else, so a
+ // straight replace would throw away anything made since the file was
+ // written. Same position (within a second) counts as the same bookmark.
+ final podcastBookmarks = data['podcastBookmarks'] as Map<String, dynamic>?;
+ if (podcastBookmarks != null) {
+ for (final entry in podcastBookmarks.entries) {
+ final incoming = (entry.value as List<dynamic>?)?.whereType<String>().toList();
+ if (incoming == null || incoming.isEmpty) continue;
+ final key = 'bookmarks_${entry.key}';
+ final existing = (await ScopedPrefs.getStringList(key)).toList();
+ final positions = <double>[];
+ for (final raw in existing) {
+ try {
+ final pos = (jsonDecode(raw) as Map<String, dynamic>)['pos'] as num?;
+ if (pos != null) positions.add(pos.toDouble());
+ } catch (_) {}
+ }
+ for (final raw in incoming) {
+ double? pos;
+ try {
+ pos = ((jsonDecode(raw) as Map<String, dynamic>)['pos'] as num?)?.toDouble();
+ } catch (_) {
+ continue; // not a bookmark we can read - leave it out
+ }
+ if (pos == null) continue;
+ if (positions.any((p) => (p - pos!).abs() < 1.0)) continue;
+ positions.add(pos);
+ existing.add(raw);
+ }
+ await ScopedPrefs.setStringList(key, existing);
+ }
+ }
+
// E-reader appearance + behavior (scoped)
final er = data['ereader'] as Map<String, dynamic>?;
if (er != null) {
diff --git a/lib/services/book_track_resolver.dart b/lib/services/book_track_resolver.dart
index 55548725..dd9db34f 100644
--- a/lib/services/book_track_resolver.dart
+++ b/lib/services/book_track_resolver.dart
@@ -1,5 +1,6 @@
import 'dart:convert';
+import '../utils/episode_key.dart';
import 'api_service.dart';
import 'download_service.dart';
@@ -15,6 +16,10 @@ typedef TrackHit = ({int index, double localOffset, BookTrack track});
/// use the local files + cached track durations; streamed books build per-file
/// URLs from the library item. Kept in one place so the preview player and the
/// exporter can't drift apart on multi-file mapping.
+///
+/// [itemId] may be a podcast's compound "showId-episodeId" key. Downloads and
+/// cached sessions are stored under the whole key; the API needs the show id
+/// and the episode's own audio file.
class BookTrackResolver {
static Future<List<BookTrack>?> resolve(String itemId, ApiService? api) async {
// Downloaded book: local files + cached track durations.
@@ -42,9 +47,34 @@ class BookTrackResolver {
// Streamed book: build per-file URLs from the library item.
if (api == null) return null;
- final item = await api.getLibraryItem(itemId);
+ final ids = splitEpisodeKey(itemId);
+ final item = await api.getLibraryItem(ids.itemId);
if (item == null) return null;
final media = item['media'] as Map<String, dynamic>? ?? {};
+
+ // A podcast item has no audioFiles - each episode carries its own single
+ // file, and its bookmark times are relative to that file.
+ final episodeId = ids.episodeId;
+ if (episodeId != null) {
+ for (final ep in ((media['episodes'] as List<dynamic>?) ?? const [])
+ .whereType<Map<String, dynamic>>()) {
+ if (ep['id'] != episodeId) continue;
+ final af = ep['audioFile'] as Map<String, dynamic>?;
+ final ino = af?['ino']?.toString();
+ if (ino == null || ino.isEmpty) return null;
+ return [
+ (
+ source: api.buildFileUrl(ids.itemId, ino),
+ duration: (af?['duration'] as num?)?.toDouble() ??
+ (ep['duration'] as num?)?.toDouble() ??
+ 0,
+ local: false,
+ ),
+ ];
+ }
+ return null;
+ }
+
final audioFiles = ((media['audioFiles'] as List<dynamic>?) ?? const [])
.whereType<Map<String, dynamic>>()
.toList()
@@ -54,7 +84,7 @@ class BookTrackResolver {
return [
for (final af in audioFiles)
(
- source: api.buildFileUrl(itemId, af['ino']?.toString() ?? ''),
+ source: api.buildFileUrl(ids.itemId, af['ino']?.toString() ?? ''),
duration: (af['duration'] as num?)?.toDouble() ?? 0,
local: false,
),
diff --git a/lib/services/bookmark_service.dart b/lib/services/bookmark_service.dart
index 29978a78..44d140b1 100644
--- a/lib/services/bookmark_service.dart
+++ b/lib/services/bookmark_service.dart
@@ -1,8 +1,10 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
+import '../utils/episode_key.dart';
import 'api_service.dart';
import 'scoped_prefs.dart';
+import 'settings_sync_service.dart';
import 'user_account_service.dart';
/// A single bookmark in an audiobook.
@@ -108,6 +110,13 @@ class Bookmark {
}
/// Stores per-book bookmarks in SharedPreferences with server sync.
+///
+/// Podcast episodes are keyed by the compound "showId-episodeId" key. Those
+/// stay on the device: an ABS bookmark carries a library item id and nothing
+/// else, so a pushed episode bookmark would come back attached to the whole
+/// show, landing every episode's marks in one pile at times that mean nothing
+/// outside the episode they were made in. They travel between devices in the
+/// settings backup instead, which is why every local change nudges the sync.
class BookmarkService {
static final BookmarkService _instance = BookmarkService._();
factory BookmarkService() => _instance;
@@ -161,6 +170,23 @@ class BookmarkService {
}
}
+ // Episode bookmarks are local-only now. Older builds queued them for a
+ // push that the server can only 404, so clear out any that are still
+ // sitting in the queue instead of retrying them forever.
+ final strandedCreates =
+ _unpushed.where((k) => isEpisodeKey(k.split('::').first)).toList();
+ if (strandedCreates.isNotEmpty) {
+ _unpushed.removeAll(strandedCreates);
+ await _persistUnpushed();
+ }
+ final strandedDeletes = _pendingDeletes.keys.where(isEpisodeKey).toList();
+ if (strandedDeletes.isNotEmpty) {
+ for (final k in strandedDeletes) {
+ _pendingDeletes.remove(k);
+ }
+ await _persistPendingDeletes();
+ }
+
_hydratedScope = scope;
}
@@ -228,6 +254,11 @@ class BookmarkService {
await _ensureHydrated();
+ if (isEpisodeKey(itemId)) {
+ SettingsSyncService().noteLocalChange();
+ return bookmark;
+ }
+
// Flag the bookmark pending BEFORE pushing it to the server. If the app is
// suspended or killed mid-push (common on iOS right after bookmarking then
// pausing), the flag is already persisted, so the next sync keeps and
@@ -279,6 +310,11 @@ class BookmarkService {
await ScopedPrefs.setStringList(key, updated);
+ if (isEpisodeKey(itemId)) {
+ SettingsSyncService().noteLocalChange();
+ return;
+ }
+
// Update on server
if (api != null && time != null && serverTitle != null) {
await api.updateBookmark(itemId, time: time, title: serverTitle);
@@ -327,6 +363,12 @@ class BookmarkService {
await _ensureHydrated();
+ if (isEpisodeKey(itemId)) {
+ SettingsSyncService().noteLocalChange();
+ debugPrint('[Bookmarks] Moved $bookmarkId: ${oldTime}s -> ${newPos}s (local)');
+ return;
+ }
+
// The old position's pending-create (if any) no longer applies. Flag the
// new position pending BEFORE the network calls (same write-ahead reasoning
// as addBookmark) so a suspend or kill mid-move can't orphan the moved
@@ -379,6 +421,11 @@ class BookmarkService {
await _ensureHydrated();
+ if (isEpisodeKey(itemId)) {
+ SettingsSyncService().noteLocalChange();
+ return;
+ }
+
// If this bookmark was an unpushed offline create, drop the pending-create
// flag - the server never knew about it, so there's nothing to delete.
if (time != null) {
@@ -410,6 +457,10 @@ class BookmarkService {
/// 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 {
+ // Episode bookmarks never reach the server, so there is nothing to merge -
+ // and an empty server list here would read as "deleted everywhere" and
+ // wipe them.
+ if (isEpisodeKey(itemId)) return;
try {
await _ensureHydrated();
diff --git a/lib/services/settings_sync_service.dart b/lib/services/settings_sync_service.dart
index ea37a608..1bad5036 100644
--- a/lib/services/settings_sync_service.dart
+++ b/lib/services/settings_sync_service.dart
@@ -87,6 +87,10 @@ class SettingsSyncService {
/// [getSyncRmab].
/// - customDownloadPath: a path that is only true on one phone.
/// - offlineMode: a per-device switch.
+ ///
+ /// `podcastBookmarks` is here for the opposite reason: ABS bookmarks carry no
+ /// episode id, so those never reach the server and this is the only way they
+ /// reach another device. It is content, not a pending ledger.
static const _syncedKeys = <String>{
'settings',
'autoRewind',
@@ -108,6 +112,7 @@ class SettingsSyncService {
'librarySettings',
'metadataOverrides',
'ebookAnnotations',
+ 'podcastBookmarks',
'ereader',
'navHold',
'podcastPrefs',
diff --git a/lib/utils/episode_key.dart b/lib/utils/episode_key.dart
new file mode 100644
index 00000000..de88b2a0
--- /dev/null
+++ b/lib/utils/episode_key.dart
@@ -0,0 +1,17 @@
+/// Podcast episodes are addressed by a compound "showId-episodeId" key
+/// wherever the app stores per-item state - downloads, progress, bookmarks.
+/// Books keep their plain 36-character item id. These three helpers put the
+/// substring arithmetic in one place.
+library;
+
+bool isEpisodeKey(String key) => key.length > 36;
+
+String episodeKeyFor(String itemId, String? episodeId) =>
+ (episodeId != null && episodeId.isNotEmpty) ? '$itemId-$episodeId' : itemId;
+
+/// Split a storage key back into the item id the server knows and, for a
+/// podcast, the episode inside it.
+({String itemId, String? episodeId}) splitEpisodeKey(String key) =>
+ isEpisodeKey(key)
+ ? (itemId: key.substring(0, 36), episodeId: key.substring(37))
+ : (itemId: key, episodeId: null);
diff --git a/lib/widgets/bookmark_detail_dialog.dart b/lib/widgets/bookmark_detail_dialog.dart
index f6a558d1..45013149 100644
--- a/lib/widgets/bookmark_detail_dialog.dart
+++ b/lib/widgets/bookmark_detail_dialog.dart
@@ -15,6 +15,7 @@ import '../services/chapter_lookup.dart';
import '../services/download_service.dart';
import '../services/ebook_cache.dart';
import '../services/transcription_service.dart';
+import '../utils/episode_key.dart';
import '../utils/passage_match.dart';
import 'clip_editor_sheet.dart';
import 'overlay_toast.dart';
@@ -33,15 +34,23 @@ typedef BookmarkDetailResult = ({String action, double position});
/// the [ClipEditorSheet]. Persists on Save/Jump, then pops a [BookmarkDetailResult].
class BookmarkDetailSheet extends StatefulWidget {
final String itemId;
+
+ /// Set when the bookmark belongs to a podcast episode: storage, audio and
+ /// downloads are keyed 'itemId-episodeId', while anything the server answers
+ /// still goes by [itemId].
+ final String? episodeId;
final Bookmark bookmark;
final ApiService? api;
const BookmarkDetailSheet({
super.key,
required this.itemId,
+ this.episodeId,
required this.bookmark,
this.api,
});
+ String get _key => episodeKeyFor(itemId, episodeId);
+
@override
State<BookmarkDetailSheet> createState() => _BookmarkDetailSheetState();
}
@@ -72,7 +81,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
// self-heals to 0 if the user saves.
_seconds = widget.bookmark.positionSeconds < 0 ? 0.0 : widget.bookmark.positionSeconds;
_preview = BookmarkPreviewPlayer(
- itemId: widget.itemId, api: widget.api, label: 'bookmark')
+ itemId: widget._key, api: widget.api, label: 'bookmark')
..clipLength = const Duration(seconds: 60)
..addListener(_onPreview);
_loadDisplaySpeed();
@@ -86,6 +95,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
/// the cached copy first, then the item's metadata (fetched lazily at
/// transcribe time when it isn't cached yet).
Future<void> _resolveEpubForCrossRef() async {
+ if (widget.episodeId != null) return; // podcasts have no ebook to match
var ef = await cachedEbookFileFor(widget.itemId);
if (ef == null && widget.api != null) {
try {
@@ -100,7 +110,9 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
Future<void> _loadDisplaySpeed() async {
if (!await PlayerSettings.getSpeedAdjustedTime()) return;
final player = AudioPlayerService();
- final speed = player.currentItemId == widget.itemId
+ final speed = player.currentItemId == widget.itemId &&
+ (widget.episodeId == null ||
+ player.currentEpisodeId == widget.episodeId)
? player.speed
: (await PlayerSettings.getBookSpeed(widget.itemId) ??
await PlayerSettings.getDefaultSpeed());
@@ -157,7 +169,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
// iOS can't export from a streaming book, so prompt to download up front
// rather than letting the user trim a clip and only fail at Save. Android
// exports streamed clips fine, so it always opens the editor.
- if (Platform.isIOS && !DownloadService().isDownloaded(widget.itemId)) {
+ if (Platform.isIOS && !DownloadService().isDownloaded(widget._key)) {
await _promptDownload();
return;
}
@@ -170,7 +182,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
),
builder: (_) => ClipEditorSheet(
- itemId: widget.itemId,
+ itemId: widget._key,
bookmarkSeconds: _seconds,
bookmarkTitle:
_titleC.text.trim().isEmpty ? widget.bookmark.title : _titleC.text.trim(),
@@ -209,14 +221,25 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
var author = '';
try {
final item = await api.getLibraryItem(widget.itemId);
- final meta = (item?['media'] as Map<String, dynamic>?)?['metadata']
- as Map<String, dynamic>?;
+ final media = item?['media'] as Map<String, dynamic>? ?? const {};
+ final meta = media['metadata'] as Map<String, dynamic>?;
title = meta?['title'] as String? ?? title;
author = meta?['authorName'] as String? ?? '';
+ // A podcast bookmark downloads its own episode, under the episode's name.
+ if (widget.episodeId != null) {
+ final ep = ((media['episodes'] as List<dynamic>?) ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .where((e) => e['id'] == widget.episodeId)
+ .firstOrNull;
+ final epTitle = ep?['title'] as String?;
+ if (author.isEmpty) author = title;
+ if (epTitle != null && epTitle.isNotEmpty) title = epTitle;
+ }
} catch (_) {}
await DownloadService().downloadItem(
api: api,
- itemId: widget.itemId,
+ itemId: widget._key,
+ episodeId: widget.episodeId,
title: title,
author: author,
coverUrl: api.getCoverUrl(widget.itemId, width: 400),
@@ -271,7 +294,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
final l = AppLocalizations.of(context)!;
await _preview.stop();
if (!mounted) return;
- if (!TranscriptionService.instance.canTranscribeBook(widget.itemId)) {
+ if (!TranscriptionService.instance.canTranscribeBook(widget._key)) {
showOverlayToast(context, l.transcriptionNotDownloadedBook,
icon: Icons.download_rounded);
return;
@@ -348,7 +371,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
String? error;
try {
final result = await TranscriptionService.instance.transcribeAt(
- itemId: widget.itemId,
+ itemId: widget._key,
positionSeconds: _seconds,
windowSeconds: window.toDouble(),
preferAccuracy: _epubForCrossRef == null,
@@ -406,7 +429,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
if (!mounted) return;
await showQuoteShareSheet(
context,
- itemId: widget.itemId,
+ itemId: widget._key,
quote: quote,
bookTitle: meta.title,
author: meta.author,
@@ -422,17 +445,19 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
final player = AudioPlayerService();
List<dynamic> chapters = const [];
double duration = 0;
- if (player.currentItemId == widget.itemId) {
+ if (player.currentItemId == widget.itemId &&
+ (widget.episodeId == null ||
+ player.currentEpisodeId == widget.episodeId)) {
chapters = player.chapters;
duration = player.totalDuration;
}
- final info = DownloadService().getInfo(widget.itemId);
+ final info = DownloadService().getInfo(widget._key);
String? title = info.title;
String? author = info.author;
if (chapters.isEmpty) {
- final raw = DownloadService().getCachedSessionData(widget.itemId);
+ final raw = DownloadService().getCachedSessionData(widget._key);
if (raw != null && raw.isNotEmpty) {
try {
final session = jsonDecode(raw) as Map<String, dynamic>;
@@ -449,13 +474,25 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
final item = await widget.api!.getLibraryItem(widget.itemId);
final media = item?['media'] as Map<String, dynamic>? ?? {};
final meta = media['metadata'] as Map<String, dynamic>? ?? {};
- if ((title ?? '').isEmpty) title = meta['title'] as String?;
- if ((author ?? '').isEmpty) author = meta['authorName'] as String?;
+ final ep = widget.episodeId == null
+ ? null
+ : ((media['episodes'] as List<dynamic>?) ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .where((e) => e['id'] == widget.episodeId)
+ .firstOrNull;
+ if ((title ?? '').isEmpty) {
+ title = (ep?['title'] as String?) ?? meta['title'] as String?;
+ }
+ if ((author ?? '').isEmpty) {
+ author = (meta['authorName'] as String?) ??
+ (ep != null ? meta['title'] as String? : null);
+ }
if (chapters.isEmpty) {
- chapters = media['chapters'] as List<dynamic>? ?? const [];
+ chapters = (ep?['chapters'] ?? media['chapters']) as List<dynamic>? ??
+ const [];
}
if (duration <= 0) {
- duration = (media['duration'] as num?)?.toDouble() ?? 0;
+ duration = ((ep?['duration'] ?? media['duration']) as num?)?.toDouble() ?? 0;
}
} catch (_) {}
}
@@ -479,7 +516,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
final newNote = _noteC.text.trim();
final svc = BookmarkService();
await svc.updateBookmark(
- itemId: widget.itemId,
+ itemId: widget._key,
bookmarkId: widget.bookmark.id,
title: newTitle,
note: newNote,
@@ -487,7 +524,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {
);
if ((_seconds - widget.bookmark.positionSeconds).abs() >= 0.05) {
await svc.moveBookmark(
- itemId: widget.itemId,
+ itemId: widget._key,
bookmarkId: widget.bookmark.id,
newPositionSeconds: _seconds,
api: widget.api,
diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dart
index 63589592..3131ccb1 100644
--- a/lib/widgets/card_buttons.dart
+++ b/lib/widgets/card_buttons.dart
@@ -17,6 +17,7 @@ import '../services/equalizer_service.dart';
import '../services/playback_history_service.dart';
import '../services/scoped_prefs.dart';
import '../services/sleep_timer_service.dart';
+import '../utils/episode_key.dart';
import 'absorb_slider.dart';
import 'absorbing_shared.dart';
import 'book_detail_sheet.dart';
@@ -430,11 +431,17 @@ class CardBookmarkButtonInline extends StatefulWidget {
final Color accent;
final bool isActive;
final String itemId;
+ final String? episodeId;
final bool large;
final bool compact;
final bool short;
final bool iconsOnly;
- const CardBookmarkButtonInline({super.key, required this.player, required this.accent, required this.isActive, required this.itemId, this.large = false, this.compact = false, this.short = false, this.iconsOnly = false});
+ const CardBookmarkButtonInline({super.key, required this.player, required this.accent, required this.isActive, required this.itemId, this.episodeId, this.large = false, this.compact = false, this.short = false, this.iconsOnly = false});
+
+ // Podcast bookmarks are keyed 'showId-episodeId' so each episode keeps its
+ // own; books use the plain itemId.
+ String get _key => episodeKeyFor(itemId, episodeId);
+
@override State<CardBookmarkButtonInline> createState() => _CardBookmarkButtonInlineState();
}
@@ -447,17 +454,19 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
_loadCount();
// Then sync with server and update. The player's api is null when no book
// is loaded (browsing a not-playing book), so fall back to the signed-in
- // one - server bookmarks should appear either way.
+ // one - server bookmarks should appear either way. Episode bookmarks never
+ // go to the server, so there is nothing to wait for.
+ if (widget.episodeId != null) return;
final api = AudioPlayerService().currentApi ??
(mounted ? context.read<AuthProvider>().apiService : null);
if (api != null) {
- await BookmarkService().syncBookmarks(widget.itemId, api);
+ await BookmarkService().syncBookmarks(widget._key, api);
_loadCount();
}
}
Future<void> _loadCount() async {
- final c = await BookmarkService().getCount(widget.itemId);
+ final c = await BookmarkService().getCount(widget._key);
if (mounted) setState(() => _count = c);
}
@@ -517,7 +526,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 ?? l.bookmark, api: AudioPlayerService().currentApi);
+ await BookmarkService().addBookmark(itemId: widget._key, positionSeconds: pos, title: chTitle ?? l.bookmark, api: AudioPlayerService().currentApi);
_loadCount();
if (ctx.mounted) {
showOverlayToast(ctx, l.bookmarkAdded,
@@ -530,7 +539,7 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {
context: context, backgroundColor: Colors.transparent, isScrollControlled: true, useSafeArea: true,
builder: (ctx) => DraggableScrollableSheet(
initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9, expand: false,
- builder: (ctx, sc) => SimpleBookmarkSheet(itemId: widget.itemId, player: widget.player, accent: widget.accent, scrollController: sc, onChanged: _loadCount),
+ builder: (ctx, sc) => SimpleBookmarkSheet(itemId: widget.itemId, episodeId: widget.episodeId, player: widget.player, accent: widget.accent, scrollController: sc, onChanged: _loadCount),
),
);
}
@@ -780,8 +789,12 @@ class _CardSpeedSheetState extends State<CardSpeedSheet> {
// ─── BOOKMARK SHEET ──────────────────────────────────────────
class SimpleBookmarkSheet extends StatefulWidget {
- final String itemId; final AudioPlayerService player; final Color accent; final ScrollController scrollController; final VoidCallback onChanged;
- const SimpleBookmarkSheet({super.key, required this.itemId, required this.player, required this.accent, required this.scrollController, required this.onChanged});
+ final String itemId; final String? episodeId; final AudioPlayerService player; final Color accent; final ScrollController scrollController; final VoidCallback onChanged;
+ const SimpleBookmarkSheet({super.key, required this.itemId, this.episodeId, required this.player, required this.accent, required this.scrollController, required this.onChanged});
+
+ /// Storage key: 'showId-episodeId' for a podcast episode, the item id for a
+ /// book. [itemId] stays the library item for anything the server answers.
+ String get _key => episodeKeyFor(itemId, episodeId);
@override State<SimpleBookmarkSheet> createState() => _SimpleBookmarkSheetState();
}
@@ -817,19 +830,20 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
// background and refresh with whatever it pulled in. The player's api is
// null when this book isn't loaded - fall back to the signed-in one.
await _load();
+ if (widget.episodeId != null) return; // episode bookmarks stay local
final api = AudioPlayerService().currentApi ??
(mounted ? context.read<AuthProvider>().apiService : null);
if (api != null) {
try {
await BookmarkService()
- .syncBookmarks(widget.itemId, api)
+ .syncBookmarks(widget._key, api)
.timeout(const Duration(seconds: 12));
} catch (_) {}
await _load();
}
}
Future<void> _load() async {
- final bm = await BookmarkService().getBookmarks(widget.itemId, sort: _sort);
+ final bm = await BookmarkService().getBookmarks(widget._key, sort: _sort);
if (mounted) setState(() => _bookmarks = bm);
widget.onChanged();
}
@@ -912,6 +926,7 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
),
builder: (_) => BookmarkDetailSheet(
itemId: widget.itemId,
+ episodeId: widget.episodeId,
bookmark: bm,
api: context.read<AuthProvider>().apiService,
),
@@ -922,7 +937,9 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
return;
}
final position = result.position;
- final isActive = widget.player.currentItemId == widget.itemId;
+ final isActive = widget.player.currentItemId == widget.itemId &&
+ (widget.episodeId == null ||
+ widget.player.currentEpisodeId == widget.episodeId);
Navigator.pop(ctx); // Close bookmark sheet first
if (isActive || _isCasting) {
final seekDur = Duration(seconds: position.round());
@@ -1012,7 +1029,7 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
);
if (!mounted || confirmed != true) return;
await BookmarkService().deleteBookmark(
- itemId: widget.itemId,
+ itemId: widget._key,
bookmarkId: bookmark.id,
api: AudioPlayerService().currentApi,
);
@@ -1034,14 +1051,32 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
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>?) ?? [];
+ var author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(widget._key);
+ var duration = (media['duration'] is num) ? (media['duration'] as num).toDouble() : 0.0;
+ var chapters = (media['chapters'] as List<dynamic>?) ?? [];
+ // A podcast bookmark belongs to one episode, so play that episode - its
+ // own duration and chapters, not the show's.
+ String? episodeTitle;
+ final epId = widget.episodeId;
+ if (epId != null) {
+ final ep = ((media['episodes'] as List<dynamic>?) ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .where((e) => e['id'] == epId)
+ .firstOrNull;
+ if (ep == null) return;
+ episodeTitle = ep['title'] as String?;
+ if (author.isEmpty) author = title; // the show stands in for the author
+ duration = (ep['duration'] as num?)?.toDouble() ??
+ ((ep['audioFile'] as Map<String, dynamic>?)?['duration'] as num?)?.toDouble() ??
+ 0.0;
+ chapters = (ep['chapters'] as List<dynamic>?) ?? const [];
+ }
await player.playItem(
api: api, itemId: widget.itemId,
- title: title, author: author, coverUrl: coverUrl,
+ title: episodeTitle ?? title, author: author, coverUrl: coverUrl,
totalDuration: duration, chapters: chapters,
+ episodeId: epId, episodeTitle: episodeTitle,
startTime: positionSeconds, forceStartTime: true,
libraryId: fullItem['libraryId'] as String?,
);
@@ -1095,7 +1130,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, api: AudioPlayerService().currentApi);
+ await BookmarkService().addBookmark(itemId: widget._key, positionSeconds: pos, title: result['title']!, note: note, api: AudioPlayerService().currentApi);
_load();
}
}
@@ -1129,7 +1164,7 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
));
if (result != null && result['title']!.isNotEmpty) {
await BookmarkService().updateBookmark(
- itemId: widget.itemId, bookmarkId: bm.id,
+ itemId: widget._key, bookmarkId: bm.id,
title: result['title']!, note: result['note']?.isNotEmpty == true ? result['note'] : null,
api: AudioPlayerService().currentApi,
);
@@ -1500,6 +1535,11 @@ class CardActionDelegate {
Map<String, dynamic> get _media => item['media'] as Map<String, dynamic>? ?? {};
+ /// Which episode the bookmark surfaces belong to. A card that knows its own
+ /// episode wins; an active podcast card falls back to what is playing.
+ String? get _bookmarkEpisodeId =>
+ episodeId ?? (isPodcastEpisode ? player.currentEpisodeId : null);
+
int get visibleButtonCount => visibleCount;
// Predefined row groupings per button count.
@@ -1637,7 +1677,8 @@ class CardActionDelegate {
accent: accent, isActive: isPlaybackActive, large: large, compact: compact, iconsOnly: iconsOnly,
child: CardBookmarkButtonInline(
player: player, accent: accent,
- isActive: isActive, itemId: itemId, large: large, compact: compact, short: short, iconsOnly: iconsOnly,
+ isActive: isActive, itemId: itemId, episodeId: _bookmarkEpisodeId,
+ large: large, compact: compact, short: short, iconsOnly: iconsOnly,
),
);
case 'details':
@@ -1791,7 +1832,7 @@ class CardActionDelegate {
showModalBottomSheet(context: context, backgroundColor: Colors.transparent, isScrollControlled: true, useSafeArea: true,
builder: (_) => DraggableScrollableSheet(
initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9, expand: false,
- builder: (_, sc) => SimpleBookmarkSheet(itemId: itemId, player: player, accent: accent, scrollController: sc, onChanged: () {}),
+ builder: (_, sc) => SimpleBookmarkSheet(itemId: itemId, episodeId: _bookmarkEpisodeId, player: player, accent: accent, scrollController: sc, onChanged: () {}),
),
);
},