Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Chapter-snap rewind, podcast subscriptions, offline listening stats, play button fix, widget radius, log auto-clear

Nathan Poulson9e1ef58e1e97
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt
index 6242a93f..05c863ee 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt
@@ -66,22 +66,19 @@ class NowPlayingWidget : AppWidgetProvider() {
private fun roundBitmap(bitmap: Bitmap, radiusDp: Float, context: Context): Bitmap {
val density = context.resources.displayMetrics.density
- val radiusPx = radiusDp * density
- // Scale bitmap to a consistent size so corner radius maps correctly
- val maxPx = (150 * density).toInt()
- val src = if (maxOf(bitmap.width, bitmap.height) > maxPx) {
- val scale = maxPx.toFloat() / maxOf(bitmap.width, bitmap.height)
- Bitmap.createScaledBitmap(bitmap, (bitmap.width * scale).toInt(), (bitmap.height * scale).toInt(), true)
- } else {
- bitmap
- }
- val output = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)
+ // Scale radius relative to the bitmap so corners look correct
+ // after the ImageView's centerCrop scales the bitmap to fit.
+ // Target: cover displays at ~150dp, so ratio = bitmapPx / 150dp_in_px.
+ val displayPx = 150f * density
+ val scale = minOf(bitmap.width, bitmap.height).toFloat() / displayPx
+ val radiusPx = radiusDp * density * scale
+ val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(output)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
- val rect = RectF(0f, 0f, src.width.toFloat(), src.height.toFloat())
+ val rect = RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat())
canvas.drawRoundRect(rect, radiusPx, radiusPx, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
- canvas.drawBitmap(src, 0f, 0f, paint)
+ canvas.drawBitmap(bitmap, 0f, 0f, paint)
return output
}
@@ -159,7 +156,7 @@ class NowPlayingWidget : AppWidgetProvider() {
val options = BitmapFactory.Options().apply { inSampleSize = 2 }
val bitmap = BitmapFactory.decodeFile(file.absolutePath, options)
if (bitmap != null) {
- views.setImageViewBitmap(R.id.widget_cover, roundBitmap(bitmap, 24f, context))
+ views.setImageViewBitmap(R.id.widget_cover, roundBitmap(bitmap, 18f, context))
} else {
views.setImageViewResource(R.id.widget_cover, R.mipmap.ic_launcher)
}
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt
index a2afb2e0..4db8bf0f 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt
@@ -63,22 +63,18 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {
private fun roundBitmap(bitmap: Bitmap, radiusDp: Float, context: Context): Bitmap {
val density = context.resources.displayMetrics.density
- val radiusPx = radiusDp * density
- // Scale bitmap to a consistent size so corner radius maps correctly
- val maxPx = (150 * density).toInt()
- val src = if (maxOf(bitmap.width, bitmap.height) > maxPx) {
- val scale = maxPx.toFloat() / maxOf(bitmap.width, bitmap.height)
- Bitmap.createScaledBitmap(bitmap, (bitmap.width * scale).toInt(), (bitmap.height * scale).toInt(), true)
- } else {
- bitmap
- }
- val output = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)
+ // Scale radius relative to the bitmap so corners look correct
+ // after the ImageView's centerCrop scales the bitmap to fit.
+ val displayPx = 150f * density
+ val scale = minOf(bitmap.width, bitmap.height).toFloat() / displayPx
+ val radiusPx = radiusDp * density * scale
+ val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(output)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
- val rect = RectF(0f, 0f, src.width.toFloat(), src.height.toFloat())
+ val rect = RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat())
canvas.drawRoundRect(rect, radiusPx, radiusPx, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
- canvas.drawBitmap(src, 0f, 0f, paint)
+ canvas.drawBitmap(bitmap, 0f, 0f, paint)
return output
}
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 96c33c44..68282e0a 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -111,6 +111,42 @@ class LibraryProvider extends ChangeNotifier {
'rolling_download_series', _rollingDownloadSeries.toList());
}
+ // Per-podcast subscription (auto-download + queue new episodes)
+ Set<String> _subscribedPodcasts = {};
+
+ bool isPodcastSubscribed(String podcastId) =>
+ _subscribedPodcasts.contains(podcastId);
+
+ Future<void> subscribePodcast(String podcastId) async {
+ _subscribedPodcasts.add(podcastId);
+ await _saveSubscribedPodcasts();
+ notifyListeners();
+ }
+
+ Future<void> unsubscribePodcast(String podcastId) async {
+ _subscribedPodcasts.remove(podcastId);
+ await _saveSubscribedPodcasts();
+ notifyListeners();
+ }
+
+ Future<void> togglePodcastSubscription(String podcastId) async {
+ if (_subscribedPodcasts.contains(podcastId)) {
+ await unsubscribePodcast(podcastId);
+ } else {
+ await subscribePodcast(podcastId);
+ }
+ }
+
+ Future<void> _loadSubscribedPodcasts() async {
+ _subscribedPodcasts =
+ (await ScopedPrefs.getStringList('subscribed_podcasts')).toSet();
+ }
+
+ Future<void> _saveSubscribedPodcasts() async {
+ await ScopedPrefs.setStringList(
+ 'subscribed_podcasts', _subscribedPodcasts.toList());
+ }
+
// Offline mode
bool _manualOffline = false;
bool _networkOffline = false;
@@ -139,6 +175,7 @@ class LibraryProvider extends ChangeNotifier {
if (_api != null) {
debugPrint('[Library] Manual offline off — flushing pending syncs');
ProgressSyncService().flushPendingSync(api: _api!);
+ ProgressSyncService().flushOfflineListeningTime(api: _api!);
}
if (_selectedLibraryId == null) {
loadLibraries();
@@ -181,6 +218,7 @@ class LibraryProvider extends ChangeNotifier {
if (_api != null) {
debugPrint('[Library] Back online — flushing pending syncs');
ProgressSyncService().flushPendingSync(api: _api!);
+ ProgressSyncService().flushOfflineListeningTime(api: _api!);
}
if (_selectedLibraryId == null) {
loadLibraries();
@@ -525,6 +563,10 @@ class LibraryProvider extends ChangeNotifier {
_startConnectivityMonitoring();
_loadManualAbsorbing();
await _loadRollingDownloadSeries();
+ await _loadSubscribedPodcasts();
+ // Seed episode counts in the background so first socket update
+ // doesn't treat all existing episodes as new.
+ Future.microtask(() => seedSubscribedPodcastCounts());
// If server was unreachable on startup, force offline mode and ping
if (!auth.serverReachable) {
@@ -540,6 +582,7 @@ class LibraryProvider extends ChangeNotifier {
_buildProgressMap(auth);
if (_api != null && !isOffline) {
ProgressSyncService().flushPendingSync(api: _api!);
+ ProgressSyncService().flushOfflineListeningTime(api: _api!);
DownloadService().enrichMetadata(_api!);
}
// Connect Socket.IO for online presence + cross-device sync
@@ -631,6 +674,7 @@ class LibraryProvider extends ChangeNotifier {
_auth?.checkLocalServer();
if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();
_catchUpQueueAutoDownloads();
+ catchUpSubscribedPodcasts();
} else {
// WiFi dropped but still have connectivity (e.g. mobile data) —
// local server won't be reachable, revert to remote URL.
@@ -816,6 +860,8 @@ class LibraryProvider extends ChangeNotifier {
void _onRemoteItemUpdated(Map<String, dynamic> data) {
// Refresh the personalized view so new/updated items appear
loadPersonalizedView(force: true);
+ // Check if a subscribed podcast has new episodes
+ _checkSubscribedPodcastUpdate(data);
}
/// Handle library item removed from socket.
@@ -942,6 +988,7 @@ class LibraryProvider extends ChangeNotifier {
// or WiFi wasn't available when the download should have triggered)
_catchUpRollingDownloads();
_catchUpQueueAutoDownloads();
+ catchUpSubscribedPodcasts();
}
/// Change the selected library and reload data.
@@ -3051,6 +3098,140 @@ class LibraryProvider extends ChangeNotifier {
));
}
+ // ── Podcast subscriptions ──
+
+ /// Track known episode counts per podcast so we can detect new ones.
+ final Map<String, int> _knownEpisodeCounts = {};
+
+ /// 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
+ /// queue the new ones.
+ void _checkSubscribedPodcastUpdate(Map<String, dynamic> data) {
+ if (_subscribedPodcasts.isEmpty || _api == null || isOffline) return;
+
+ final itemId = data['id'] as String?;
+ if (itemId == null || !_subscribedPodcasts.contains(itemId)) return;
+
+ final mediaType = data['mediaType'] as String?;
+ if (mediaType != 'podcast') return;
+
+ final media = data['media'] as Map<String, dynamic>? ?? {};
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ final currentCount = episodes.length;
+ final knownCount = _knownEpisodeCounts[itemId] ?? 0;
+
+ if (knownCount > 0 && currentCount > knownCount) {
+ // New episodes detected
+ final newEpisodes = episodes.sublist(0, currentCount - knownCount);
+ debugPrint('[Subscription] ${currentCount - knownCount} 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;
+ final key = '$itemId-$epId';
+
+ // Add to absorbing queue
+ _absorbingIdsAdd(key, atFront: true);
+ _absorbingItemCache[key] = {
+ 'id': itemId,
+ 'mediaType': 'podcast',
+ '_absorbingKey': key,
+ 'recentEpisode': epMap,
+ 'media': media,
+ };
+ 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
+ /// 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;
+ 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');
+ } catch (e) {
+ debugPrint('[Subscription] Failed to seed $podcastId: $e');
+ }
+ }
+ }
+
+ /// Download queued episodes for a subscribed podcast, respecting WiFi-only.
+ Future<void> _downloadSubscribedEpisodes(String podcastId) async {
+ if (_api == null || isOffline) return;
+ final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
+ if (wifiOnly) {
+ final connectivity = await Connectivity().checkConnectivity();
+ if (!connectivity.contains(ConnectivityResult.wifi)) {
+ debugPrint('[Subscription] Skipping download (not on WiFi) - will retry on WiFi');
+ return;
+ }
+ }
+
+ final dl = DownloadService();
+ int downloaded = 0;
+
+ for (final key in _absorbingBookIds) {
+ if (!key.startsWith(podcastId)) continue;
+ if (dl.isDownloaded(key) || dl.isDownloading(key)) continue;
+
+ final cached = _absorbingItemCache[key];
+ final epId = key.substring(37);
+ final ep = cached?['recentEpisode'] as Map<String, dynamic>?;
+ final media = cached?['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+
+ dl.downloadItem(
+ api: _api!,
+ itemId: key,
+ title: ep?['title'] as String? ?? 'Episode',
+ author: metadata['title'] as String? ?? '',
+ coverUrl: getCoverUrl(podcastId),
+ episodeId: epId,
+ );
+ downloaded++;
+ }
+
+ if (downloaded > 0) {
+ final cached = _absorbingItemCache.values.firstWhere(
+ (c) => (c['id'] as String?) == podcastId,
+ orElse: () => {},
+ );
+ final media = cached['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final showTitle = metadata['title'] as String? ?? 'Podcast';
+ _showRollingSnackBar('$showTitle: $downloaded new episode${downloaded == 1 ? '' : 's'} downloading');
+ }
+ }
+
+ /// Catch up on subscribed podcast downloads - called on WiFi reconnect
+ /// and app startup.
+ Future<void> catchUpSubscribedPodcasts() async {
+ if (_subscribedPodcasts.isEmpty || _api == null || isOffline) return;
+ for (final podcastId in _subscribedPodcasts) {
+ await _downloadSubscribedEpisodes(podcastId);
+ }
+ }
+
/// Check if a book/episode is on the absorbing page (persisted local list, not removed).
/// [key] can be a plain itemId (books) or compound "itemId-episodeId" (podcasts).
bool isOnAbsorbingList(String key) {
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 921d8e28..b3883b93 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1198,6 +1198,7 @@ class AudioPlayerService extends ChangeNotifier {
if (_trackStartOffsets.length <= 1) {
// Single file — seek directly
await _player!.seek(Duration(milliseconds: (absoluteSeconds * 1000).round()));
+ notifyListeners();
return;
}
// Multi-file — find the right track and local offset
@@ -1209,6 +1210,7 @@ class AudioPlayerService extends ChangeNotifier {
// Update index BEFORE seeking so positionStream events use the right offset
_currentTrackIndex = i;
await _player!.seek(Duration(milliseconds: (localOffset * 1000).round()), index: i);
+ notifyListeners();
return;
}
}
@@ -2179,6 +2181,10 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Player] processingState → completed');
_onPlaybackComplete();
}
+ // Notify UI when buffering/loading state changes so spinners update
+ if (state == ProcessingState.ready || state == ProcessingState.loading || state == ProcessingState.buffering) {
+ notifyListeners();
+ }
}, onError: (Object e, StackTrace st) {
debugPrint('[Player] processingState stream error: $e');
_attemptStreamRetry(e);
@@ -2262,6 +2268,14 @@ class AudioPlayerService extends ChangeNotifier {
final prefs = await SharedPreferences.getInstance();
final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
+ if (manualOffline || _isOfflineMode || _playbackSessionId == null) {
+ // Offline or no session - accumulate listening time locally
+ final progressKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ _progressSync.addOfflineListeningTime(progressKey, 60);
+ }
+
if (manualOffline) {
// Manual offline — local save only, no server sync
} else if (!_isOfflineMode && _playbackSessionId != null) {
@@ -2411,7 +2425,7 @@ class AudioPlayerService extends ChangeNotifier {
if (_api == null || _playbackSessionId == null) return;
final ct = pos.inMilliseconds / 1000.0;
final now = DateTime.now();
- final elapsed = now.difference(_lastServerSync).inSeconds.clamp(0, 120);
+ final elapsed = now.difference(_lastServerSync).inSeconds.clamp(0, 300);
_lastServerSync = now;
try {
await _api!.syncPlaybackSession(
@@ -2574,14 +2588,42 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Service] skipForward done — playing=${_player!.playing}');
}
+ DateTime? _lastRewindChapterSnap;
+
Future<void> skipBackward([int seconds = 10]) async {
if (_player == null) return;
- debugPrint('[Service] skipBackward(${seconds}s) — playing=${_player!.playing}');
- var n = position - Duration(seconds: seconds);
- if (n < Duration.zero) n = Duration.zero;
- await _seekAbsolute(n.inMilliseconds / 1000.0);
+ final posS = position.inMilliseconds / 1000.0;
+ final targetS = posS - seconds;
+
+ // Find current chapter start
+ if (_chapters.isNotEmpty) {
+ double chapterStart = 0;
+ for (int i = _chapters.length - 1; i >= 0; i--) {
+ final s = (_chapters[i]['start'] as num?)?.toDouble() ?? 0;
+ if (s <= posS + 0.5) { chapterStart = s; break; }
+ }
+
+ final intoChapter = posS - chapterStart;
+ // If the rewind would cross the chapter boundary
+ if (targetS < chapterStart && intoChapter > 0.5) {
+ final now = DateTime.now();
+ final recentSnap = _lastRewindChapterSnap != null &&
+ now.difference(_lastRewindChapterSnap!).inMilliseconds < 2000;
+ if (!recentSnap) {
+ // Snap to chapter start instead of crossing
+ _lastRewindChapterSnap = now;
+ await _seekAbsolute(chapterStart);
+ _logEvent(PlaybackEventType.skipBackward, detail: 'snap to chapter start');
+ return;
+ }
+ // Double-tap within 2s - break through the barrier
+ _lastRewindChapterSnap = null;
+ }
+ }
+
+ var n = targetS < 0 ? 0.0 : targetS;
+ await _seekAbsolute(n);
_logEvent(PlaybackEventType.skipBackward, detail: '-${seconds}s');
- debugPrint('[Service] skipBackward done — playing=${_player!.playing}');
}
Future<void> skipToNextChapter() async {
diff --git a/lib/services/log_service.dart b/lib/services/log_service.dart
index 7e0a588e..0ee7ccb9 100644
--- a/lib/services/log_service.dart
+++ b/lib/services/log_service.dart
@@ -13,10 +13,9 @@ class LogService {
static const supportEmail = '[email protected]';
- // Keep 3MB max, trim to 2MB. At ~100 bytes/line this retains ~20k lines
- // which covers multiple sessions across several days of normal use.
- static const _maxSize = 3 * 1024 * 1024; // 3 MB
- static const _keepSize = 2 * 1024 * 1024; // 2 MB
+ // Keep 1MB max, trim to 512KB.
+ static const _maxSize = 1 * 1024 * 1024; // 1 MB
+ static const _keepSize = 512 * 1024; // 512 KB
static const _rotateCheckInterval = 500; // check every N writes
File? _logFile;
@@ -35,6 +34,14 @@ class LogService {
final dir = await getApplicationDocumentsDirectory();
_logFile = File('${dir.path}/absorb_logs.txt');
+ // Auto-clear if log is older than 24 hours
+ if (_logFile!.existsSync()) {
+ final lastModified = _logFile!.lastModifiedSync();
+ if (DateTime.now().difference(lastModified).inHours >= 24) {
+ _logFile!.writeAsStringSync('');
+ }
+ }
+
// Rotate on startup if needed
await _rotateIfNeeded();
diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dart
index 8897972c..3e4dd544 100644
--- a/lib/services/progress_sync_service.dart
+++ b/lib/services/progress_sync_service.dart
@@ -281,6 +281,87 @@ class ProgressSyncService {
}
}
+ // ── Offline listening time tracking ──
+
+ /// Add listening time for an item that was played offline.
+ Future<void> addOfflineListeningTime(String itemId, int seconds) async {
+ if (seconds <= 0) return;
+ final key = 'offline_listening_$itemId';
+ final existing = await ScopedPrefs.getInt(key) ?? 0;
+ await ScopedPrefs.setInt(key, existing + seconds);
+
+ // Track which items have pending offline time
+ final pending = await ScopedPrefs.getStringList('pending_offline_listening');
+ if (!pending.contains(itemId)) {
+ pending.add(itemId);
+ await ScopedPrefs.setStringList('pending_offline_listening', pending);
+ }
+ }
+
+ /// Flush accumulated offline listening time to the server by creating
+ /// a session, syncing the accumulated time, and closing it.
+ Future<void> flushOfflineListeningTime({required ApiService api}) async {
+ if (!_isOnline) return;
+
+ final pending = List<String>.from(
+ await ScopedPrefs.getStringList('pending_offline_listening'));
+ if (pending.isEmpty) return;
+ final flushed = <String>{};
+
+ debugPrint('[Sync] Flushing offline listening time for ${pending.length} item(s)');
+
+ for (final itemId in pending) {
+ final key = 'offline_listening_$itemId';
+ final seconds = await ScopedPrefs.getInt(key) ?? 0;
+ if (seconds <= 0) {
+ await ScopedPrefs.remove(key);
+ continue;
+ }
+
+ final data = await getLocal(itemId);
+ final currentTime = (data?['currentTime'] as num?)?.toDouble() ?? 0;
+ final duration = (data?['duration'] as num?)?.toDouble() ?? 0;
+
+ try {
+ final isCompound = itemId.length > 36;
+ final apiItemId = isCompound ? itemId.substring(0, 36) : itemId;
+ final episodeId = isCompound ? itemId.substring(37) : null;
+
+ final sessionData = episodeId != null
+ ? await api.startEpisodePlaybackSession(apiItemId, episodeId)
+ : await api.startPlaybackSession(apiItemId);
+
+ if (sessionData != null) {
+ final sid = sessionData['id'] as String?;
+ if (sid != null) {
+ await api.syncPlaybackSession(
+ sid,
+ currentTime: currentTime,
+ duration: duration,
+ timeListened: seconds,
+ );
+ await api.closePlaybackSession(sid);
+ debugPrint('[Sync] Flushed ${seconds}s offline listening for $itemId');
+ }
+ }
+ // Only remove after successful sync
+ await ScopedPrefs.remove(key);
+ flushed.add(itemId);
+ } catch (e) {
+ debugPrint('[Sync] Failed to flush offline listening for $itemId: $e');
+ if (e.toString().contains('SocketException')) break;
+ }
+ }
+
+ // Only remove successfully flushed items from pending list
+ if (flushed.isNotEmpty) {
+ final remaining = List<String>.from(
+ await ScopedPrefs.getStringList('pending_offline_listening'));
+ remaining.removeWhere((id) => flushed.contains(id));
+ await ScopedPrefs.setStringList('pending_offline_listening', remaining);
+ }
+ }
+
void dispose() {
_connectivitySub?.cancel();
}
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index c349e9a9..53c6ec6d 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -56,6 +56,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
bool _isLoading = true;
bool _isDownloadingAll = false;
bool _autoDownloadEnabled = false;
+ bool _subscribed = false;
bool _newestFirst = true;
bool _hideFinished = false;
String _podcastAdvanceDir = 'oldest_first'; // 'oldest_first' or 'newest_first'
@@ -107,6 +108,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
final lib = context.read<LibraryProvider>();
setState(() {
_autoDownloadEnabled = lib.isRollingDownloadEnabled(_itemId);
+ _subscribed = lib.isPodcastSubscribed(_itemId);
});
}
@@ -416,6 +418,37 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
await lib.toggleRollingDownload(_itemId);
setState(() => _autoDownloadEnabled = lib.isRollingDownloadEnabled(_itemId));
}),
+ if (_itemId.isNotEmpty)
+ _podMoreItem(cs,
+ _subscribed ? Icons.notifications_active_rounded : Icons.notifications_none_rounded,
+ _subscribed ? 'Unsubscribe from New Episodes' : 'Subscribe to New Episodes',
+ onTap: () async {
+ Navigator.pop(ctx);
+ if (_subscribed) {
+ final lib = context.read<LibraryProvider>();
+ await lib.unsubscribePodcast(_itemId);
+ if (mounted) setState(() => _subscribed = false);
+ } else {
+ final confirm = await showDialog<bool>(
+ context: context,
+ builder: (dCtx) => AlertDialog(
+ icon: const Icon(Icons.notifications_active_rounded),
+ title: const Text('Subscribe to this podcast?'),
+ content: const Text(
+ 'New episodes will be automatically downloaded and added to your absorbing queue when they appear on the server.'),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(dCtx, false), child: const Text('Cancel')),
+ FilledButton(onPressed: () => Navigator.pop(dCtx, true), child: const Text('Subscribe')),
+ ],
+ ),
+ );
+ if (confirm == true && mounted) {
+ final lib = context.read<LibraryProvider>();
+ await lib.subscribePodcast(_itemId);
+ setState(() => _subscribed = true);
+ }
+ }
+ }),
_podMoreItem(cs,
_hideFinished ? Icons.visibility_rounded : Icons.visibility_off_rounded,
_hideFinished ? 'Show Finished Episodes' : 'Hide Finished Episodes',
@@ -569,6 +602,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
if (!_isLoading) _chip(Icons.podcasts_rounded, '${_episodes.length} episode${_episodes.length == 1 ? '' : 's'}'),
if (_autoDownloadEnabled) _chip(Icons.downloading_rounded, 'Auto-Download'),
+ if (_subscribed) _chip(Icons.notifications_active_rounded, 'Subscribed', highlight: true),
..._genres.take(3).map((g) => _chip(Icons.tag_rounded, g)),
if (_language.isNotEmpty) _chip(Icons.language_rounded, _language.toUpperCase()),
if (_explicit) _chip(Icons.explicit_rounded, 'Explicit'),
@@ -761,17 +795,19 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
);
}
- Widget _chip(IconData icon, String text) {
+ Widget _chip(IconData icon, String text, {bool highlight = false}) {
final cs = Theme.of(context).colorScheme;
return Container(
constraints: const BoxConstraints(maxWidth: 200),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
- decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(20),
- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08))),
+ decoration: BoxDecoration(
+ color: highlight ? cs.primary.withValues(alpha: 0.15) : cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: highlight ? cs.primary.withValues(alpha: 0.3) : cs.onSurface.withValues(alpha: 0.08))),
child: Row(mainAxisSize: MainAxisSize.min, children: [
- Icon(icon, size: 12, color: cs.onSurfaceVariant), const SizedBox(width: 4),
+ Icon(icon, size: 12, color: highlight ? cs.primary : cs.onSurfaceVariant), const SizedBox(width: 4),
Flexible(child: Text(text, overflow: TextOverflow.ellipsis, maxLines: 1,
- style: TextStyle(color: cs.onSurfaceVariant, fontSize: 11)))]));
+ style: TextStyle(color: highlight ? cs.primary : cs.onSurfaceVariant, fontSize: 11)))]));
}
}
diff --git a/pubspec.yaml b/pubspec.yaml
index 68cc5bf0..7237624d 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.27+53
+version: 1.8.28+54
environment:
sdk: '>=3.1.0 <4.0.0'