A cross platform Audiobookshelf client for Android and iOS
Dart
Add a headphone button sleep timer snooze, fix the last-chapter pin when rereading, and pick up progress made on other devices while away
Barnabas94ba8783efae
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 69b012e8..42314fdf 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -773,6 +773,7 @@"shakeAddTime": "Add Time","shakeReset": "Reset","shakeAdds": "Shake adds",+ "sleepAddAmount": "Add time amount","shakeAddsValue": "{minutes} min","@shakeAddsValue": {"placeholders": {@@ -787,6 +788,8 @@"shakeSensitivityMedium": "Medium","shakeSensitivityHigh": "High","shakeSensitivityVeryHigh": "Very high",+ "buttonDuringSleepTimer": "Headphone button during wind-down",+ "buttonDuringSleepTimerHint": "In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.","resetTimerOnPause": "Reset timer on pause","resetTimerOnPauseOnSubtitle": "Timer restarts from full duration when you resume","resetTimerOnPauseOffSubtitle": "Timer continues from where it left off",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 5e01d084..d65b9b46 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -3082,6 +3082,12 @@ abstract class AppLocalizations {/// **'Shake adds'**String get shakeAdds;+ /// No description provided for @sleepAddAmount.+ ///+ /// In en, this message translates to:+ /// **'Add time amount'**+ String get sleepAddAmount;+/// No description provided for @shakeAddsValue.////// In en, this message translates to:@@ -3124,6 +3130,18 @@ abstract class AppLocalizations {/// **'Very high'**String get shakeSensitivityVeryHigh;+ /// No description provided for @buttonDuringSleepTimer.+ ///+ /// In en, this message translates to:+ /// **'Headphone button during wind-down'**+ String get buttonDuringSleepTimer;++ /// No description provided for @buttonDuringSleepTimerHint.+ ///+ /// In en, this message translates to:+ /// **'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.'**+ String get buttonDuringSleepTimerHint;+/// No description provided for @resetTimerOnPause.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex b350ba47..a8c86dd6 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -1660,6 +1660,9 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get shakeAdds => 'Schütteln fügt hinzu';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes Min.';@@ -1683,6 +1686,13 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Sehr hoch';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Timer bei Pause zurücksetzen';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 629669d5..b742aa02 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -1643,6 +1643,9 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1666,6 +1669,13 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex e3d64ee9..cf7333f6 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -1643,6 +1643,9 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1666,6 +1669,13 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex 8c9af321..c6d4cad0 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -1645,6 +1645,9 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1668,6 +1671,13 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 6bc6f4dc..25c7b713 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -1668,6 +1668,9 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get shakeAdds => 'Secouer ajoute';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1691,6 +1694,13 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Très haute';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Réinitialiser le minuteur en cas de pause';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 84da28a7..7645ecf1 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -1643,6 +1643,9 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1666,6 +1669,13 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex e631ded6..e33dee54 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -1643,6 +1643,9 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1666,6 +1669,13 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex f055c539..aff16b3d 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -1643,6 +1643,9 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1666,6 +1669,13 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 51b4ff4c..185d17ce 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -1643,6 +1643,9 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1666,6 +1669,13 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 61b8145b..fcf4e140 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -1643,6 +1643,9 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1666,6 +1669,13 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex c8537451..cff5117c 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -1647,6 +1647,9 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get shakeAdds => 'Shake adds';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes min';@@ -1670,6 +1673,13 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => 'Very high';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => 'Reset timer on pause';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 9c0b1475..132f2636 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -1614,6 +1614,9 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get shakeAdds => '摇一摇添加';+ @override+ String get sleepAddAmount => 'Add time amount';+@overrideString shakeAddsValue(int minutes) {return '$minutes 分钟';@@ -1637,6 +1640,13 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get shakeSensitivityVeryHigh => '非常高';+ @override+ String get buttonDuringSleepTimer => 'Headphone button during wind-down';++ @override+ String get buttonDuringSleepTimerHint =>+ 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';+@overrideString get resetTimerOnPause => '暂停时重置定时器';diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dartindex 7c73a049..8f4a3bc5 100644--- a/lib/providers/_lp_absorbing.dart+++ b/lib/providers/_lp_absorbing.dart@@ -542,7 +542,11 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {// Stats widget shows "books finished this year"; force a refresh so it// reflects the new count without waiting on the 15-min throttle.HomeWidgetService().refreshStats(force: true);- if (_absorbingBookIds.remove(itemId)) {+ if (fromRemote) {+ // Finished on another device: leave Absorbing right away, same as when+ // the book isn't loaded - don't linger until the next play press+ _absorbingBookIds.remove(itemId);+ } else if (_absorbingBookIds.remove(itemId)) {_absorbingBookIds.insert(0, itemId);}if (itemId.length > 36) {diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 9065681b..e931ca44 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -1407,6 +1407,47 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {// ── Socket event handlers ──+ DateTime? _lastProgressCatchUp;++ /// The socket only delivers progress events while connected - anything+ /// that happens during a backgrounded gap is lost for good, which left+ /// finished-elsewhere books sitting in Absorbing until a tap un-finished+ /// them. On every socket auth, pull the server's progress list and replay+ /// entries newer than what we hold through the same handler the live+ /// event uses, so pruning and shelf refreshes behave identically.+ Future<void> _catchUpRemoteProgress() async {+ final api = _api;+ if (api == null) return;+ final now = DateTime.now();+ if (_lastProgressCatchUp != null &&+ now.difference(_lastProgressCatchUp!) < const Duration(seconds: 45)) {+ return;+ }+ _lastProgressCatchUp = now;+ try {+ final list = await api.getAllProgress();+ if (list == null) return;+ var applied = 0;+ for (final mp in list) {+ final itemId = mp['libraryItemId'] as String?;+ if (itemId == null) continue;+ final episodeId = mp['episodeId'] as String?;+ final key = episodeId != null ? '$itemId-$episodeId' : itemId;+ final serverUpd = (mp['lastUpdate'] as num?)?.toInt() ?? 0;+ final localUpd =+ ((_progressMap[key]?['lastUpdate']) as num?)?.toInt() ?? 0;+ if (serverUpd <= localUpd) continue;+ _onRemoteProgressUpdated(mp);+ applied++;+ }+ if (applied > 0) {+ debugPrint('[Sync] Progress catch-up applied $applied newer entries');+ }+ } catch (e) {+ debugPrint('[Sync] Progress catch-up failed: $e');+ }+ }+void _onRemoteProgressUpdated(Map<String, dynamic> mp) {final itemId = mp['libraryItemId'] as String?;final episodeId = mp['episodeId'] as String?;@@ -1419,12 +1460,40 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {: player.currentItemId;if (key == playingKey && player.hasBook) {if (mp['isFinished'] == true && !_resetItems.contains(key)) {- (this as _AbsorbingMixin)- .markFinishedLocally(key, skipAutoAdvance: true, fromRemote: true);+ // Re-reading a finished book: the server keeps isFinished=true and+ // echoes it back after every sync. Pinning the override to 100%+ // while this device is actively mid-listen drags every inactive+ // view to the end of the book (GH #345) - only honor the echo when+ // we aren't the ones listening far from the end.+ final posS = player.position.inMilliseconds / 1000.0;+ final durS = player.totalDuration;+ final nearEnd = durS <= 0 || posS >= durS - 60;+ if (!player.isPlaying || nearEnd) {+ (this as _AbsorbingMixin)+ .markFinishedLocally(key, skipAutoAdvance: true, fromRemote: true);+ }} else if (mp['isFinished'] != true) {+ final prevUpd = ((_progressMap[key]?['lastUpdate']) as num?)?.toInt() ?? 0;+ final newUpd = (mp['lastUpdate'] as num?)?.toInt() ?? 0;_progressMap[key] = mp;_localProgressOverrides.remove(key);_resetItems.remove(key);+ // Cross-device continuity: a newer position from another device+ // moves the paused player too, so the card shows it and resume+ // carries on from there instead of the stale pause point.+ final serverTime = (mp['currentTime'] as num?)?.toDouble();+ if (serverTime != null &&+ newUpd > prevUpd &&+ !player.isPlaying &&+ !ChromecastService().isCasting) {+ final posS = player.position.inMilliseconds / 1000.0;+ if ((serverTime - posS).abs() > 5.0) {+ debugPrint('[Sync] Adopting newer remote position for paused player: '+ '${posS.toStringAsFixed(1)}s -> ${serverTime.toStringAsFixed(1)}s');+ unawaited(player.seekTo(+ Duration(milliseconds: (serverTime * 1000).round())));+ }+ }notifyListeners();}return;diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex b37a906f..e2e5e31b 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -222,6 +222,7 @@ class LibraryProvider extends ChangeNotifierif (auth.serverUrl != null && auth.token != null) {final socket = SocketService();socket.onProgressUpdated = _onRemoteProgressUpdated;+ socket.onAuthenticated = _catchUpRemoteProgress;socket.onItemUpdated = _onRemoteItemUpdated;socket.onItemRemoved = _onRemoteItemRemoved;socket.onSeriesUpdated = _onRemoteSeriesUpdated;diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dartindex 594b69ce..0e03c793 100644--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@ -971,6 +971,16 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {final Color cardBgBottom = bgHsl != null? bgHsl.withLightness(isDark ? 0.11 : 0.88).toColor(): cardBgTop;+ // The percent and progress bar sit on the tinted card bottom; a dark+ // cover accent on its own dark tint is invisible (and the reverse in+ // light mode). Keep the hue but force lightness contrast with the card.+ final Color rowAccent = bgHsl != null+ ? HSLColor.fromColor(accent)+ .withLightness(isDark ? 0.72 : 0.30)+ .withSaturation(+ HSLColor.fromColor(accent).saturation.clamp(0.35, 1.0))+ .toColor()+ : accent;final progressValue =(totalDuration > 0 ? currentTime / totalDuration : progress).clamp(0.0, 1.0);final remaining = totalDuration > 0 ? totalDuration - currentTime : 0.0;@@ -1124,8 +1134,8 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {child: LinearProgressIndicator(value: progressValue,minHeight: 3,- backgroundColor: cs.outlineVariant.withValues(alpha: 0.3),- valueColor: AlwaysStoppedAnimation(accent),+ backgroundColor: rowAccent.withValues(alpha: 0.22),+ valueColor: AlwaysStoppedAnimation(rowAccent),),),const SizedBox(height: 4),@@ -1133,7 +1143,7 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {Text('${(progressValue * 100).round()}%',style: tt.labelSmall?.copyWith(fontWeight: FontWeight.w700,- color: accent,+ color: rowAccent,fontSize: 11)),if (remaining > 0) ...[const SizedBox(width: 6),diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex de4871e6..cf648c1a 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -97,6 +97,7 @@ class _SettingsScreenState extends State<SettingsScreen> {double _sleepChimeVolume = 0.7;int _shakeAddMinutes = 5;String _shakeSensitivity = 'medium';+ String _sleepButtonMode = 'off';String _bookQueueMode = 'off';String _podcastQueueMode = 'off';String? _queuePlaylistId;@@ -830,6 +831,7 @@ class _SettingsScreenState extends State<SettingsScreen> {final manualSeed = await PlayerSettings.getManualSeedColor();final gradientIntensity = await PlayerSettings.getGradientIntensity();final useColorEverywhere = await PlayerSettings.getUseColorEverywhere();+ final sleepButtonMode = await PlayerSettings.getSleepButtonMode();final statsGoalMinutes = <String, int>{for (final p in PlayerSettings.statsGoalPeriods)p: await PlayerSettings.getStatsGoalMinutesFor(p)@@ -978,6 +980,7 @@ class _SettingsScreenState extends State<SettingsScreen> {_sleepChime = chime;_sleepChimeVolume = chimeVol;_shakeSensitivity = shakeSens;+ _sleepButtonMode = sleepButtonMode;_language = language;_canPickDownloadLocation = true;_statsGoalMinutes@@ -2740,14 +2743,46 @@ class _SettingsScreenState extends State<SettingsScreen> {),const SizedBox(height: 4),],- if (_shakeMode == 'addTime') ...[+ const Divider(height: 1, indent: 16, endIndent: 16),+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),+ child: Text(l.buttonDuringSleepTimer, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),+ child: SizedBox(+ width: double.infinity,+ child: SegmentedButton<String>(+ showSelectedIcon: false,+ segments: [+ ButtonSegment(value: 'off', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeOff))),+ ButtonSegment(value: 'addTime', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeAddTime))),+ ButtonSegment(value: 'resetTimer', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeReset))),+ ],+ selected: {_sleepButtonMode},+ onSelectionChanged: _loaded ? (v) {+ setState(() => _sleepButtonMode = v.first);+ PlayerSettings.setSleepButtonMode(v.first);+ } : null,+ ),+ ),+ ),+ if (_sleepButtonMode != 'off')+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),+ child: Text(l.buttonDuringSleepTimerHint,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.7), fontSize: 11)),+ ),+ // Shared by shake and button add-time modes, so it shows+ // whenever either trigger needs it+ if (_shakeMode == 'addTime' || _sleepButtonMode == 'addTime') ...[const Divider(height: 1, indent: 16, endIndent: 16),Padding(padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [- Text(l.shakeAdds, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),+ Text(l.sleepAddAmount, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),Text(l.shakeAddsValue(_shakeAddMinutes),style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),],diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 1d058c90..26a7166c 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -786,6 +786,15 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {);switch (count) {case 1:+ // Sleep-timer snooze (GH #333): during the wind-down window a+ // single press resets the timer instead of pausing. Sits after all+ // the phantom guards so a spurious AA/BT click can't reset it, and+ // inside the resolver so double/triple presses still skip.+ if (await SleepTimerService().snoozeFromMediaButton()) {+ _lastClickKeyCode = null;+ debugPrint('[Handler] → single press consumed by sleep timer snooze');+ break;+ }_inClickResolver = true;try {// Honor the actual keycode the system dispatched when we can.@@ -4462,14 +4471,22 @@ class AudioPlayerService extends ChangeNotifier {return ch['title'] as String?;}}- // Past all chapters — use the last one- if (_chapters.isNotEmpty) {- final last = _chapters.last as Map<String, dynamic>;- _currentChapterStart = (last['start'] as num?)?.toDouble() ?? 0;- _currentChapterEnd = (last['end'] as num?)?.toDouble() ?? _totalDuration;- _lastNotifiedChapterIndex = _chapters.length - 1;- return last['title'] as String?;- }+ // Slightly past the last chapter still counts as the last chapter.+ // Grossly past it means the chapters don't cover the timeline (e.g.+ // duplicate audio files doubling the duration, GH #345) - report no+ // chapter rather than pinning the last one.+ final graceIdx =+ ChapterLookup.indexAtWithGrace(_chapters, posSeconds, _totalDuration);+ if (graceIdx != null) {+ final ch = _chapters[graceIdx] as Map<String, dynamic>;+ _currentChapterStart = (ch['start'] as num?)?.toDouble() ?? 0;+ _currentChapterEnd = (ch['end'] as num?)?.toDouble() ?? _totalDuration;+ _lastNotifiedChapterIndex = graceIdx;+ return ch['title'] as String?;+ }+ _currentChapterStart = 0;+ _currentChapterEnd = _totalDuration;+ _lastNotifiedChapterIndex = -1;return null;}@@ -5074,6 +5091,36 @@ class AudioPlayerService extends ChangeNotifier {}}+ // Within the grace window past the last chapter, keep the last one+ if (chapterIdx < 0) {+ final g = ChapterLookup.indexAtWithGrace(_chapters, posSec, _totalDuration);+ if (g != null) {+ final ch = _chapters[g] as Map<String, dynamic>;+ chapterIdx = g;+ chapterTitle = ch['title'] as String?;+ chapterStart = (ch['start'] as num?)?.toDouble() ?? 0;+ chapterEnd = (ch['end'] as num?)?.toDouble() ?? _totalDuration;+ }+ }++ if (chapterIdx < 0 && _lastNotifiedChapterIndex >= 0) {+ // Position left the chapter span entirely - clear the stale+ // chapter so the notification stops claiming the last one+ debugPrint(+ '[Battery] Chapter cleared: ${posSec.toStringAsFixed(1)}s is outside the chapter span',+ );+ _lastNotifiedChapterIndex = -1;+ _currentChapterStart = 0;+ _currentChapterEnd = _totalDuration;+ _pushMediaItem(+ _currentItemId!,+ _currentTitle ?? '',+ _currentAuthor ?? '',+ _currentCoverUrl,+ _totalDuration,+ );+ }+if (chapterIdx >= 0 && chapterIdx != _lastNotifiedChapterIndex) {debugPrint('[Battery] Chapter change: idx=$chapterIdx "$chapterTitle" at ${posSec.toStringAsFixed(1)}s',diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dartindex b1e3116c..65737fb0 100644--- a/lib/services/backup_service.dart+++ b/lib/services/backup_service.dart@@ -33,6 +33,7 @@ class BackupService {'longForwardSkip': await PlayerSettings.getLongForwardSkip(),'longBackSkip': await PlayerSettings.getLongBackSkip(),'shakeMode': await PlayerSettings.getShakeMode(),+ 'sleepButtonMode': await PlayerSettings.getSleepButtonMode(),'shakeAddMinutes': await PlayerSettings.getShakeAddMinutes(),'shakeSensitivity': await PlayerSettings.getShakeSensitivity(),'resetSleepOnPause': await PlayerSettings.getResetSleepOnPause(),@@ -463,6 +464,7 @@ class BackupService {if (s['forwardSkip'] != null) PlayerSettings.setForwardSkip(s['forwardSkip'] as int);if (s['backSkip'] != null) PlayerSettings.setBackSkip(s['backSkip'] as int);if (s['shakeMode'] != null) PlayerSettings.setShakeMode(s['shakeMode'] as String);+ if (s['sleepButtonMode'] != null) PlayerSettings.setSleepButtonMode(s['sleepButtonMode'] as String);// Migrate old bool settingif (s['shakeMode'] == null && s['shakeToResetSleep'] != null) {PlayerSettings.setShakeMode(s['shakeToResetSleep'] as bool ? 'addTime' : 'off');diff --git a/lib/services/chapter_lookup.dart b/lib/services/chapter_lookup.dartindex 794a74eb..cc51450f 100644--- a/lib/services/chapter_lookup.dart+++ b/lib/services/chapter_lookup.dart@@ -33,6 +33,31 @@ class ChapterLookup {return null;}+ /// How far past the last chapter's end a position may sit while still+ /// counting as the last chapter (covers rounding and trailing gaps).+ /// Positions grossly past that mean the chapters don't cover the item's+ /// timeline - e.g. duplicate audio files doubling the duration (GH #345) -+ /// and resolve to no chapter instead of pinning the last one.+ static const graceSeconds = 120.0;++ /// Like [indexAt], but keeps the last chapter for positions within+ /// [graceSeconds] past its end.+ static int? indexAtWithGrace(+ List<dynamic> chapters,+ double positionSeconds,+ double totalDuration,+ ) {+ final idx = indexAt(chapters, positionSeconds, totalDuration);+ if (idx != null) return idx;+ if (chapters.isEmpty) return null;+ final last = chapters.last as Map<String, dynamic>;+ final end = (last['end'] as num?)?.toDouble() ?? totalDuration;+ if (positionSeconds >= end && positionSeconds <= end + graceSeconds) {+ return chapters.length - 1;+ }+ return null;+ }+static ({double seconds, bool finishesItem})? nextSkipTarget(List<dynamic> chapters,double positionSeconds,diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 5615f694..e0c5fffb 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -742,6 +742,12 @@ class PlayerSettings {static Future<int> getSleepTimerChapters() => _get('sleepTimerChapters', 1);static Future<void> setSleepTimerChapters(int chapters) => _set('sleepTimerChapters', chapters);+ /// Media-button snooze during the sleep timer wind-down (GH #333):+ /// 'off' | 'addTime' | 'resetTimer'. A press inside the wind-down window+ /// resets or extends the timer instead of pausing.+ static Future<String> getSleepButtonMode() => _get('sleepButtonMode', 'off');+ static Future<void> setSleepButtonMode(String v) => _set('sleepButtonMode', v);+static Future<bool> getResetSleepOnPause() => _get('resetSleepOnPause', false);static Future<void> setResetSleepOnPause(bool value) => _set('resetSleepOnPause', value);diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dartindex 7e655beb..3695dd24 100644--- a/lib/services/sleep_timer_service.dart+++ b/lib/services/sleep_timer_service.dart@@ -239,15 +239,9 @@ class SleepTimerService extends ChangeNotifier {if (!_wasPlaying) {final resetOnPause = await PlayerSettings.getResetSleepOnPause();if (resetOnPause) {- _timeRemaining = _initialDuration;- _warningSent = false;- if (_isFadingOut) {- _isFadingOut = false;- _player.setVolume(_fadeStartVolume);- }+ _resetToFull();debugPrint('[SleepTimer] Reset to ${_initialDuration.inMinutes}m on resume');onToast?.call('Sleep timer reset: ${_initialDuration.inMinutes}m');- _scheduleNextTick();}}_wasPlaying = true;@@ -495,6 +489,42 @@ class SleepTimerService extends ChangeNotifier {bool _isFadingOut = false;bool get isFadingOut => _isFadingOut;+ /// True during the wind-down window of a time-based timer (chime played,+ /// fade underway or imminent).+ bool get isInWarningWindow => _mode == SleepTimerMode.time && _warningSent;++ /// Reset the countdown to its full duration, undoing any wind-down fade.+ /// Shared by shake reset, reset-on-resume and the media-button snooze.+ void _resetToFull() {+ _timeRemaining = _initialDuration;+ _warningSent = false;+ if (_isFadingOut) {+ _isFadingOut = false;+ _player.setVolume(_fadeStartVolume);+ }+ if (_timer?.isActive == true) _scheduleNextTick();+ notifyListeners();+ }++ /// Media-button snooze (GH #333): during the wind-down window a single+ /// headphone press resets or extends the timer instead of pausing.+ /// Returns true when the press was consumed.+ Future<bool> snoozeFromMediaButton() async {+ if (!isInWarningWindow || !_isPlaybackActive) return false;+ final mode = await PlayerSettings.getSleepButtonMode();+ if (mode == 'off') return false;+ _vibrateSnooze();+ if (mode == 'addTime') {+ final addMins = await PlayerSettings.getShakeAddMinutes();+ addTime(Duration(minutes: addMins));+ debugPrint('[SleepTimer] Media button snooze: +${addMins}m');+ } else {+ _resetToFull();+ debugPrint('[SleepTimer] Media button snooze: reset to ${_initialDuration.inMinutes}m');+ }+ return true;+ }+Future<void> _triggerSleep() async {if (_isTriggeringSleep) return;final pauseRequested = !_cast.isCastEngaged && _player.isPauseRequested;@@ -806,9 +836,7 @@ class SleepTimerService extends ChangeNotifier {if (_shakeMode == 'resetTimer') {if (_mode == SleepTimerMode.time) {- _timeRemaining = _initialDuration;- _warningSent = false;- notifyListeners();+ _resetToFull();onToast?.call('Timer reset to ${_initialDuration.inMinutes}m');} else if (_mode == SleepTimerMode.chapters) {// For chapter mode, re-count from current positiondiff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dartindex b74da0f1..4f780288 100644--- a/lib/services/socket_service.dart+++ b/lib/services/socket_service.dart@@ -66,6 +66,10 @@ class SocketService {/// Called when the server pushes a progress update (cross-device sync).void Function(Map<String, dynamic> progress)? onProgressUpdated;+ /// Called after each successful socket auth (initial connect and every+ /// reconnect) so listeners can catch up on events missed while offline.+ void Function()? onAuthenticated;+/// Called when a library item is added, updated, or removed.void Function(Map<String, dynamic> data)? onItemUpdated;@@ -342,6 +346,7 @@ class SocketService {_socket!.on('init', (_) {debugPrint('[Socket] Authenticated - user is online');_syncServerLogSubscription();+ onAuthenticated?.call();});_socket!.on('auth_failed', (_) {@@ -494,6 +499,7 @@ class SocketService {_token = null;_serverUrl = null;onProgressUpdated = null;+ onAuthenticated = null;onItemUpdated = null;onItemRemoved = null;onSeriesUpdated = null;@@ -547,6 +553,7 @@ class SocketService {_socket!.on('init', (_) {debugPrint('[Socket] Authenticated - user is online');_syncServerLogSubscription();+ onAuthenticated?.call();});_socket!.on('auth_failed', (_) {diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dartindex 1555ee70..8e01db94 100644--- a/lib/widgets/card_progress_bar.dart+++ b/lib/widgets/card_progress_bar.dart@@ -3,6 +3,7 @@ import 'dart:math';import 'package:flutter/material.dart';import '../l10n/app_localizations.dart';import '../services/audio_player_service.dart';+import '../services/chapter_lookup.dart';import '../services/chromecast_service.dart';import 'absorb_slider.dart';@@ -304,15 +305,23 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsBbreak;}}- // Past last chapter end - use last chapter+ // Slightly past the last chapter end still counts as the last+ // chapter. Grossly past means the chapters don't cover the item's+ // timeline (e.g. duplicate audio files, GH #345) - keep the+ // whole-book span so the pill stays honest and keeps moving.if (resolvedChapterIdx < 0 && posS > 0) {final last = chapterSource.last as Map<String, dynamic>;- chapterStart = (last['start'] as num?)?.toDouble() ?? 0;- chapterEnd = (last['end'] as num?)?.toDouble() ?? totalDur;- resolvedChapterName = last['title'] as String?;- resolvedChapterIdx = chapterSource.length - 1;+ final lastEnd = (last['end'] as num?)?.toDouble() ?? totalDur;+ if (posS <= lastEnd + ChapterLookup.graceSeconds) {+ chapterStart = (last['start'] as num?)?.toDouble() ?? 0;+ chapterEnd = lastEnd;+ resolvedChapterName = last['title'] as String?;+ resolvedChapterIdx = chapterSource.length - 1;+ }}}+ final chapterUnresolved =+ chapterSource.isNotEmpty && resolvedChapterIdx < 0 && posS > 0;final chapterDur = chapterEnd - chapterStart;final chapterPos = (posS - chapterStart).clamp(0.0, chapterDur);final chapterProgress = chapterDur > 0 ? chapterPos / chapterDur : 0.0;@@ -374,7 +383,8 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsB// Prefer the chapter name resolved from posS (consistent with// the fill position) over the externally-passed name which// may come from player.currentChapter (different position source).- final rawName = resolvedChapterName ?? widget.chapterName;+ final rawName = resolvedChapterName ??+ (chapterUnresolved ? null : widget.chapterName);final chIdx = resolvedChapterIdx >= 0 ? resolvedChapterIdx : widget.chapterIndex;final chName = rawName != null? _smartChapterName(l, rawName, chIdx, widget.totalChapters)