A cross platform Audiobookshelf client for Android and iOS
Dart
Fix podcast subscription auto-download and absorbing, add subscribed bell overlay
Nathan Poulsonbaf57f1ae3c1
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 68282e0a..a5b02456 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -120,6 +120,17 @@ class LibraryProvider extends ChangeNotifier {Future<void> subscribePodcast(String podcastId) async {_subscribedPodcasts.add(podcastId);await _saveSubscribedPodcasts();+ // Seed the known episode IDs so future updates can detect new ones.+ final item = await _api?.getLibraryItem(podcastId);+ if (item != null) {+ final media = item['media'] as Map<String, dynamic>? ?? {};+ final episodes = media['episodes'] as List<dynamic>? ?? [];+ final ids = episodes+ .map((e) => (e as Map<String, dynamic>)['id'] as String?)+ .whereType<String>()+ .toSet();+ _knownEpisodeIds[podcastId] = ids;+ }notifyListeners();}@@ -594,6 +605,7 @@ class LibraryProvider extends ChangeNotifier {socket.onSeriesUpdated = _onRemoteSeriesUpdated;socket.onCollectionUpdated = _onRemoteCollectionUpdated;socket.onUserUpdated = _onRemoteUserUpdated;+ socket.onReconnectFailed = _onSocketReconnectFailed;socket.connect(auth.serverUrl!, auth.token!);}debugPrint('[Library] Calling loadLibraries()');@@ -804,6 +816,12 @@ class LibraryProvider extends ChangeNotifier {error is HttpException;}+ /// Socket.IO exhausted all reconnection attempts - server is unreachable.+ void _onSocketReconnectFailed() {+ debugPrint('[Library] Socket reconnection failed — going offline');+ _goOffline();+ }+/// Go offline due to a network error. Builds offline sections and starts/// pinging the server for recovery if the device still has connectivity.void _goOffline() {@@ -3100,8 +3118,9 @@ class LibraryProvider extends ChangeNotifier {// ── Podcast subscriptions ──- /// Track known episode counts per podcast so we can detect new ones.- final Map<String, int> _knownEpisodeCounts = {};+ /// Track known episode IDs per podcast so we can detect new ones+ /// regardless of position or date.+ final Map<String, Set<String>> _knownEpisodeIds = {};/// Called when a library item is updated via socket. If it's a subscribed/// podcast with more episodes than we last knew about, auto-download and@@ -3115,25 +3134,50 @@ class LibraryProvider extends ChangeNotifier {final mediaType = data['mediaType'] as String?;if (mediaType != 'podcast') return;- final media = data['media'] as Map<String, dynamic>? ?? {};+ // Socket payloads may not include the full episode list, so fetch the+ // complete item from the API to get accurate episode data.+ _fetchAndCheckSubscribedPodcast(itemId);+ }++ /// Fetch the full podcast item and check for new episodes.+ Future<void> _fetchAndCheckSubscribedPodcast(String itemId) async {+ if (_api == null || isOffline) return;++ final item = await _api!.getLibraryItem(itemId);+ if (item == null) return;++ final media = item['media'] as Map<String, dynamic>? ?? {};final episodes = media['episodes'] as List<dynamic>? ?? [];- final currentCount = episodes.length;- final knownCount = _knownEpisodeCounts[itemId] ?? 0;+ final knownIds = _knownEpisodeIds[itemId];++ if (knownIds == null) {+ // First time seeing this podcast - seed and return+ final ids = episodes+ .map((e) => (e as Map<String, dynamic>)['id'] as String?)+ .whereType<String>()+ .toSet();+ _knownEpisodeIds[itemId] = ids;+ return;+ }- if (knownCount > 0 && currentCount > knownCount) {- // New episodes detected- final newEpisodes = episodes.sublist(0, currentCount - knownCount);- debugPrint('[Subscription] ${currentCount - knownCount} new episode(s) for $itemId');+ // Find episodes we haven't seen before+ final newEpisodes = <Map<String, dynamic>>[];+ for (final ep in episodes) {+ final epMap = ep as Map<String, dynamic>;+ final epId = epMap['id'] as String?;+ if (epId != null && !knownIds.contains(epId)) {+ newEpisodes.add(epMap);+ }+ }+ if (newEpisodes.isNotEmpty) {+ debugPrint('[Subscription] ${newEpisodes.length} new episode(s) for $itemId');int queued = 0;- for (final ep in newEpisodes) {- final epMap = ep as Map<String, dynamic>;- final epId = epMap['id'] as String?;- if (epId == null) continue;+ for (final epMap in newEpisodes) {+ final epId = epMap['id'] as String;final key = '$itemId-$epId';- // Add to absorbing queue_absorbingIdsAdd(key, atFront: true);_absorbingItemCache[key] = {'id': itemId,@@ -3142,33 +3186,39 @@ class LibraryProvider extends ChangeNotifier {'recentEpisode': epMap,'media': media,};+ // Protect from pruning - no progress yet so _updateAbsorbingCache+ // would remove it without this.+ _manualAbsorbAdds.add(key);+ _manualAbsorbRemoves.remove(key);+ knownIds.add(epId);queued++;}if (queued > 0) {_saveManualAbsorbing();notifyListeners();- // Download in background (respects WiFi-only setting)_downloadSubscribedEpisodes(itemId);}}-- _knownEpisodeCounts[itemId] = currentCount;}- /// Seed known episode counts for subscribed podcasts so the first+ /// Seed known episode IDs for subscribed podcasts so the first/// socket update doesn't treat all existing episodes as new.Future<void> seedSubscribedPodcastCounts() async {if (_subscribedPodcasts.isEmpty || _api == null) return;for (final podcastId in _subscribedPodcasts) {- if (_knownEpisodeCounts.containsKey(podcastId)) continue;+ if (_knownEpisodeIds.containsKey(podcastId)) continue;try {final item = await _api!.getLibraryItem(podcastId);if (item == null) continue;final media = item['media'] as Map<String, dynamic>? ?? {};final episodes = media['episodes'] as List<dynamic>? ?? [];- _knownEpisodeCounts[podcastId] = episodes.length;- debugPrint('[Subscription] Seeded $podcastId with ${episodes.length} episodes');+ final ids = episodes+ .map((e) => (e as Map<String, dynamic>)['id'] as String?)+ .whereType<String>()+ .toSet();+ _knownEpisodeIds[podcastId] = ids;+ debugPrint('[Subscription] Seeded $podcastId with ${ids.length} episodes');} catch (e) {debugPrint('[Subscription] Failed to seed $podcastId: $e');}diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dartindex cd3afc19..ddf40f21 100644--- a/lib/services/socket_service.dart+++ b/lib/services/socket_service.dart@@ -41,6 +41,9 @@ class SocketService {/// Called when the current user's data changes on the server.void Function(Map<String, dynamic> data)? onUserUpdated;+ /// Called when socket.io exhausts all reconnection attempts.+ VoidCallback? onReconnectFailed;+void connect(String serverUrl, String token) {if (_socket != null) disconnect();@@ -135,6 +138,7 @@ class SocketService {debugPrint('[Socket] Reconnection attempts exhausted — giving up');_socket?.dispose();_socket = null;+ onReconnectFailed?.call();});} catch (e) {debugPrint('[Socket] Failed to connect: $e');@@ -156,6 +160,7 @@ class SocketService {onSeriesUpdated = null;onCollectionUpdated = null;onUserUpdated = null;+ onReconnectFailed = null;}/// Disconnect the socket but keep callbacks and credentials so we can@@ -246,6 +251,7 @@ class SocketService {debugPrint('[Socket] Reconnection attempts exhausted — giving up');_socket?.dispose();_socket = null;+ onReconnectFailed?.call();});} catch (e) {debugPrint('[Socket] Failed to reconnect: $e');diff --git a/lib/widgets/home_section.dart b/lib/widgets/home_section.dartindex 3004fabb..a404c9fd 100644--- a/lib/widgets/home_section.dart+++ b/lib/widgets/home_section.dart@@ -254,6 +254,7 @@ class _EpisodeCard extends StatelessWidget {final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final showTitle = metadata['title'] as String? ?? '';final coverUrl = lib.getCoverUrl(itemId);+ final isSubscribed = lib.isPodcastSubscribed(itemId);// Get episode info from recentEpisodefinal episode = item['recentEpisode'] as Map<String, dynamic>?;@@ -304,6 +305,21 @@ class _EpisodeCard extends StatelessWidget {child: Icon(Icons.podcasts_rounded, size: 32,color: cs.onSurfaceVariant.withValues(alpha: 0.3)),),+ // Subscribed bell+ if (isSubscribed)+ Positioned(+ top: 4,+ right: 4,+ child: Container(+ padding: const EdgeInsets.all(3),+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.6),+ shape: BoxShape.circle,+ ),+ child: const Icon(Icons.notifications_rounded,+ size: 11, color: Colors.white),+ ),+ ),],),),diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dartindex 5eade36a..b12919eb 100644--- a/lib/widgets/library_grid_tiles.dart+++ b/lib/widgets/library_grid_tiles.dart@@ -57,6 +57,7 @@ class _GridBookTileState extends State<GridBookTile> {final progress = lib.getProgress(itemId);final isDownloaded = _dl.isDownloaded(itemId);final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;+ final isSubscribed = lib.isPodcastLibrary && lib.isPodcastSubscribed(itemId);return GestureDetector(onTap: () {@@ -107,6 +108,22 @@ class _GridBookTileState extends State<GridBookTile> {),),+ // Subscribed bell+ if (isSubscribed)+ Positioned(+ top: 4,+ right: 4,+ child: Container(+ padding: const EdgeInsets.all(3),+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.6),+ shape: BoxShape.circle,+ ),+ child: const Icon(Icons.notifications_rounded,+ size: 11, color: Colors.white),+ ),+ ),+// ── Banners ──if (isFinished || isDownloaded)Positioned(