A cross platform Audiobookshelf client for Android and iOS
Dart
Move iOS widget intents into shared package so @Dependency resolves
Barnabasedd1f5e0fc05
diff --git a/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/Intents.swift b/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/Intents.swiftnew file mode 100644index 00000000..272f8e6c--- /dev/null+++ b/ios/AbsorbPlayerCore/Sources/AbsorbPlayerCore/Intents.swift@@ -0,0 +1,115 @@+import AppIntents+import AVFoundation+import Foundation++/// App group used by the host app, the widget extension, and these+/// intents. Hardcoded so the package has no setup at the call site.+public let absorbAppGroup = "group.com.barnabas.absorb"++// MARK: - Helpers++/// Posts a Darwin notification visible to the main app process. Lives in+/// the package so widget intents (and any future Siri/Live Activity+/// intents) share the same wakeup mechanism.+public func postAbsorbDarwinNotification(_ name: String) {+ NSLog("[WidgetDebug] postDarwinNotification: %@", name)+ let center = CFNotificationCenterGetDarwinNotifyCenter()+ CFNotificationCenterPostNotification(center, CFNotificationName(name as CFString), nil, nil, true)+}++/// Activate the system audio session from inside an AudioPlaybackIntent's+/// perform(). AVAudioSession is system-wide, so flipping it on here keeps+/// it active by the time the host app's audio engine runs play() a few+/// hundred ms later. Without this, the iOS-granted "audio playback"+/// privilege from AudioPlaybackIntent expires before the Darwin+/// notification reaches Flutter and the host app's setActive(true)+/// silently fails.+public func activateAbsorbAudioSession() {+ let session = AVAudioSession.sharedInstance()+ do {+ try session.setCategory(.playback, mode: .spokenAudio, options: [])+ try session.setActive(true)+ NSLog("[WidgetDebug] AVAudioSession activated in widget perform()")+ } catch {+ NSLog("[WidgetDebug] AVAudioSession activate error: %@", error.localizedDescription)+ }+}++// MARK: - App Intents+//+// AudioPlaybackIntent (iOS 17+) tells the system this intent controls+// audio playback. Combined with @Dependency on AbsorbPlayerCoreProtocol,+// iOS launches the host app's process (where the dependency is+// registered in AppDelegate) to run perform() rather than running it in+// the widget extension's sandbox where AbsorbPlayerCore isn't reachable.+//+// The intents live in this shared package (rather than the widget+// extension target) so both Runner and NowPlayingWidgetExtension see the+// same Swift type. AppDependencyManager.shared.add() in the host app is+// keyed by Swift type identity, and types declared only in the widget+// extension target wouldn't match anything the host app registered.++public struct AbsorbSkipBackIntent: AudioPlaybackIntent {+ public static let title: LocalizedStringResource = "Skip Back"+ public static let description = IntentDescription("Skip backward in the current audiobook.")+ public static let openAppWhenRun = false++ @Dependency+ private var core: AbsorbPlayerCoreProtocol++ public init() {}++ public func perform() async throws -> some IntentResult {+ core.log("[NativeCore] SkipBackIntent.perform fired (host process)")+ activateAbsorbAudioSession()+ let seconds = UserDefaults(suiteName: absorbAppGroup)?+ .integer(forKey: "widget_skip_back")+ core.skipBackward(seconds: (seconds ?? 0) > 0 ? seconds! : 10)+ postAbsorbDarwinNotification("com.barnabas.absorb.widget.skipBack")+ return .result()+ }+}++public struct AbsorbPlayPauseIntent: AudioPlaybackIntent {+ public static let title: LocalizedStringResource = "Play or Pause"+ public static let description = IntentDescription("Toggle audiobook playback.")+ public static let openAppWhenRun = false++ @Dependency+ private var core: AbsorbPlayerCoreProtocol++ public init() {}++ public func perform() async throws -> some IntentResult {+ core.log("[NativeCore] PlayPauseIntent.perform fired (host process)")+ let defaults = UserDefaults(suiteName: absorbAppGroup)+ let wasPlaying = defaults?.bool(forKey: "widget_is_playing") ?? false+ defaults?.set(!wasPlaying, forKey: "widget_is_playing")+ core.log("[NativeCore] wasPlaying=\(wasPlaying) -> \(!wasPlaying) defaults=\(defaults == nil ? "nil" : "ok")")+ activateAbsorbAudioSession()+ core.toggle()+ postAbsorbDarwinNotification("com.barnabas.absorb.widget.playPause")+ return .result()+ }+}++public struct AbsorbSkipForwardIntent: AudioPlaybackIntent {+ public static let title: LocalizedStringResource = "Skip Forward"+ public static let description = IntentDescription("Skip forward in the current audiobook.")+ public static let openAppWhenRun = false++ @Dependency+ private var core: AbsorbPlayerCoreProtocol++ public init() {}++ public func perform() async throws -> some IntentResult {+ core.log("[NativeCore] SkipForwardIntent.perform fired (host process)")+ activateAbsorbAudioSession()+ let seconds = UserDefaults(suiteName: absorbAppGroup)?+ .integer(forKey: "widget_skip_forward")+ core.skipForward(seconds: (seconds ?? 0) > 0 ? seconds! : 30)+ postAbsorbDarwinNotification("com.barnabas.absorb.widget.skipForward")+ return .result()+ }+}diff --git a/ios/NowPlayingWidget/NowPlayingWidget.swift b/ios/NowPlayingWidget/NowPlayingWidget.swiftindex b4cd4c39..673ca24d 100644--- a/ios/NowPlayingWidget/NowPlayingWidget.swift+++ b/ios/NowPlayingWidget/NowPlayingWidget.swift@@ -12,110 +12,12 @@ private let appGroup = "group.com.barnabas.absorb"// home_widget Flutter plugin intercepts the URL on launch.private let playPauseURL = URL(string: "audiobookshelf://widget/play_pause?homeWidget")!-// MARK: - Darwin Notification Helper--/// Posts a Darwin notification visible to the main app process.-private func postDarwinNotification(_ name: String) {- NSLog("[WidgetDebug] postDarwinNotification: %@", name)- let center = CFNotificationCenterGetDarwinNotifyCenter()- CFNotificationCenterPostNotification(center, CFNotificationName(name as CFString), nil, nil, true)-}--/// Activate the system audio session from inside an AudioPlaybackIntent's-/// perform(). AVAudioSession is system-wide, so flipping it on here keeps it-/// active by the time the host app's audio engine runs play() a few hundred-/// ms later. Without this, the iOS-granted "audio playback" privilege from-/// AudioPlaybackIntent expires before the Darwin notification reaches Flutter-/// and the host app's setActive(true) silently fails — engine state flips to-/// playing=true but no sound comes out.-private func activateAudioSession() {- let session = AVAudioSession.sharedInstance()- do {- try session.setCategory(.playback, mode: .spokenAudio, options: [])- try session.setActive(true)- NSLog("[WidgetDebug] AVAudioSession activated in widget perform()")- } catch {- NSLog("[WidgetDebug] AVAudioSession activate error: %@", error.localizedDescription)- }-}--// MARK: - App Intents (background-capable widget buttons)--// AudioPlaybackIntent (iOS 17+) tells the system this intent controls audio-// playback. The system grants perform() the audio-session privilege; we-// exercise it by activating AVAudioSession before posting the Darwin-// notification so the host app's player can start audio without iOS-// re-checking permissions.--struct SkipBackIntent: AudioPlaybackIntent {- static var title: LocalizedStringResource = "Skip Back"- static var description = IntentDescription("Skip backward in the current audiobook.")-- @Dependency- private var core: AbsorbPlayerCoreProtocol-- func perform() async throws -> some IntentResult {- core.log("[NativeCore] SkipBackIntent.perform fired (host process)")- activateAudioSession()- let seconds = UserDefaults(suiteName: appGroup)?- .integer(forKey: "widget_skip_back")- core.skipBackward(seconds: (seconds ?? 0) > 0 ? seconds! : 10)- postDarwinNotification("com.barnabas.absorb.widget.skipBack")- return .result()- }-}--struct PlayPauseIntent: AudioPlaybackIntent {- static var title: LocalizedStringResource = "Play or Pause"- static var description = IntentDescription("Toggle audiobook playback.")-- /// Declaring this dependency tells iOS to launch the host app's process- /// to run perform() - the AppDependencyManager registration lives in- /// Runner's AppDelegate. Without this the intent runs in the widget- /// extension's sandbox where it can't drive audio.- @Dependency- private var core: AbsorbPlayerCoreProtocol-- func perform() async throws -> some IntentResult {- // Routing through core.log lands the line in absorb's in-app log- // viewer (via the widget channel's "log" method), that's how we- // verify Phase 1 without needing Xcode console access.- core.log("[NativeCore] PlayPauseIntent.perform fired (host process)")- // Optimistic UI: flip the stored state so the widget redraws immediately.- let defaults = UserDefaults(suiteName: appGroup)- let wasPlaying = defaults?.bool(forKey: "widget_is_playing") ?? false- defaults?.set(!wasPlaying, forKey: "widget_is_playing")- core.log("[NativeCore] wasPlaying=\(wasPlaying) -> \(!wasPlaying) defaults=\(defaults == nil ? "nil" : "ok")")-- activateAudioSession()- // Phase 1: native core just logs so we can confirm @Dependency- // resolution actually puts us in the host app process. Once that's- // verified, the core will drive AVAudioEngine here directly and the- // Darwin notification fallback can go away.- core.toggle()- postDarwinNotification("com.barnabas.absorb.widget.playPause")- WidgetCenter.shared.reloadTimelines(ofKind: "NowPlayingWidget")- return .result()- }-}--struct SkipForwardIntent: AudioPlaybackIntent {- static var title: LocalizedStringResource = "Skip Forward"- static var description = IntentDescription("Skip forward in the current audiobook.")-- @Dependency- private var core: AbsorbPlayerCoreProtocol-- func perform() async throws -> some IntentResult {- core.log("[NativeCore] SkipForwardIntent.perform fired (host process)")- activateAudioSession()- let seconds = UserDefaults(suiteName: appGroup)?- .integer(forKey: "widget_skip_forward")- core.skipForward(seconds: (seconds ?? 0) > 0 ? seconds! : 30)- postDarwinNotification("com.barnabas.absorb.widget.skipForward")- return .result()- }-}+// Intents (AbsorbPlayPauseIntent / AbsorbSkipBackIntent /+// AbsorbSkipForwardIntent) live in the AbsorbPlayerCore Swift package so+// both Runner and this extension see the same Swift type. Without that,+// AppDependencyManager registrations made in Runner's AppDelegate can't+// resolve in widget-process intent invocations, the @Dependency throws,+// and only the optimistic UI flip in perform() takes effect.// MARK: - Entry@@ -247,14 +149,14 @@ struct SmallWidgetView: View {.frame(maxWidth: .infinity, alignment: .leading)HStack(spacing: 18) {- Button(intent: SkipBackIntent()) {+ Button(intent: AbsorbSkipBackIntent()) {Image(systemName: "backward.fill").font(.title3).frame(width: 28, height: 28).contentShape(Rectangle())}if entry.hasBook {- Button(intent: PlayPauseIntent()) {+ Button(intent: AbsorbPlayPauseIntent()) {Image(systemName: entry.isPlaying ? "pause.fill" : "play.fill").font(.title2).frame(width: 32, height: 32)@@ -271,7 +173,7 @@ struct SmallWidgetView: View {.contentShape(Rectangle())}}- Button(intent: SkipForwardIntent()) {+ Button(intent: AbsorbSkipForwardIntent()) {Image(systemName: "forward.fill").font(.title3).frame(width: 28, height: 28)@@ -311,7 +213,7 @@ struct MediumWidgetView: View {Spacer(minLength: 0)HStack(spacing: 28) {- Button(intent: SkipBackIntent()) {+ Button(intent: AbsorbSkipBackIntent()) {Image(systemName: "backward.fill").font(.title3).frame(width: 36, height: 36)@@ -319,7 +221,7 @@ struct MediumWidgetView: View {}if entry.hasBook {- Button(intent: PlayPauseIntent()) {+ Button(intent: AbsorbPlayPauseIntent()) {Image(systemName: entry.isPlaying ? "pause.fill" : "play.fill").font(.title2).frame(width: 40, height: 40)@@ -334,7 +236,7 @@ struct MediumWidgetView: View {}}- Button(intent: SkipForwardIntent()) {+ Button(intent: AbsorbSkipForwardIntent()) {Image(systemName: "forward.fill").font(.title3).frame(width: 36, height: 36)diff --git a/pubspec.yaml b/pubspec.yamlindex 20aadd4b..0083d152 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: An Audiobookshelf Clientpublish_to: 'none'-version: 1.8.78+106+version: 1.8.78+107environment:sdk: '>=3.1.0 <4.0.0'