Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add new episode notifications on iPhone, show a read along badge on covers, label BookOrbit collection and Smart Scope rows on Home and let the What's new popup be turned off

Barnabas106e46ff2411
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index c7c3be4b..8f6f85f0 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -4,11 +4,17 @@ import Flutter
import UIKit
import AVFoundation
import AVKit
+import BackgroundTasks
import CoreMedia
import Intents
import MediaPlayer
import just_audio
import os
+import SwiftUI
+#if canImport(Translation)
+import Translation
+#endif
+import UserNotifications
let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlessExecution: true)
@@ -16,6 +22,11 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
@objc class AppDelegate: FlutterAppDelegate {
private var widgetChannel: FlutterMethodChannel?
private var volumeKeysChannel: FlutterMethodChannel?
+ private var backgroundChannel: FlutterMethodChannel?
+ // New podcast episodes and release-day books, checked when iOS gives the
+ // app background refresh time. Listed in Info.plist.
+ private let episodeCheckTaskId = "com.barnabas.absorb.episodeNotifCheck"
+ private let episodeCheckMinutesKey = "absorb_episode_check_minutes"
private let volumeKeyWatcher = VolumeKeyWatcher()
// Native log lines emitted before Dart's channel handler registers, kept
@@ -134,6 +145,13 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
registerAudioSessionObservers()
+ // Notifications the app shows (new episodes, release days) reach the
+ // plugin through FlutterAppDelegate, for taps and showing them in-app.
+ UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
+
+ // Must be registered before launch finishes, or iOS drops the task.
+ registerEpisodeCheckTask()
+
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
@@ -244,6 +262,63 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
}
}
+ private func registerEpisodeCheckTask() {
+ BGTaskScheduler.shared.register(forTaskWithIdentifier: episodeCheckTaskId, using: nil) { [weak self] task in
+ guard let self, let refresh = task as? BGAppRefreshTask else {
+ task.setTaskCompleted(success: false)
+ return
+ }
+ self.runEpisodeCheck(refresh)
+ }
+ }
+
+ /// Asks iOS for the next background refresh, no sooner than the chosen
+ /// interval. iOS decides when it actually comes. A request already waiting
+ /// is kept unless [replacing]: the app asks on every launch, and starting
+ /// the wait over each time could push the refresh off for good.
+ private func scheduleEpisodeCheck(replacing: Bool) {
+ let minutes = UserDefaults.standard.integer(forKey: episodeCheckMinutesKey)
+ guard minutes > 0 else {
+ BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: episodeCheckTaskId)
+ return
+ }
+ BGTaskScheduler.shared.getPendingTaskRequests { [weak self] pending in
+ guard let self else { return }
+ if !replacing && pending.contains(where: { $0.identifier == self.episodeCheckTaskId }) { return }
+ let request = BGAppRefreshTaskRequest(identifier: self.episodeCheckTaskId)
+ request.earliestBeginDate = Date(timeIntervalSinceNow: TimeInterval(max(minutes, 15) * 60))
+ do {
+ try BGTaskScheduler.shared.submit(request)
+ } catch {
+ self.logToFlutter("[EpisodeNotif] background refresh not scheduled: \(error.localizedDescription)")
+ }
+ }
+ }
+
+ /// The check runs in the app's own Dart code. On a cold background launch
+ /// the message waits in the channel until Dart is listening.
+ private func runEpisodeCheck(_ task: BGAppRefreshTask) {
+ scheduleEpisodeCheck(replacing: true)
+ var done = false
+ let finish: (Bool) -> Void = { ok in
+ DispatchQueue.main.async {
+ guard !done else { return }
+ done = true
+ task.setTaskCompleted(success: ok)
+ }
+ }
+ task.expirationHandler = { finish(false) }
+ DispatchQueue.main.async { [weak self] in
+ guard let channel = self?.backgroundChannel else {
+ finish(false)
+ return
+ }
+ channel.invokeMethod("runEpisodeCheck", arguments: nil) { reply in
+ finish(!(reply is FlutterError))
+ }
+ }
+ }
+
/// Forwards a log line to the Dart LogService via the widget channel so it
/// appears in the in-app log viewer (NSLog alone only shows in Xcode /
/// Console.app on a Mac). Lines emitted before Dart signals "logReady" are
@@ -371,6 +446,21 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
// decorate CPNowPlayingTemplate only — the lock screen is untouched.
CarPlayNowPlaying.shared.register(with: messenger)
+ let background = FlutterMethodChannel(name: "com.barnabas.absorb/background",
+ binaryMessenger: messenger)
+ background.setMethodCallHandler { [weak self] call, result in
+ guard let self, call.method == "scheduleEpisodeCheck" else {
+ result(FlutterMethodNotImplemented)
+ return
+ }
+ let minutes = (call.arguments as? [String: Any])?["minutes"] as? Int ?? 0
+ let changed = UserDefaults.standard.integer(forKey: self.episodeCheckMinutesKey) != minutes
+ UserDefaults.standard.set(minutes, forKey: self.episodeCheckMinutesKey)
+ self.scheduleEpisodeCheck(replacing: changed)
+ result(nil)
+ }
+ backgroundChannel = background
+
// iOS audio output device switching is not implemented yet — iOS routes
// through the system's MPVolumeView/AVRoutePicker rather than letting apps
// pick output devices directly. Stub those, but do expose the AirPlay
@@ -470,6 +560,28 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
}
}
+ // The phone's time zone, and how far another one (the zone BookOrbit
+ // counts days in) is from UTC right now, so the Stats screen can say when
+ // the two split days differently.
+ let timeZoneChannel = FlutterMethodChannel(name: "com.absorb.time_zone",
+ binaryMessenger: messenger)
+ timeZoneChannel.setMethodCallHandler { (call, result) in
+ guard call.method == "compare" else {
+ result(FlutterMethodNotImplemented)
+ return
+ }
+ let here = TimeZone.current
+ var answer: [String: Any] = [
+ "id": here.identifier,
+ "offsetSeconds": here.secondsFromGMT(),
+ ]
+ if let otherId = (call.arguments as? [String: Any])?["other"] as? String,
+ let other = TimeZone(identifier: otherId) {
+ answer["otherOffsetSeconds"] = other.secondsFromGMT()
+ }
+ result(answer)
+ }
+
// Bookmark clip export: extract a time window of a book and write a .m4a.
let clipChannel = FlutterMethodChannel(name: "com.absorb.clip",
binaryMessenger: messenger)
@@ -721,6 +833,39 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
}
}
+ case "translateText":
+ // Reader Translate: Apple's translation sheet, the same one the system
+ // text menu offers. Before iOS 17.4 Dart falls back to the web.
+ let text = args?["text"] as? String ?? ""
+ #if canImport(Translation)
+ if #available(iOS 17.4, *), !text.isEmpty {
+ DispatchQueue.main.async {
+ let scene = UIApplication.shared.connectedScenes
+ .compactMap { $0 as? UIWindowScene }
+ .first { $0.activationState == .foregroundActive }
+ let window = scene?.windows.first { $0.isKeyWindow } ?? scene?.windows.first
+ guard var presenter = window?.rootViewController else {
+ result(false)
+ return
+ }
+ while let presented = presenter.presentedViewController {
+ presenter = presented
+ }
+ weak var hostRef: UIViewController?
+ let host = UIHostingController(rootView: TranslateSheetHost(text: text) {
+ hostRef?.dismiss(animated: false)
+ })
+ hostRef = host
+ host.view.backgroundColor = .clear
+ host.modalPresentationStyle = .overFullScreen
+ presenter.present(host, animated: false)
+ result(true)
+ }
+ return
+ }
+ #endif
+ result(false)
+
case "init":
result([
"bands": 5,
@@ -1042,3 +1187,29 @@ enum AudioWindowExtractor {
}
}
}
+
+#if canImport(Translation)
+/// Invisible full-screen host for Apple's translation sheet; tells the caller
+/// to take it down once the sheet closes.
+@available(iOS 17.4, *)
+struct TranslateSheetHost: View {
+ let text: String
+ let onDone: () -> Void
+ @State private var shown = false
+
+ init(text: String, onDone: @escaping () -> Void) {
+ self.text = text
+ self.onDone = onDone
+ }
+
+ var body: some View {
+ Color.clear
+ .ignoresSafeArea()
+ .translationPresentation(isPresented: $shown, text: text, attachmentAnchor: .point(.center))
+ .onAppear { DispatchQueue.main.async { shown = true } }
+ .onChange(of: shown) { _, isShown in
+ if !isShown { onDone() }
+ }
+ }
+}
+#endif
diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist
index ff1078bc..457cd1a4 100644
--- a/ios/Runner/Info.plist
+++ b/ios/Runner/Info.plist
@@ -84,6 +84,10 @@
<string>audio</string>
<string>fetch</string>
</array>
+ <key>BGTaskSchedulerPermittedIdentifiers</key>
+ <array>
+ <string>com.barnabas.absorb.episodeNotifCheck</string>
+ </array>
<key>NSSiriUsageDescription</key>
<string>Siri can play, pause and find your audiobooks and podcasts in Absorb.</string>
<key>INIntentsSupported</key>
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index d16bf6d4..434ffa5e 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -754,15 +754,63 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
/// True if [itemId] currently appears in the personalized "Continue Listening"
/// shelf. Gates the "Remove from Continue Listening" book action.
- bool isInContinueListeningShelf(String itemId) {
- for (final section in _personalizedSections) {
- if (section is! Map<String, dynamic>) continue;
- if (section['id'] != 'continue-listening') continue;
- for (final e in (section['entities'] as List<dynamic>? ?? const [])) {
- if (e is Map<String, dynamic> && e['id'] == itemId) return true;
+ bool isInContinueListeningShelf(String itemId) => continueShelfOf(itemId) == 'continue-listening';
+
+ /// Which Continue shelf shows [itemId], 'continue-listening' or
+ /// 'continue-reading', or null. Gates the remove-from-Continue action.
+ String? continueShelfOf(String itemId) {
+ for (final id in const ['continue-listening', 'continue-reading']) {
+ for (final section in _personalizedSections) {
+ if (section is! Map<String, dynamic> || section['id'] != id) continue;
+ for (final e in (section['entities'] as List<dynamic>? ?? const [])) {
+ if (e is Map<String, dynamic> && e['id'] == itemId) return id;
+ }
}
}
- return false;
+ return null;
+ }
+
+ /// Takes a book or a series off the Continue shelves straight away. A
+ /// refresh already on its way could otherwise put it back from before the
+ /// server heard.
+ void hideFromContinueShelves({String? itemId, String? seriesId}) {
+ final now = DateTime.now();
+ if (itemId != null) _hiddenShelfItems[itemId] = now;
+ if (seriesId != null) _hiddenShelfSeries[seriesId] = now;
+ _personalizedSections = _withoutJustHidden(_personalizedSections);
+ notifyListeners();
+ }
+
+ List<dynamic> _withoutJustHidden(List<dynamic> sections) {
+ final now = DateTime.now();
+ bool stale(String _, DateTime at) => now.difference(at) > const Duration(minutes: 2);
+ _hiddenShelfItems.removeWhere(stale);
+ _hiddenShelfSeries.removeWhere(stale);
+ if (_hiddenShelfItems.isEmpty && _hiddenShelfSeries.isEmpty) return sections;
+ bool hidden(String shelf, Object? e) {
+ if (e is! Map) return false;
+ if (shelf != 'continue-series') return _hiddenShelfItems.containsKey(e['id']);
+ final series = [
+ ((e['media'] as Map?)?['metadata'] as Map?)?['series'],
+ e['series'],
+ ].expand((s) => s is List ? s : [s]);
+ return series.any((s) => s is Map && _hiddenShelfSeries.containsKey(s['id']));
+ }
+
+ return [
+ for (final section in sections)
+ if (section is Map<String, dynamic> &&
+ const {'continue-listening', 'continue-reading', 'continue-series'}.contains(section['id']))
+ {
+ ...section,
+ 'entities': [
+ for (final e in (section['entities'] as List<dynamic>? ?? const []))
+ if (!hidden(section['id'] as String, e)) e,
+ ],
+ }
+ else
+ section,
+ ];
}
/// If one of [seriesIds] (the opened book's series) is currently shown in the
@@ -1403,19 +1451,25 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
/// BookOrbit pushes no progress events, so while the app is open the book
/// sitting paused in the player is checked against the server instead, and
/// a newer position from another device goes through the same handler the
- /// Audiobookshelf socket feeds.
+ /// Audiobookshelf socket feeds. Its notification feed runs alongside.
void _startBookOrbitPoll() {
_bookOrbitPollTimer?.cancel();
_bookOrbitPollTimer = null;
- if (_auth?.isBookOrbit != true) return;
- if (_isBackgrounded || _readerQuiet || PlayerSettings.einkMode) return;
+ final api = _api;
+ if (_auth?.isBookOrbit != true || api == null ||
+ _isBackgrounded || _readerQuiet || PlayerSettings.einkMode) {
+ BookOrbitNotificationSocket.instance.stop();
+ return;
+ }
_bookOrbitPollTimer = Timer.periodic(
const Duration(seconds: 30), (_) => _pollPausedBookProgress());
+ unawaited(BookOrbitNotificationSocket.instance.start(api));
}
void _stopBookOrbitPoll() {
_bookOrbitPollTimer?.cancel();
_bookOrbitPollTimer = null;
+ BookOrbitNotificationSocket.instance.stop();
}
Future<void> _pollPausedBookProgress() async {
@@ -1953,11 +2007,11 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
try {
await _refreshProgress();
- _personalizedSections = await _api!.getPersonalizedView(
+ _personalizedSections = _withoutJustHidden(await _api!.getPersonalizedView(
_selectedLibraryId!,
include: const ['numEpisodesIncomplete'],
) ??
- [];
+ []);
for (final section in _personalizedSections) {
for (final e in (section['entities'] as List<dynamic>? ?? [])) {
if (e is Map<String, dynamic>) {
@@ -2013,7 +2067,12 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final existing = _progressShelvesInFlight;
if (existing != null) {
await existing;
- return;
+ // A forced refresh wants an answer from after it was asked for.
+ if (!force) return;
+ if (_progressShelvesInFlight != null) {
+ await _progressShelvesInFlight;
+ return;
+ }
}
if (!force &&
@@ -2103,7 +2162,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
}
- _personalizedSections = merged;
+ _personalizedSections = _withoutJustHidden(merged);
_narratedToContinueListening();
}
@@ -2193,7 +2252,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
_lastRssHydrationLibraryId = libraryId;
if (_selectedLibraryId == libraryId && sections.isNotEmpty) {
- _personalizedSections = sections;
+ _personalizedSections = _withoutJustHidden(sections);
await (this as _AbsorbingMixin)._updateAbsorbingCache();
notifyListeners();
}
@@ -2587,10 +2646,11 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final id = 'collection:${cm['id']}';
allSections[id] = {
'id': id,
- 'label': 'Server Collection - ${cm['name'] ?? 'Collection'}',
+ 'label': _collectionSectionLabel(cm),
'type': 'collection',
'entities': (cm['books'] as List<dynamic>?) ?? [],
'_collectionId': cm['id'],
+ if (_isSmartScope(cm)) '_smartScope': true,
};
}
@@ -2667,7 +2727,8 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final cm = c as Map<String, dynamic>;
result.add({
'id': 'collection:${cm['id']}',
- 'label': 'Server Collection - ${cm['name'] as String? ?? 'Collection'}',
+ 'label': _collectionSectionLabel(cm),
+ if (_isSmartScope(cm)) 'smartScope': 'true',
});
}
for (final genre in _addedGenres) {
@@ -2679,6 +2740,19 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
return result;
}
+ bool _isSmartScope(Map<String, dynamic> cm) =>
+ (cm['bookOrbit'] as Map?)?['smartScope'] == true;
+
+ // Audiobookshelf collections are shared by everyone on the server, so their
+ // rows say so. BookOrbit lists the user's own collections and Smart Scopes.
+ String _collectionSectionLabel(Map<String, dynamic> cm) {
+ final name = cm['name'] as String? ?? 'Collection';
+ final kind = cm['bookOrbit'] is! Map
+ ? 'Server Collection'
+ : _isSmartScope(cm) ? 'Smart Scope' : 'Collection';
+ return '$kind - $name';
+ }
+
// ── Podcast subscriptions ──
Future<void> _loadKnownEpisodeIds() async {
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index b028c794..8a7e3a22 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -11,6 +11,10 @@ mixin _StateMixin on ChangeNotifier {
bool _librariesFromCache = false;
String? _selectedLibraryId;
List<dynamic> _personalizedSections = [];
+ // Books and series just taken off the Continue shelves, kept off them
+ // until the server's own lists catch up.
+ final Map<String, DateTime> _hiddenShelfItems = {};
+ final Map<String, DateTime> _hiddenShelfSeries = {};
List<dynamic> _series = [];
bool _isLoading = false;
bool _isLoadingSeries = false;
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 39b837de..f7eade20 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -8,6 +8,7 @@ import '../services/scoped_prefs.dart';
import '../services/audio_player_service.dart';
import 'auth_provider.dart';
import '../services/api_service.dart';
+import '../services/bookorbit_notification_socket.dart';
import '../services/progress_sync_service.dart';
import '../services/local_session_service.dart';
import '../services/download_service.dart';
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index a8fdf106..4d876a4a 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -794,7 +794,9 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
} else if (isCollection) {
titleTap = () => CollectionDetailSheet.show(
context, section['_collectionId'] as String);
- sectionIcon = Icons.collections_bookmark_rounded;
+ sectionIcon = section['_smartScope'] == true
+ ? Icons.filter_alt_rounded
+ : Icons.collections_bookmark_rounded;
} else if (id.startsWith('genre:')) {
sectionIcon = Icons.label_outline_rounded;
final sectionLabel = label;
@@ -1369,9 +1371,10 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {
return;
}
- // An Audiobookshelf EPUB that reads itself aloud plays from the phone, so
- // its narration is downloaded first.
+ // An Audiobookshelf EPUB that reads itself aloud streams from the server,
+ // so offline it has to be on the phone already.
if (!auth.isBookOrbit &&
+ widget.lib.isOffline &&
NarratedBooks.contains(itemId) &&
!NarrationService.instance.hasLocalAudio(itemId)) {
setState(() => _isLoading = false);
diff --git a/lib/services/episode_notification_service.dart b/lib/services/episode_notification_service.dart
index ce87d9c1..51f5bb58 100644
--- a/lib/services/episode_notification_service.dart
+++ b/lib/services/episode_notification_service.dart
@@ -1,7 +1,10 @@
import 'dart:convert';
import 'dart:io';
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workmanager/workmanager.dart';
@@ -19,15 +22,19 @@ import 'scoped_prefs.dart';
import 'user_account_service.dart';
import 'package:provider/provider.dart';
-/// Background new-episode notifications (Android). A WorkManager periodic job
+/// Background new-episode notifications. On Android a WorkManager periodic job
/// polls the subscribed shows and notifies about episodes it hasn't notified
-/// about before. The job keeps its own last-seen state (notified_episodes_*),
+/// about before. On iOS the system's background refresh wakes the app and the
+/// check runs in the app itself, as it also does while the app is alive in
+/// the background (playing a book). The job keeps its own last-seen state (notified_episodes_*),
/// separate from known_episodes_* - that one drives the in-app absorbing-queue
/// insertion and auto-download and must keep seeing "new" episodes when the
/// app next opens.
class EpisodeNotificationService {
static const _uniqueName = 'com.barnabas.absorb.episodeNotifCheck';
static const channelId = 'new_episodes';
+ static const _iosChannel = MethodChannel('com.barnabas.absorb/background');
+ static const _lastCheckKey = 'episodeNotifLastCheckMs';
static String notifiedKey(String showId) => 'notified_episodes_$showId';
@@ -82,6 +89,17 @@ class EpisodeNotificationService {
/// Register/cancel the periodic job to match the setting. Called on app
/// start (self-healing after OEM kills) and when the setting changes.
static Future<void> syncRegistration() async {
+ if (Platform.isIOS) {
+ try {
+ final minutes = await PlayerSettings.getEpisodeNotifIntervalMinutes();
+ await _iosChannel.invokeMethod('scheduleEpisodeCheck', {'minutes': minutes});
+ _IosBackgroundTimer.instance.sync(minutes > 0);
+ debugPrint('[EpisodeNotif] iOS background refresh ${minutes > 0 ? 'asked for every ${minutes}m' : 'off'}');
+ } catch (e) {
+ debugPrint('[EpisodeNotif] iOS syncRegistration failed: $e');
+ }
+ return;
+ }
if (!Platform.isAndroid) return;
try {
final minutes = await PlayerSettings.getEpisodeNotifIntervalMinutes();
@@ -107,11 +125,23 @@ class EpisodeNotificationService {
/// Foreground notification-tap wiring. Safe to call once at startup; also
/// resolves a cold start launched from a notification.
static Future<void> initTapHandling() async {
- if (!Platform.isAndroid) return;
+ if (!Platform.isAndroid && !Platform.isIOS) return;
+ if (Platform.isIOS) {
+ _iosChannel.setMethodCallHandler((call) async {
+ if (call.method != 'runEpisodeCheck') return null;
+ return checkInApp();
+ });
+ }
final plugin = FlutterLocalNotificationsPlugin();
await plugin.initialize(
const InitializationSettings(
android: AndroidInitializationSettings('drawable/ic_notification'),
+ // Permission is asked when the user turns notifications on, not here.
+ iOS: DarwinInitializationSettings(
+ requestAlertPermission: false,
+ requestBadgePermission: false,
+ requestSoundPermission: false,
+ ),
),
onDidReceiveNotificationResponse: (resp) => _handleTap(resp.payload),
);
@@ -121,6 +151,37 @@ class EpisodeNotificationService {
}
}
+ /// Asks iOS to allow notifications. True when they are allowed.
+ static Future<bool> requestIosPermission() async {
+ if (!Platform.isIOS) return true;
+ final ios = FlutterLocalNotificationsPlugin()
+ .resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>();
+ return await ios?.requestPermissions(alert: true, sound: true) ?? false;
+ }
+
+ /// The check, run in the app itself (iOS): when the system's background
+ /// refresh wakes it, or while it is alive in the background. Only once the
+ /// chosen interval has passed since the last one. Episodes are left for the
+ /// in-app catch-up to download when the app is next opened.
+ static Future<bool> checkInApp() async {
+ try {
+ final minutes = await PlayerSettings.getEpisodeNotifIntervalMinutes();
+ if (minutes <= 0) return false;
+ final prefs = await SharedPreferences.getInstance();
+ final last = prefs.getInt(_lastCheckKey) ?? 0;
+ final now = DateTime.now().millisecondsSinceEpoch;
+ // A little slack so a wake-up just short of the interval still counts.
+ if (now - last < Duration(minutes: minutes).inMilliseconds * 0.9) return false;
+ await prefs.setInt(_lastCheckKey, now);
+ debugPrint('[EpisodeNotif] checking in the app');
+ await _checkAndNotify(inApp: true);
+ return true;
+ } catch (e) {
+ debugPrint('[EpisodeNotif] in-app check failed: $e');
+ return false;
+ }
+ }
+
/// Open the show's episode list once the app (navigator + session) is up.
static Future<void> _handleTap(String? payload) async {
if (payload == 'upcoming') {
@@ -178,10 +239,12 @@ void episodeNotifDispatcher() {
});
}
-Future<void> _checkAndNotify() async {
+/// [inApp] runs it in the app's own engine (iOS), where the preferences and
+/// the account are already loaded and downloads are left to the app.
+Future<void> _checkAndNotify({bool inApp = false}) async {
// WorkManager uses a separate Flutter engine whose SharedPreferences cache
// can lag behind writes from earlier workers or the foreground app.
- await EpisodeNotificationService.prepareBackgroundPreferences();
+ if (!inApp) await EpisodeNotificationService.prepareBackgroundPreferences();
// Purely local, so it runs before the subscribed-podcasts early return.
await _checkReleaseDayNotifs();
@@ -251,11 +314,13 @@ Future<void> _checkAndNotify() async {
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
),
+ iOS: DarwinNotificationDetails(threadIdentifier: 'new_episodes'),
),
payload: 'show:$showId',
);
await ScopedPrefs.setStringList(key, [...seen, ...fresh.map((e) => e['id'] as String)]);
+ if (inApp) continue;
// Start the downloads now so the episodes are ready when the app next
// opens - same auto-download behavior as the in-app catch-up (WiFi-only
@@ -350,6 +415,7 @@ Future<void> _checkReleaseDayNotifs() async {
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
),
+ iOS: DarwinNotificationDetails(threadIdentifier: 'release_day'),
),
payload: 'upcoming',
);
@@ -365,6 +431,46 @@ Future<void> _checkReleaseDayNotifs() async {
}
}
+/// While the app is alive in the background on iOS (playing a book), runs
+/// the check once it is due. iOS's own background refresh comes when the
+/// system chooses, and a suspended app runs no timers, so this only adds
+/// checks while Absorb is running anyway.
+class _IosBackgroundTimer with WidgetsBindingObserver {
+ _IosBackgroundTimer._();
+ static final instance = _IosBackgroundTimer._();
+
+ bool _on = false;
+ bool _observing = false;
+ Timer? _timer;
+
+ void sync(bool on) {
+ _on = on;
+ if (on && !_observing) {
+ WidgetsBinding.instance.addObserver(this);
+ _observing = true;
+ } else if (!on && _observing) {
+ WidgetsBinding.instance.removeObserver(this);
+ _observing = false;
+ }
+ if (!on) _stop();
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (!_on) return;
+ if (state == AppLifecycleState.paused) {
+ _timer ??= Timer.periodic(const Duration(minutes: 15), (_) => EpisodeNotificationService.checkInApp());
+ } else if (state == AppLifecycleState.resumed) {
+ _stop();
+ }
+ }
+
+ void _stop() {
+ _timer?.cancel();
+ _timer = null;
+ }
+}
+
/// ApiService from raw prefs - same pattern as the home-widget cold path
/// (server_url/token/refresh_token/custom_headers, prefer a reachable local
/// server so home-WiFi setups work).
diff --git a/lib/services/narrated_books.dart b/lib/services/narrated_books.dart
index 11257a72..14324eab 100644
--- a/lib/services/narrated_books.dart
+++ b/lib/services/narrated_books.dart
@@ -9,6 +9,17 @@ import 'package:shared_preferences/shared_preferences.dart';
/// them as audiobooks, and the detail sheet knows straight away which
/// buttons a book gets. Item ids are unique across servers, so one list
/// serves every account.
+/// Whether [item] has an EPUB that reads itself aloud: BookOrbit says so in
+/// its book lists, an Audiobookshelf book once its EPUB has been looked at.
+bool hasReadAlongEbook(Map<String, dynamic>? item) {
+ if (item == null) return false;
+ final bookOrbit = item['bookOrbit'];
+ if (bookOrbit is Map && bookOrbit['readAlong'] == true) return true;
+ if ((item['media'] as Map?)?['narration'] != null) return true;
+ final id = item['id'];
+ return id is String && NarratedBooks.contains(id);
+}
+
class NarratedBooks {
NarratedBooks._();
diff --git a/lib/widgets/book_card.dart b/lib/widgets/book_card.dart
index 85f3c036..c1582853 100644
--- a/lib/widgets/book_card.dart
+++ b/lib/widgets/book_card.dart
@@ -4,6 +4,7 @@ import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../l10n/app_localizations.dart';
import 'cover_badges.dart';
+import '../services/narrated_books.dart';
import '../services/ebook_cache.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
@@ -65,6 +66,7 @@ class BookCard extends StatelessWidget {
final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;
final isDownloaded = DownloadService().isDownloaded(itemId ?? '');
final hasEbook = PlayerSettings.showEbookBadge && hasEbookFile(item);
+ final readAlong = hasEbook && hasReadAlongEbook(item);
// Only compute for podcast shows that aren't being rendered as an episode
// (an episode card shows the recentEpisode payload, not show-level info).
final unfinishedCount = (lib.isPodcastLibrary && item['recentEpisode'] == null)
@@ -74,8 +76,8 @@ class BookCard extends StatelessWidget {
final headers = lib.mediaHeaders;
final card = isWide
- ? _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit, hasEbook: hasEbook)
- : _buildCompactCard(context, cs, tt, l, title, subtitle, authorName, coverUrl, progress, headers, isFinished: isFinished, isSkimmed: isSkimmed, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount, hasEbook: hasEbook);
+ ? _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit, hasEbook: hasEbook, readAlong: readAlong)
+ : _buildCompactCard(context, cs, tt, l, title, subtitle, authorName, coverUrl, progress, headers, isFinished: isFinished, isSkimmed: isSkimmed, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount, hasEbook: hasEbook, readAlong: readAlong);
if (!selectionMode) return card;
// Selection sits on top of the finished card rather than inside both
// layouts: the overlay swallows the tap, so nothing below it can open a
@@ -204,6 +206,7 @@ class BookCard extends StatelessWidget {
Map<String, String> headers, {
bool isExplicit = false,
bool hasEbook = false,
+ bool readAlong = false,
}) {
return Card(
elevation: 0,
@@ -224,7 +227,7 @@ class BookCard extends StatelessWidget {
children: [
_CoverImage(coverUrl: coverUrl, cs: cs, fit: BoxFit.contain, httpHeaders: headers, title: title, author: authorName),
if (hasEbook && !selectionMode)
- const Positioned(top: 4, left: 4, child: EbookCoverBadge()),
+ Positioned(top: 4, left: 4, child: EbookCoverBadge(readAlong: readAlong)),
if (isExplicit)
Positioned(
top: 4, right: DownloadService().isDownloaded(item['id'] as String? ?? '') ? 30 : 4,
@@ -327,6 +330,7 @@ class BookCard extends StatelessWidget {
bool isExplicit = false,
int unfinishedCount = 0,
bool hasEbook = false,
+ bool readAlong = false,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -403,7 +407,7 @@ class BookCard extends StatelessWidget {
),
),
if (hasEbook && !selectionMode)
- const Positioned(top: 4, left: 4, child: EbookCoverBadge()),
+ Positioned(top: 4, left: 4, child: EbookCoverBadge(readAlong: readAlong)),
if (isFinished || isDownloaded)
Positioned(
left: 0, right: 0, bottom: 0,
diff --git a/lib/widgets/cover_badges.dart b/lib/widgets/cover_badges.dart
index 903c0a5d..28058fc9 100644
--- a/lib/widgets/cover_badges.dart
+++ b/lib/widgets/cover_badges.dart
@@ -107,13 +107,29 @@ class CoverStateBadges extends StatelessWidget {
}
}
-/// Small book icon for a cover corner, on books that come with an ebook:
+/// Small book icon for a cover corner, on books that come with an ebook,
+/// with headphones beside it when the ebook reads itself aloud:
/// Positioned(top: 4, left: 4, child: EbookCoverBadge())
class EbookCoverBadge extends StatelessWidget {
- const EbookCoverBadge({super.key});
+ final bool readAlong;
+ const EbookCoverBadge({super.key, this.readAlong = false});
@override
Widget build(BuildContext context) {
+ if (readAlong) {
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 3),
+ decoration: BoxDecoration(
+ color: Colors.black.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(9),
+ ),
+ child: const Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.menu_book_rounded, size: 11, color: Colors.white),
+ SizedBox(width: 2),
+ Icon(Icons.headphones_rounded, size: 11, color: Colors.white),
+ ]),
+ );
+ }
return Container(
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
diff --git a/lib/widgets/home_customize_sheet.dart b/lib/widgets/home_customize_sheet.dart
index 2cce0578..c7ecbc49 100644
--- a/lib/widgets/home_customize_sheet.dart
+++ b/lib/widgets/home_customize_sheet.dart
@@ -293,7 +293,9 @@ class _HomeCustomizeSheetState extends State<HomeCustomizeSheet> {
final icon = isPlaylist
? Icons.playlist_play_rounded
: isCollection
- ? Icons.collections_bookmark_rounded
+ ? (section['smartScope'] == 'true'
+ ? Icons.filter_alt_rounded
+ : Icons.collections_bookmark_rounded)
: isGenre
? Icons.label_outline_rounded
: (_sectionIcons[id] ?? Icons.album_outlined);
diff --git a/lib/widgets/home_section.dart b/lib/widgets/home_section.dart
index decc2535..aae9d621 100644
--- a/lib/widgets/home_section.dart
+++ b/lib/widgets/home_section.dart
@@ -244,8 +244,10 @@ class HomeSection extends StatelessWidget {
}
String _collectionNameFromTitle(String value) {
- const prefix = 'Server Collection - ';
- return value.startsWith(prefix) ? value.substring(prefix.length) : value;
+ for (final prefix in const ['Server Collection - ', 'Smart Scope - ', 'Collection - ']) {
+ if (value.startsWith(prefix)) return value.substring(prefix.length);
+ }
+ return value;
}
}
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index 9a50775c..e0d758b9 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -4,6 +4,7 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../l10n/app_localizations.dart';
import 'cover_badges.dart';
+import '../services/narrated_books.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
@@ -81,6 +82,7 @@ class _GridBookTileState extends State<GridBookTile> {
final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;
final isDownloaded = _dl.isDownloaded(itemId);
final hasEbook = PlayerSettings.showEbookBadge && hasEbookFile(widget.item);
+ final readAlong = hasEbook && hasReadAlongEbook(widget.item);
final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;
final isSkimmed = lib.getProgressData(itemId)?['skimmed'] == true;
final isSubscribed = lib.isPodcastLibrary && lib.isPodcastSubscribed(itemId);
@@ -200,7 +202,7 @@ class _GridBookTileState extends State<GridBookTile> {
if (hasEbook && !widget.selectionMode)
Positioned(
top: widget.sequenceBadge != null ? 24 : 4, left: 4,
- child: const EbookCoverBadge(),
+ child: EbookCoverBadge(readAlong: readAlong),
),
// Sequence badge
diff --git a/lib/widgets/whats_new_prompt.dart b/lib/widgets/whats_new_prompt.dart
index 5c82574c..ae4b1101 100644
--- a/lib/widgets/whats_new_prompt.dart
+++ b/lib/widgets/whats_new_prompt.dart
@@ -11,8 +11,17 @@ import 'welcome_sheet.dart';
/// After an update, offers the GitHub release notes for the new build.
class WhatsNewPrompt {
static const _lastBuildKey = 'whats_new_last_build';
+ static const _enabledKey = 'whats_new_enabled';
static const _isDevBuild = bool.fromEnvironment('DEV_BUILD');
+ /// Some people read the release notes on GitHub anyway, so the prompt can
+ /// be turned off, from the prompt itself or in Settings.
+ static Future<bool> isEnabled() async =>
+ (await SharedPreferences.getInstance()).getBool(_enabledKey) ?? true;
+
+ static Future<void> setEnabled(bool on) async =>
+ (await SharedPreferences.getInstance()).setBool(_enabledKey, on);
+
/// Call before [WelcomeSheet.showIfNeeded]: a fresh install hasn't seen the
/// welcome yet, and that's how it's told apart from an update.
static Future<void> showIfUpdated(BuildContext context) async {
@@ -25,6 +34,7 @@ class WhatsNewPrompt {
final lastBuild = prefs.getInt(_lastBuildKey);
await prefs.setInt(_lastBuildKey, build);
if (freshInstall || (lastBuild != null && build <= lastBuild)) return;
+ if (prefs.getBool(_enabledKey) == false) return;
final beta = betaNumberFor(info.version);
final tag = beta == null ? 'v${info.version}' : 'v${info.version}-$build';
@@ -36,11 +46,31 @@ class WhatsNewPrompt {
final l = AppLocalizations.of(context)!;
final version =
beta == null ? info.version : '${info.version} (${l.betaLabel(beta)})';
+ var keepShowing = true;
final open = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l.whatsNewTitle),
- content: Text(l.whatsNewContent(version)),
+ content: StatefulBuilder(
+ builder: (ctx, setDialogState) => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.whatsNewContent(version)),
+ const SizedBox(height: 12),
+ SwitchListTile(
+ contentPadding: EdgeInsets.zero,
+ title: Text(l.whatsNewKeepShowing),
+ subtitle: Text(l.whatsNewKeepShowingHint),
+ value: keepShowing,
+ onChanged: (v) {
+ setDialogState(() => keepShowing = v);
+ setEnabled(v);
+ },
+ ),
+ ],
+ ),
+ ),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),