A cross platform Audiobookshelf client for Android and iOS
Dart
Round out iOS native player: streaming, lock screen, iCloud
Barnabas0ecd63c1b401
diff --git a/ios/Runner/AbsorbPlayerCore.swift b/ios/Runner/AbsorbPlayerCore.swiftindex 9eab4924..84ca070a 100644--- a/ios/Runner/AbsorbPlayerCore.swift+++ b/ios/Runner/AbsorbPlayerCore.swift@@ -1,35 +1,35 @@import AbsorbPlayerCoreimport AVFoundationimport Foundation+import MediaPlayer+import UIKit-/// Phase 1.3: native AVAudioPlayer driving downloaded audiobook playback.+/// Phase 1.7: native player core that drives downloaded AND streaming+/// audiobooks via AVPlayer, exposes lock-screen / Control Center / CarPlay+/// metadata via MPNowPlayingInfoCenter, and handles remote commands via+/// MPRemoteCommandCenter.///-/// Reads playback state from the app group (`np_*` keys written by-/// `home_widget_service.dart`), loads the first downloaded track, seeks to-/// the saved position, and plays. Streaming-only items get a no-op for now-/// (Phase 2 will pick up token + URL handling).-///-/// Logging hits absorb's in-app log viewer via `logSink` so we don't need-/// Xcode/Console.app to verify behavior.-final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDelegate, @unchecked Sendable {+/// Reads playback state from the iOS app group (`np_*` keys written by+/// `home_widget_service.dart`), respects the `audio_owner_alive_at`+/// heartbeat so it doesn't double-drive while Flutter is in charge, and+/// keeps Flutter in sync by writing position back as it plays.+final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sendable {static let shared = AbsorbPlayerCore()- /// AppDelegate populates this so log lines get forwarded to Flutter and- /// surface in the in-app log viewer. Stays nil if the host app hasn't- /// set up the widget channel yet (e.g. during init).static var logSink: ((String) -> Void)?private static let appGroup = "group.com.barnabas.absorb"- /// Serializes access to `_player` so calls from intent perform() and- /// Flutter channel handlers don't trample each other.+ /// Serializes mutation of `_player` and friends across the various entry+ /// points (intent perform(), remote commands, periodic timer).private let queue = DispatchQueue(label: "com.barnabas.absorb.nativecore")- private var _player: AVAudioPlayer?+ private var _player: AVPlayer?private var _currentItemId: String?- /// Position-write timer: persists current playhead back to the app group- /// every few seconds so Flutter sees up-to-date progress when it wakes.- private var _positionTimer: Timer?+ private var _currentEpisodeId: String?+ private var _periodicObserver: Any?+ private var _itemEndObserver: NSObjectProtocol?+ private var _commandsConfigured = falseprivate override init() {super.init()@@ -47,8 +47,10 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerD}self?.activateAudioSession()p.play()- self?.emit("[NativeCore] play(): playing=\(p.isPlaying) pos=\(p.currentTime)s")+ self?.applySpeed(to: p)+ self?.emit("[NativeCore] play(): rate=\(p.rate)")self?.startPositionTimer()+ self?.updateNowPlayingInfo(rate: Double(p.rate))}}@@ -59,9 +61,10 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDreturn}p.pause()- self?.emit("[NativeCore] pause(): pos=\(p.currentTime)s")+ let pos = p.currentTime().seconds+ self?.emit("[NativeCore] pause(): pos=\(pos)s")self?.savePosition()- self?.stopPositionTimer()+ self?.updateNowPlayingInfo(rate: 0)}}@@ -72,16 +75,18 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDself?.emit("[NativeCore] toggle(): no player loaded")return}- if p.isPlaying {+ if p.rate > 0 {p.pause()- self?.emit("[NativeCore] toggle(): paused at \(p.currentTime)s")+ self?.emit("[NativeCore] toggle(): paused")self?.savePosition()- self?.stopPositionTimer()+ self?.updateNowPlayingInfo(rate: 0)} else {self?.activateAudioSession()p.play()- self?.emit("[NativeCore] toggle(): playing from \(p.currentTime)s")+ self?.applySpeed(to: p)+ self?.emit("[NativeCore] toggle(): playing rate=\(p.rate)")self?.startPositionTimer()+ self?.updateNowPlayingInfo(rate: Double(p.rate))}}}@@ -92,10 +97,11 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDself?.emit("[NativeCore] skipForward: no player")return}- let target = min(p.duration, p.currentTime + Double(seconds))- p.currentTime = target+ let now = p.currentTime().seconds.isFinite ? p.currentTime().seconds : 0+ let dur = self?.currentDuration() ?? 0+ let target = min(dur > 0 ? dur : .greatestFiniteMagnitude, now + Double(seconds))+ self?.seekInternal(to: target)self?.emit("[NativeCore] skipForward(\(seconds)s) -> \(target)s")- self?.savePosition()}}@@ -105,10 +111,10 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDself?.emit("[NativeCore] skipBackward: no player")return}- let target = max(0, p.currentTime - Double(seconds))- p.currentTime = target+ let now = p.currentTime().seconds.isFinite ? p.currentTime().seconds : 0+ let target = max(0, now - Double(seconds))+ self?.seekInternal(to: target)self?.emit("[NativeCore] skipBackward(\(seconds)s) -> \(target)s")- self?.savePosition()}}@@ -118,10 +124,8 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerD// MARK: - State plumbing- /// Phase 1.4 hand-off check. If Flutter wrote a recent- /// `audio_owner_alive_at` timestamp, it's alive and owns playback. The- /// native core bails so we don't double-drive the audio engine. Stale or- /// missing timestamp means Flutter is dead and we can take over.+ /// Phase 1.4 hand-off check. Recent heartbeat means Flutter is alive and+ /// owns playback - native bails so we don't double-drive.private func flutterIsAlive() -> Bool {let defaults = UserDefaults(suiteName: Self.appGroup)guard let aliveAt = defaults?.object(forKey: "audio_owner_alive_at") as? Int else {@@ -132,8 +136,9 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDreturn ageMs >= 0 && ageMs < 30_000}- /// Lazily load the AVAudioPlayer from the app group's stashed playback- /// state. Caches the loaded player; rebuilds if the active item changed.+ /// Lazily load AVPlayer from app group state. Caches the player; rebuilds+ /// only when the active item changes. Picks downloaded file path or+ /// streaming URL based on `np_is_downloaded`.private func ensureLoaded() {if flutterIsAlive() {emit("[NativeCore] ensureLoaded: Flutter is alive, skipping native load")@@ -144,49 +149,120 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDemit("[NativeCore] ensureLoaded: no np_item_id in app group")return}- if _player != nil && itemId == _currentItemId { return }+ let episodeId = defaults?.string(forKey: "np_episode_id")+ if _player != nil && itemId == _currentItemId && episodeId == _currentEpisodeId {+ return+ }- // Streaming-only: bail until Phase 2 wires auth tokens.let isDownloaded = defaults?.bool(forKey: "np_is_downloaded") ?? false- if !isDownloaded {- emit("[NativeCore] ensureLoaded: \(itemId) is streaming-only, skipping (Phase 2)")+ let asset: AVURLAsset?+ if isDownloaded,+ let pathsJson = defaults?.string(forKey: "np_audio_paths_json"),+ let pathsData = pathsJson.data(using: .utf8),+ let paths = try? JSONSerialization.jsonObject(with: pathsData) as? [String],+ let firstPath = paths.first,+ FileManager.default.fileExists(atPath: firstPath) {+ asset = AVURLAsset(url: URL(fileURLWithPath: firstPath))+ emit("[NativeCore] Loading downloaded \(itemId) from \(firstPath)")+ } else if let urlsJson = defaults?.string(forKey: "np_stream_urls_json"),+ let urlsData = urlsJson.data(using: .utf8),+ let urls = try? JSONSerialization.jsonObject(with: urlsData) as? [String],+ let firstUrl = urls.first,+ let streamUrl = URL(string: firstUrl) {+ var options: [String: Any] = [:]+ if let headersJson = defaults?.string(forKey: "np_stream_headers_json"),+ let headersData = headersJson.data(using: .utf8),+ let headers = try? JSONSerialization.jsonObject(with: headersData) as? [String: String],+ !headers.isEmpty {+ // Private but long-standing key for passing custom HTTP headers+ // through AVURLAsset; documented widely though not in the public+ // SDK. Required for Cloudflare Access and similar reverse-proxy+ // auth that can't ride in the URL.+ options["AVURLAssetHTTPHeaderFieldsKey"] = headers+ }+ asset = AVURLAsset(url: streamUrl, options: options)+ emit("[NativeCore] Loading stream \(itemId) from \(firstUrl)")+ } else {+ emit("[NativeCore] ensureLoaded: no playable source for \(itemId)")return}- guard let pathsJson = defaults?.string(forKey: "np_audio_paths_json"),- let pathsData = pathsJson.data(using: .utf8),- let paths = try? JSONSerialization.jsonObject(with: pathsData) as? [String],- let firstPath = paths.first else {- emit("[NativeCore] ensureLoaded: no audio paths for \(itemId)")- return+ guard let asset = asset else { return }+ let item = AVPlayerItem(asset: asset)+ let player = AVPlayer(playerItem: item)++ let savedPos = defaults?.double(forKey: "np_position_s") ?? 0+ if savedPos > 0 {+ player.seek(to: CMTime(seconds: savedPos, preferredTimescale: 1000))}- let url = URL(fileURLWithPath: firstPath)- guard FileManager.default.fileExists(atPath: firstPath) else {- emit("[NativeCore] ensureLoaded: file missing at \(firstPath)")- return+ _player = player+ _currentItemId = itemId+ _currentEpisodeId = episodeId+ observeItemEnd(item)+ addPeriodicObserver(player: player)+ configureRemoteCommandsIfNeeded()+ updateNowPlayingInfo(rate: 0)++ emit("[NativeCore] Loaded \(itemId) at \(savedPos)s")+ }++ private func currentDuration() -> Double {+ let defaults = UserDefaults(suiteName: Self.appGroup)+ let stashed = defaults?.double(forKey: "np_total_s") ?? 0+ if stashed > 0 { return stashed }+ if let dur = _player?.currentItem?.duration.seconds, dur.isFinite, dur > 0 {+ return dur}+ return 0+ }- do {- let p = try AVAudioPlayer(contentsOf: url)- p.delegate = self- p.enableRate = true- let savedPos = defaults?.double(forKey: "np_position_s") ?? 0- let speed = defaults?.double(forKey: "np_speed") ?? 1.0- p.currentTime = max(0, min(p.duration, savedPos))- p.rate = Float(speed > 0 ? speed : 1.0)- p.prepareToPlay()- _player = p- _currentItemId = itemId- emit("[NativeCore] Loaded \(itemId) from \(firstPath) pos=\(savedPos)s speed=\(speed)x duration=\(p.duration)s")- } catch {- emit("[NativeCore] AVAudioPlayer load failed: \(error.localizedDescription)")+ private func applySpeed(to player: AVPlayer) {+ let defaults = UserDefaults(suiteName: Self.appGroup)+ let speed = defaults?.double(forKey: "np_speed") ?? 1.0+ player.rate = Float(speed > 0 ? speed : 1.0)+ }++ private func seekInternal(to seconds: Double) {+ guard let p = _player else { return }+ p.seek(to: CMTime(seconds: seconds, preferredTimescale: 1000),+ toleranceBefore: .zero, toleranceAfter: .zero) { [weak self] _ in+ self?.savePosition()+ self?.updateNowPlayingInfo(rate: Double(p.rate))+ }+ }++ private func observeItemEnd(_ item: AVPlayerItem) {+ if let prev = _itemEndObserver {+ NotificationCenter.default.removeObserver(prev)+ }+ _itemEndObserver = NotificationCenter.default.addObserver(+ forName: .AVPlayerItemDidPlayToEndTime,+ object: item,+ queue: nil+ ) { [weak self] _ in+ self?.queue.async {+ self?.emit("[NativeCore] AVPlayerItem reached end")+ self?.savePosition()+ self?.updateNowPlayingInfo(rate: 0)+ }}}- /// Activate the system audio session so AVAudioPlayer actually produces- /// sound. Already done in the widget intent's perform() too (belt and- /// suspenders, since session state can drop between processes).+ private func addPeriodicObserver(player: AVPlayer) {+ if let prev = _periodicObserver {+ player.removeTimeObserver(prev)+ }+ _periodicObserver = player.addPeriodicTimeObserver(+ forInterval: CMTime(seconds: 5, preferredTimescale: 1),+ queue: .main+ ) { [weak self] _ in+ self?.queue.async { self?.savePosition() }+ }+ }++ /// Activate the playback audio session so AVPlayer actually produces+ /// sound. Belt-and-suspenders alongside the widget's own activation.private func activateAudioSession() {let session = AVAudioSession.sharedInstance()do {@@ -199,35 +275,105 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, AVAudioPlayerDprivate func savePosition() {guard let p = _player else { return }+ let pos = p.currentTime().seconds+ if !pos.isFinite { return }let defaults = UserDefaults(suiteName: Self.appGroup)- defaults?.set(p.currentTime, forKey: "np_position_s")- defaults?.set(p.isPlaying, forKey: "widget_is_playing")+ defaults?.set(pos, forKey: "np_position_s")+ defaults?.set(p.rate > 0, forKey: "widget_is_playing")}private func startPositionTimer() {- DispatchQueue.main.async { [weak self] in- self?._positionTimer?.invalidate()- self?._positionTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in- self?.queue.async { self?.savePosition() }- }- }+ // Periodic time observer already saves position every 5s. Keeping this+ // method as a no-op for symmetry with the previous AVAudioPlayer-based+ // version; callers don't need to know which mechanism we're using.}- private func stopPositionTimer() {- DispatchQueue.main.async { [weak self] in- self?._positionTimer?.invalidate()- self?._positionTimer = nil+ // MARK: - MPNowPlayingInfoCenter++ /// Push title / author / artwork / duration / elapsed / rate to the+ /// system "Now Playing" so lock screen, Control Center, CarPlay, AirPods+ /// long-press menu etc. all show what we're playing and let the user+ /// pause/scrub from those surfaces.+ private func updateNowPlayingInfo(rate: Double) {+ guard let p = _player else { return }+ let defaults = UserDefaults(suiteName: Self.appGroup)+ let title = defaults?.string(forKey: "np_title")+ ?? defaults?.string(forKey: "widget_title")+ ?? ""+ let author = defaults?.string(forKey: "np_author")+ ?? defaults?.string(forKey: "widget_author")+ ?? ""+ let coverPath = defaults?.string(forKey: "np_cover_path")+ ?? defaults?.string(forKey: "widget_cover_path")+ let duration = currentDuration()+ let elapsed = p.currentTime().seconds.isFinite ? p.currentTime().seconds : 0++ var info: [String: Any] = [+ MPMediaItemPropertyTitle: title,+ MPMediaItemPropertyArtist: author,+ MPNowPlayingInfoPropertyElapsedPlaybackTime: elapsed,+ MPNowPlayingInfoPropertyPlaybackRate: rate,+ MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue,+ ]+ if duration > 0 {+ info[MPMediaItemPropertyPlaybackDuration] = duration+ }+ if let coverPath = coverPath, let img = UIImage(contentsOfFile: coverPath) {+ let artwork = MPMediaItemArtwork(boundsSize: img.size) { _ in img }+ info[MPMediaItemPropertyArtwork] = artwork}+ MPNowPlayingInfoCenter.default().nowPlayingInfo = info}- // MARK: - AVAudioPlayerDelegate+ // MARK: - MPRemoteCommandCenter- func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {- queue.async { [weak self] in- self?.emit("[NativeCore] audioPlayerDidFinishPlaying success=\(flag)")- self?.savePosition()- self?.stopPositionTimer()+ /// Wire up lock screen / Control Center / AirPods / CarPlay remote+ /// commands once. Each handler bounces back through the public+ /// play/pause/skip API so flutter-alive coordination still applies.+ private func configureRemoteCommandsIfNeeded() {+ if _commandsConfigured { return }+ _commandsConfigured = true+ let cc = MPRemoteCommandCenter.shared()++ cc.playCommand.addTarget { [weak self] _ in+ self?.emit("[NativeCore] remote: play")+ self?.play()+ return .success+ }+ cc.pauseCommand.addTarget { [weak self] _ in+ self?.emit("[NativeCore] remote: pause")+ self?.pause()+ return .success+ }+ cc.togglePlayPauseCommand.addTarget { [weak self] _ in+ self?.emit("[NativeCore] remote: toggle")+ self?.toggle()+ return .success+ }++ cc.skipForwardCommand.preferredIntervals = [30]+ cc.skipForwardCommand.addTarget { [weak self] event in+ let interval = (event as? MPSkipIntervalCommandEvent)?.interval ?? 30+ self?.skipForward(seconds: Int(interval))+ return .success+ }+ cc.skipBackwardCommand.preferredIntervals = [10]+ cc.skipBackwardCommand.addTarget { [weak self] event in+ let interval = (event as? MPSkipIntervalCommandEvent)?.interval ?? 10+ self?.skipBackward(seconds: Int(interval))+ return .success+ }++ cc.changePlaybackPositionCommand.addTarget { [weak self] event in+ guard let event = event as? MPChangePlaybackPositionCommandEvent else {+ return .commandFailed+ }+ self?.queue.async {+ self?.seekInternal(to: event.positionTime)+ }+ return .success}+ emit("[NativeCore] Remote command center wired")}// MARK: - Loggingdiff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swiftindex 55ba5330..e0d52a64 100644--- a/ios/Runner/AppDelegate.swift+++ b/ios/Runner/AppDelegate.swift@@ -179,6 +179,23 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlNSLog("[WidgetDebug] getGroupContainerPath: containerURL returned nil - app group entitlement missing or misconfigured")result(nil)}+ case "excludeFromBackup":+ // Stops iCloud from backing up downloaded audio files. Audiobooks+ // are large and re-downloadable, no point eating user's iCloud+ // quota. Called by DownloadService for each file post-download or+ // post-migration.+ let args = call.arguments as? [String: Any]+ guard let path = args?["path"] as? String else { result(false); return }+ var url = URL(fileURLWithPath: path)+ do {+ var values = URLResourceValues()+ values.isExcludedFromBackup = true+ try url.setResourceValues(values)+ result(true)+ } catch {+ NSLog("[WidgetDebug] excludeFromBackup failed for %@: %@", path, error.localizedDescription)+ result(false)+ }default:result(FlutterMethodNotImplemented)}diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex dffd00e8..6a866ba6 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -786,6 +786,14 @@ class AudioPlayerService extends ChangeNotifier {ApiService? _api;ApiService? get currentApi => _api;String? _playbackSessionId;+ /// Phase 1.7: latest streaming URLs (with auth token already in the+ /// query string) and custom HTTP headers needed by reverse proxies like+ /// Cloudflare Access. Stashed to the iOS app group on each player update+ /// so the native widget core can keep playing if Flutter dies.+ List<String> _activeStreamUrls = const [];+ Map<String, String> _activeStreamHeaders = const {};+ List<String> get activeStreamUrls => _activeStreamUrls;+ Map<String, String> get activeStreamHeaders => _activeStreamHeaders;bool _isOfflineMode = false;bool _isBackgrounded = false;bool get isBackgrounded => _isBackgrounded;@@ -983,6 +991,22 @@ class AudioPlayerService extends ChangeNotifier {debugPrint('[Player] Track offsets: $_trackStartOffsets');}+ /// Phase 1.7: snapshot the URLs and HTTP headers used to build the+ /// streaming AudioSource so the iOS native widget core can hit the same+ /// endpoints if Flutter dies. Token is already in the URL; custom headers+ /// (Cloudflare Access etc.) ride along for reverse-proxy auth.+ void _captureStreamUrls(List<dynamic> audioTracks, ApiService api) {+ final urls = <String>[];+ for (final t in audioTracks) {+ final track = t as Map<String, dynamic>;+ final contentUrl = track['contentUrl'] as String? ?? '';+ if (contentUrl.isEmpty) continue;+ urls.add(api.buildTrackUrl(contentUrl));+ }+ _activeStreamUrls = urls;+ _activeStreamHeaders = Map<String, String>.from(api.mediaHeaders);+ }+/// Subscribe to track index changes for multi-file playback.void _subscribeTrackIndex() {_indexSub?.cancel();@@ -1365,6 +1389,18 @@ class AudioPlayerService extends ChangeNotifier {}}+ // Phase 1.6: if the iOS native player core was driving while Flutter was+ // dead, it stamped a fresher `np_position_s` to the app group. Pick that+ // up so opening absorb after a widget-tap session shows the right spot.+ if (Platform.isIOS && !forceStartTime) {+ final nativePos = await HomeWidgetService()+ .getNativeNowPlayingPosition(itemId, episodeId);+ if (nativePos != null && nativePos > startTime + 1.0) {+ debugPrint('[Player] Resuming from native widget position: ${nativePos}s (was ${startTime}s)');+ startTime = nativePos;+ }+ }+// Set seek target early so the UI doesn't flash chapter 1 while loadingif (startTime > 0) {_lastSeekTargetSeconds = startTime;@@ -1797,6 +1833,7 @@ class AudioPlayerService extends ChangeNotifier {_currentTrackIndex = 0;final audioHeaders = api.mediaHeaders;_buildTrackOffsets(audioTracks);+ _captureStreamUrls(audioTracks, api);AudioSource source;if (audioTracks.length == 1) {final track = audioTracks.first as Map<String, dynamic>;@@ -2030,8 +2067,9 @@ class AudioPlayerService extends ChangeNotifier {_currentTrackIndex = 0;final audioHeaders = api.mediaHeaders;- // Build audio source — one source per track file+ // Build audio source - one source per track file_buildTrackOffsets(audioTracks);+ _captureStreamUrls(audioTracks, api);AudioSource source;if (audioTracks.length == 1) {final track = audioTracks.first as Map<String, dynamic>;diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex e33fa8aa..22b64204 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -268,6 +268,22 @@ class DownloadService extends ChangeNotifier {/// (the app group entitlement may roll in mid-session).String? _iosAppGroupContainerPath;+ /// Stops iCloud from backing up an audio file. Audiobooks are large and+ /// re-downloadable from the user's ABS server, so eating their iCloud+ /// quota would only cause problems (system backup breaks once quota is+ /// hit). iOS-only no-op elsewhere.+ Future<void> _excludeFromBackup(String path) async {+ if (!Platform.isIOS) return;+ try {+ await _widgetChannel.invokeMethod<bool>(+ 'excludeFromBackup',+ {'path': path},+ );+ } catch (e) {+ debugPrint('[Download] excludeFromBackup failed for $path: $e');+ }+ }+/// Returns the iOS app group's audio directory (`<group>/audio/downloads`),/// or null on Android / when the app group entitlement isn't available./// Audio downloads live here so the native player core can read them@@ -499,6 +515,7 @@ class DownloadService extends ChangeNotifier {try { newFile.deleteSync(); } catch (_) {}}await oldFile.rename(newPath);+ await _excludeFromBackup(newPath);newPaths.add(newPath);needsUpdate = true;moved++;@@ -1018,6 +1035,7 @@ class DownloadService extends ChangeNotifier {await sink.close();}localPaths[i] = filePath;+ await _excludeFromBackup(filePath);}// Download tracks in parallel batches of 3diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex 2ea5a792..7a5fa73e 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -141,6 +141,29 @@ class HomeWidgetService {}}+ /// Phase 1.6: read the native player core's last position for an item, so+ /// when Flutter wakes up after a widget-driven session it can pick up+ /// where native left off. Returns null if the stashed `np_item_id` doesn't+ /// match (the app group has data for some other item) or if reads fail.+ ///+ /// iOS only - Android doesn't have the native core path.+ Future<double?> getNativeNowPlayingPosition(+ String itemId, String? episodeId) async {+ if (!Platform.isIOS) return null;+ try {+ final stashedItem = await HomeWidget.getWidgetData<String>('np_item_id');+ if (stashedItem != itemId) return null;+ final stashedEpisode =+ await HomeWidget.getWidgetData<String>('np_episode_id');+ if (stashedEpisode != episodeId) return null;+ final pos = await HomeWidget.getWidgetData<double>('np_position_s');+ return pos;+ } catch (e) {+ debugPrint('[WidgetDebug] getNativeNowPlayingPosition failed: $e');+ return null;+ }+ }+void dispose() {_progressTimer?.cancel();_statsTimer?.cancel();@@ -424,13 +447,30 @@ class HomeWidgetService {}// Downloaded audio file paths (one per track for multi-file books).- // Empty list => streaming-only, native core will skip Phase 1 playback- // for now and Phase 2 will pick up streaming via auth token.final download = DownloadService().getInfo(itemId);final paths = download.localPaths;await HomeWidget.saveWidgetData<String>('np_audio_paths_json', jsonEncode(paths));await HomeWidget.saveWidgetData<bool>('np_is_downloaded', paths.isNotEmpty);++ // Streaming endpoints (token already in URL, plus any reverse-proxy+ // headers like Cloudflare Access). Native picks these up when+ // np_is_downloaded is false.+ await HomeWidget.saveWidgetData<String>(+ 'np_stream_urls_json', jsonEncode(player.activeStreamUrls));+ await HomeWidget.saveWidgetData<String>(+ 'np_stream_headers_json', jsonEncode(player.activeStreamHeaders));++ // Cover path piggybacks on the existing widget_cover_path entry, but+ // expose it under the np_ namespace too for clarity on the native side.+ final coverPath = await HomeWidget.getWidgetData<String>('widget_cover_path');+ if (coverPath != null) {+ await HomeWidget.saveWidgetData<String>('np_cover_path', coverPath);+ }+ await HomeWidget.saveWidgetData<String>(+ 'np_title', player.currentTitle ?? '');+ await HomeWidget.saveWidgetData<String>(+ 'np_author', player.currentAuthor ?? '');}Future<void> _updateAllWidgets() async {