A cross platform Audiobookshelf client for Android and iOS
Dart
Add EPUB3 narration, Siri, keeping reading and listening in sync, reading time in stats and an ebook page history, and stop the reader losing its place on BookOrbit
Barnabasad8498d88948
diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxprojindex cd62e0a6..b0a59b72 100644--- a/ios/Runner.xcodeproj/project.pbxproj+++ b/ios/Runner.xcodeproj/project.pbxproj@@ -28,6 +28,8 @@BB10020000000000000E0007 /* AbsorbAudioBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0007 /* AbsorbAudioBridge.swift */; };BB10020000000000000E0008 /* CarPlayNowPlaying.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0008 /* CarPlayNowPlaying.swift */; };BB10020000000000000E0009 /* NowPlayingPrimer.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0009 /* NowPlayingPrimer.swift */; };+ BB10020000000000000E0040 /* SiriMedia.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0040 /* SiriMedia.swift */; };+ BB10020000000000000E0041 /* SiriShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB10010000000000000E0041 /* SiriShortcuts.swift */; };BB10020000000000000E0020 /* AbsorbPlayerCore in Frameworks */ = {isa = PBXBuildFile; productRef = BB10010000000000000E0020 /* AbsorbPlayerCore */; };BB10020000000000000E0021 /* AbsorbPlayerCore in Frameworks */ = {isa = PBXBuildFile; productRef = BB10010000000000000E0021 /* AbsorbPlayerCore */; };/* End PBXBuildFile section */@@ -109,6 +111,8 @@BB10010000000000000E0007 /* AbsorbAudioBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsorbAudioBridge.swift; sourceTree = "<group>"; };BB10010000000000000E0008 /* CarPlayNowPlaying.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CarPlayNowPlaying.swift; sourceTree = "<group>"; };BB10010000000000000E0009 /* NowPlayingPrimer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowPlayingPrimer.swift; sourceTree = "<group>"; };+ BB10010000000000000E0040 /* SiriMedia.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SiriMedia.swift; sourceTree = "<group>"; };+ BB10010000000000000E0041 /* SiriShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SiriShortcuts.swift; sourceTree = "<group>"; };B7990BE5669E13951B2BAD46 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };DAACD72AEC68ADA3FA213E6C /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };E4A191144C46AC47851AEE49 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };@@ -224,6 +228,8 @@BB10010000000000000E0002 /* IOSQueueAdvancer.swift */,BB10010000000000000E0008 /* CarPlayNowPlaying.swift */,BB10010000000000000E0009 /* NowPlayingPrimer.swift */,+ BB10010000000000000E0040 /* SiriMedia.swift */,+ BB10010000000000000E0041 /* SiriShortcuts.swift */,BB10010000000000000E0030 /* Audio */,74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,);@@ -534,6 +540,8 @@BB10020000000000000E0007 /* AbsorbAudioBridge.swift in Sources */,BB10020000000000000E0008 /* CarPlayNowPlaying.swift in Sources */,BB10020000000000000E0009 /* NowPlayingPrimer.swift in Sources */,+ BB10020000000000000E0040 /* SiriMedia.swift in Sources */,+ BB10020000000000000E0041 /* SiriShortcuts.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;};diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swiftindex c26af534..e296ffe3 100644--- a/ios/Runner/AppDelegate.swift+++ b/ios/Runner/AppDelegate.swift@@ -5,6 +5,7 @@ import UIKitimport AVFoundationimport AVKitimport CoreMedia+import Intentsimport MediaPlayerimport just_audioimport os@@ -94,6 +95,9 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlAbsorbAudioEngine.logSink = { [weak self] line inself?.logToFlutter(line)}+ SiriBridge.logSink = { [weak self] line in+ self?.logToFlutter(line)+ }AbsorbAudioBridge.logSink = { [weak self] line inself?.logToFlutter(line)}@@ -133,6 +137,18 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlreturn super.application(application, didFinishLaunchingWithOptions: launchOptions)}+ /// Siri's "Play <book> on Absorb" runs here in the app process (in-app+ /// intent handling), so playback starts without an Intents extension.+ /// FlutterAppDelegate doesn't implement this, so it is not an override; the+ /// selector is spelled out so UIKit finds it.+ @objc(application:handlerForIntent:)+ func application(_ application: UIApplication, handlerFor intent: INIntent) -> Any? {+ if intent is INPlayMediaIntent {+ return SiriMediaHandler.shared+ }+ return nil+ }+private func registerAudioSessionObservers() {let nc = NotificationCenter.defaultnc.addObserver(@@ -351,6 +367,7 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlIOSQueueAdvancer.shared.register(with: messenger)AbsorbAudioBridge.shared.register(with: messenger)+ SiriBridge.shared.register(with: messenger)// CarPlay Now Playing custom buttons (chapter nav, speed, bookmark). These// decorate CPNowPlayingTemplate only — the lock screen is untouched.diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plistindex 0a0e0505..adfcdeb6 100644--- a/ios/Runner/Info.plist+++ b/ios/Runner/Info.plist@@ -84,6 +84,21 @@<string>audio</string><string>fetch</string></array>+ <key>NSSiriUsageDescription</key>+ <string>Siri can play, pause and find your audiobooks and podcasts in Absorb.</string>+ <key>INIntentsSupported</key>+ <array>+ <string>INPlayMediaIntent</string>+ </array>+ <key>INSupportedMediaCategories</key>+ <array>+ <string>INMediaCategoryAudiobooks</string>+ <string>INMediaCategoryPodcasts</string>+ </array>+ <key>NSUserActivityTypes</key>+ <array>+ <string>INPlayMediaIntent</string>+ </array><key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key>diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlementsindex 2f4f646b..5d095823 100644--- a/ios/Runner/Runner.entitlements+++ b/ios/Runner/Runner.entitlements@@ -8,5 +8,7 @@</array><key>com.apple.developer.carplay-audio</key><true/>+ <key>com.apple.developer.siri</key>+ <true/></dict></plist>diff --git a/ios/Runner/SiriMedia.swift b/ios/Runner/SiriMedia.swiftnew file mode 100644index 00000000..57604cb6--- /dev/null+++ b/ios/Runner/SiriMedia.swift@@ -0,0 +1,392 @@+import AbsorbPlayerCore+import Flutter+import Foundation+import Intents+import UIKit++/// Talks to Dart's SiriService over `com.absorb.siri`. A Siri request can+/// launch the app in the background, where Dart is still booting, so calls+/// made before Dart says it is ready wait for it, up to their timeout.+final class SiriBridge {+ static let shared = SiriBridge()++ static var logSink: ((String) -> Void)?++ private var channel: FlutterMethodChannel?+ private(set) var dartReady = false+ private var waiting: [() -> Void] = []++ func register(with messenger: FlutterBinaryMessenger) {+ let channel = FlutterMethodChannel(name: "com.absorb.siri", binaryMessenger: messenger)+ self.channel = channel+ channel.setMethodCallHandler { [weak self] call, result in+ self?.handle(call, result: result)+ }+ }++ func log(_ line: String) {+ SiriBridge.logSink?("[Siri] \(line)")+ }++ private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {+ let args = call.arguments as? [String: Any] ?? [:]+ switch call.method {+ case "ready":+ dartReady = true+ let pending = waiting+ waiting = []+ log("Dart is ready, \(pending.count) request(s) were waiting")+ pending.forEach { $0() }+ result(true)+ case "catalogUpdated":+ SiriLibrary.update(args)+ result(true)+ case "donate":+ SiriLibrary.donate(args)+ result(true)+ case "authorizationStatus":+ result(SiriLibrary.statusName(INPreferences.siriAuthorizationStatus()))+ case "requestAuthorization":+ INPreferences.requestSiriAuthorization { status in+ DispatchQueue.main.async {+ self.log("authorization -> \(SiriLibrary.statusName(status))")+ result(SiriLibrary.statusName(status))+ }+ }+ case "openSettings":+ if let url = URL(string: UIApplication.openSettingsURLString) {+ UIApplication.shared.open(url)+ }+ result(true)+ default:+ result(FlutterMethodNotImplemented)+ }+ }++ /// Calls Dart, waiting for it to come up first if needed. `completion` runs+ /// once on the main queue with Dart's reply, or nil on a timeout or error;+ /// `sent` says whether the call reached Dart before that, so a slow play+ /// that is already under way isn't reported as a failure.+ func call(+ _ method: String,+ _ args: [String: Any],+ timeout: TimeInterval,+ completion: @escaping (_ reply: [String: Any]?, _ sent: Bool) -> Void+ ) {+ DispatchQueue.main.async {+ var done = false+ var sent = false+ let finish: ([String: Any]?) -> Void = { reply in+ if done { return }+ done = true+ completion(reply, sent)+ }+ DispatchQueue.main.asyncAfter(deadline: .now() + timeout) {+ if !done {+ self.log("\(method) timed out after \(Int(timeout))s (dartReady=\(self.dartReady) sent=\(sent))")+ }+ finish(nil)+ }+ let send: () -> Void = {+ if done { return }+ guard let channel = self.channel else {+ finish(nil)+ return+ }+ sent = true+ channel.invokeMethod(method, arguments: args) { reply in+ finish(reply as? [String: Any])+ }+ }+ if self.dartReady {+ send()+ } else {+ self.log("\(method) waiting for Dart")+ self.waiting.append(send)+ }+ }+ }+}++/// What Siri knows about the library: the titles and names it should expect,+/// the books to suggest, and what was played (so Siri learns the listener's+/// books and offers them on the lock screen and in Spotlight).+enum SiriLibrary {+ static let catalogFileName = "siri_catalog.json"++ static func statusName(_ status: INSiriAuthorizationStatus) -> String {+ switch status {+ case .authorized: return "authorized"+ case .denied: return "denied"+ case .restricted: return "restricted"+ case .notDetermined: return "notDetermined"+ @unknown default: return "notDetermined"+ }+ }++ static func update(_ args: [String: Any]) {+ let titles = args["titles"] as? [String] ?? []+ let authors = args["authors"] as? [String] ?? []+ let shows = args["shows"] as? [String] ?? []+ let count = args["count"] as? Int ?? 0++ let context = INMediaUserContext()+ context.numberOfLibraryItems = count+ context.becomeCurrent()++ if INPreferences.siriAuthorizationStatus() == .authorized {+ let vocabulary = INVocabulary.shared()+ vocabulary.setVocabularyStrings(NSOrderedSet(array: titles), of: .mediaAudiobookTitle)+ vocabulary.setVocabularyStrings(NSOrderedSet(array: authors), of: .mediaAudiobookAuthorName)+ vocabulary.setVocabularyStrings(NSOrderedSet(array: shows), of: .mediaShowTitle)+ }++ if let upNext = args["upNext"] as? [[String: Any]] {+ let intents = upNext.compactMap(playIntent(for:))+ INUpcomingMediaManager.shared.setSuggestedMediaIntents(NSOrderedSet(array: intents))+ }++ if #available(iOS 17.0, *) {+ AbsorbSiriShortcuts.updateAppShortcutParameters()+ }+ SiriBridge.shared.log("library updated: \(count) items, \(titles.count) titles, \(authors.count) authors, \(shows.count) shows")+ }++ static func donate(_ args: [String: Any]) {+ guard let intent = playIntent(for: args) else { return }+ let response = INPlayMediaIntentResponse(code: .success, userActivity: nil)+ INInteraction(intent: intent, response: response).donate { error in+ if let error {+ SiriBridge.shared.log("donate failed: \(error.localizedDescription)")+ }+ }+ }++ static func playIntent(for item: [String: Any]) -> INPlayMediaIntent? {+ guard let mediaItem = mediaItem(item) else { return nil }+ return INPlayMediaIntent(+ mediaItems: [mediaItem],+ mediaContainer: nil,+ playShuffled: nil,+ playbackRepeatMode: .unknown,+ resumePlayback: true,+ playbackQueueLocation: .now,+ playbackSpeed: nil,+ mediaSearch: nil+ )+ }++ static func mediaItem(_ item: [String: Any]) -> INMediaItem? {+ guard let id = item["id"] as? String, !id.isEmpty else { return nil }+ let title = item["title"] as? String ?? ""+ let type: INMediaItemType+ switch item["kind"] as? String {+ case "podcast": type = .podcastShow+ case "episode": type = .podcastEpisode+ default: type = .audioBook+ }+ let author = (item["author"] as? String).flatMap { $0.isEmpty ? nil : $0 }+ return INMediaItem(+ identifier: id,+ title: title.isEmpty ? nil : title,+ type: type,+ artwork: artwork(item["coverPath"] as? String),+ artist: author+ )+ }++ private static func artwork(_ path: String?) -> INImage? {+ guard let path, FileManager.default.fileExists(atPath: path),+ let data = try? Data(contentsOf: URL(fileURLWithPath: path)),+ data.count < 3_000_000+ else { return nil }+ return INImage(imageData: data)+ }++ /// The catalog Dart last wrote to the app group, for when Dart can't+ /// answer in time and for the Shortcuts app's book picker.+ static func catalog() -> [[String: Any]] {+ guard let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: absorbAppGroup),+ let data = try? Data(contentsOf: dir.appendingPathComponent(catalogFileName)),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let entries = json["entries"] as? [[String: Any]]+ else { return [] }+ return entries+ }++ static func normalize(_ s: String) -> String {+ let folded = s.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)+ let words = folded.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { !$0.isEmpty }+ var joined = words.joined(separator: " ")+ for article in ["the ", "a ", "an "] where joined.hasPrefix(article) {+ joined.removeFirst(article.count)+ break+ }+ return joined+ }++ /// Plain title and author matching against the catalog, used only when Dart+ /// didn't answer in time.+ static func search(name: String?, artist: String?, type: String) -> [[String: Any]] {+ let query = normalize(name ?? artist ?? "")+ if query.isEmpty { return [] }+ let byAuthor = name == nil+ let hits = catalog().filter { entry in+ let kind = entry["kind"] as? String ?? "book"+ switch type {+ case "book": if kind != "book" && kind != "series" { return false }+ case "podcast", "episode": if kind != "podcast" && kind != "episode" { return false }+ default: break+ }+ let field = normalize(entry[byAuthor ? "author" : "title"] as? String ?? "")+ return !field.isEmpty && (field == query || field.contains(query))+ }+ let exact = hits.filter { normalize($0[byAuthor ? "author" : "title"] as? String ?? "") == query }+ return Array((exact.isEmpty ? hits : exact).prefix(4))+ }+}++/// "Play Project Hail Mary on Absorb", "Play the latest episode of The Daily+/// on Absorb", "Resume Absorb". Handled in the app process, so the audio can+/// start straight from here.+final class SiriMediaHandler: NSObject, INPlayMediaIntentHandling {+ static let shared = SiriMediaHandler()++ private func log(_ line: String) {+ SiriBridge.shared.log(line)+ }++ private static func typeName(_ type: INMediaItemType?) -> String {+ switch type {+ case .audioBook?: return "book"+ case .podcastShow?, .podcastPlaylist?, .podcastStation?: return "podcast"+ case .podcastEpisode?: return "episode"+ default: return "any"+ }+ }++ func resolveMediaItems(+ for intent: INPlayMediaIntent,+ with completion: @escaping ([INPlayMediaMediaItemResolutionResult]) -> Void+ ) {+ if let chosen = intent.mediaItems, let first = chosen.first {+ completion([INPlayMediaMediaItemResolutionResult.success(with: first)])+ return+ }+ let search = intent.mediaSearch+ var args: [String: Any] = ["type": Self.typeName(search?.mediaType)]+ if search?.reference != .currentlyPlaying {+ if let name = search?.mediaName, !name.isEmpty { args["name"] = name }+ if let artist = search?.artistName, !artist.isEmpty { args["artist"] = artist }+ }+ if search?.sortOrder == .newest { args["latest"] = true }+ log("resolve name=\(args["name"] ?? "-") artist=\(args["artist"] ?? "-") type=\(args["type"] ?? "-")")++ SiriBridge.shared.call("resolve", args, timeout: 8) { reply, _ in+ guard let reply else {+ completion(self.resolveNatively(args))+ return+ }+ let items = (reply["items"] as? [[String: Any]] ?? []).compactMap(SiriLibrary.mediaItem)+ let status = reply["status"] as? String ?? "none"+ self.log("resolve -> \(status) \(items.compactMap { $0.title }.joined(separator: " | "))")+ switch status {+ case "ok" where !items.isEmpty:+ completion([INPlayMediaMediaItemResolutionResult.success(with: items[0])])+ case "ambiguous" where items.count > 1:+ completion([INPlayMediaMediaItemResolutionResult.disambiguation(with: items)])+ case "ambiguous" where items.count == 1:+ completion([INPlayMediaMediaItemResolutionResult.success(with: items[0])])+ case "signedOut":+ completion([INPlayMediaMediaItemResolutionResult.unsupported(forReason: .loginRequired)])+ default:+ completion([INPlayMediaMediaItemResolutionResult.unsupported()])+ }+ }+ }++ /// Dart didn't answer in time: resume the stashed book, or match the+ /// catalog from the last run by plain text.+ private func resolveNatively(_ args: [String: Any]) -> [INPlayMediaMediaItemResolutionResult] {+ let name = args["name"] as? String+ let artist = args["artist"] as? String+ if name == nil && artist == nil {+ let defaults = UserDefaults(suiteName: absorbAppGroup)+ guard defaults?.string(forKey: "np_item_id") != nil else {+ return [INPlayMediaMediaItemResolutionResult.unsupported()]+ }+ let item = INMediaItem(+ identifier: "resume",+ title: defaults?.string(forKey: "np_title"),+ type: .audioBook,+ artwork: nil,+ artist: defaults?.string(forKey: "np_author")+ )+ return [INPlayMediaMediaItemResolutionResult.success(with: item)]+ }+ let hits = SiriLibrary.search(name: name, artist: artist, type: args["type"] as? String ?? "any")+ .compactMap(SiriLibrary.mediaItem)+ log("resolve natively -> \(hits.count) match(es)")+ if hits.count == 1 { return [INPlayMediaMediaItemResolutionResult.success(with: hits[0])] }+ if hits.count > 1 { return [INPlayMediaMediaItemResolutionResult.disambiguation(with: hits)] }+ return [INPlayMediaMediaItemResolutionResult.unsupported()]+ }++ func resolvePlaybackSpeed(+ for intent: INPlayMediaIntent,+ with completion: @escaping (INPlayMediaPlaybackSpeedResolutionResult) -> Void+ ) {+ guard let speed = intent.playbackSpeed else {+ completion(INPlayMediaPlaybackSpeedResolutionResult.notRequired())+ return+ }+ completion(INPlayMediaPlaybackSpeedResolutionResult.success(with: min(max(speed, 0.5), 5.0)))+ }++ func handle(intent: INPlayMediaIntent, completion: @escaping (INPlayMediaIntentResponse) -> Void) {+ let id = intent.mediaItems?.first?.identifier ?? "resume"+ var args: [String: Any] = ["id": id]+ if let speed = intent.playbackSpeed { args["speed"] = speed }+ if intent.mediaSearch?.sortOrder == .newest { args["latest"] = true }+ log("handle \(id)")++ // Siri only grants the background audio start for a short while; hold+ // the session open now so the play that follows isn't refused.+ absorbClaimOwnershipIfOwnerDead()+ activateAbsorbAudioSession()++ if !SiriBridge.shared.dartReady && (id == "resume" || Self.isStashed(id)) {+ log("handle \(id): Dart is still starting, resuming from the native player")+ AbsorbPlayerCore.shared.play()+ completion(INPlayMediaIntentResponse(code: .success, userActivity: nil))+ return+ }++ SiriBridge.shared.call("play", args, timeout: 12) { reply, sent in+ if let reply {+ let ok = reply["ok"] as? Bool ?? false+ self.log("handle \(id) -> ok=\(ok)")+ completion(INPlayMediaIntentResponse(code: ok ? .success : .failure, userActivity: nil))+ } else if sent {+ // Under way but slow (a stream still buffering): let Siri finish.+ completion(INPlayMediaIntentResponse(code: .success, userActivity: nil))+ } else if id == "resume" {+ AbsorbPlayerCore.shared.play()+ completion(INPlayMediaIntentResponse(code: .success, userActivity: nil))+ } else {+ completion(INPlayMediaIntentResponse(code: .failureRequiringAppLaunch, userActivity: nil))+ }+ }+ }++ /// The book the native player can start with no help from Dart.+ private static func isStashed(_ id: String) -> Bool {+ let parts = id.split(separator: "|", omittingEmptySubsequences: false).map(String.init)+ guard parts.count >= 2, parts[0] == "book" || parts[0] == "episode" else { return false }+ let defaults = UserDefaults(suiteName: absorbAppGroup)+ guard defaults?.string(forKey: "np_item_id") == parts[1] else { return false }+ let stashedEpisode = defaults?.string(forKey: "np_episode_id") ?? ""+ let episode = parts.count > 2 ? parts[2] : ""+ return stashedEpisode == episode+ }+}diff --git a/ios/Runner/SiriShortcuts.swift b/ios/Runner/SiriShortcuts.swiftnew file mode 100644index 00000000..8d0cb1bc--- /dev/null+++ b/ios/Runner/SiriShortcuts.swift@@ -0,0 +1,481 @@+import AbsorbPlayerCore+import AppIntents+import Foundation++@available(iOS 16.0, *)+enum SiriIntentError: Error, CustomLocalizedStringResourceConvertible {+ case nothingPlaying+ case nothingToResume+ case noTimer+ case notAnswering+ case couldNotPlay++ var localizedStringResource: LocalizedStringResource {+ switch self {+ case .nothingPlaying: return "Nothing is playing in Absorb."+ case .nothingToResume: return "There's nothing to resume in Absorb yet."+ case .noTimer: return "There's no sleep timer running."+ case .notAnswering: return "Absorb didn't answer in time. Try again in a moment."+ case .couldNotPlay: return "Absorb couldn't start that book."+ }+ }+}++/// Runs a player action through Dart, or through the native player while Dart+/// is still starting (only resume, pause and the skips work there).+@available(iOS 16.0, *)+enum SiriControl {+ static func run(+ _ action: String,+ _ extra: [String: Any] = [:],+ native: (() -> Void)? = nil+ ) async -> [String: Any]? {+ if !SiriBridge.shared.dartReady, let native {+ SiriBridge.shared.log("\(action): Dart is still starting, using the native player")+ native()+ return ["ok": true]+ }+ var args = extra+ args["action"] = action+ let reply: [String: Any]? = await withCheckedContinuation { continuation in+ SiriBridge.shared.call("control", args, timeout: 10) { reply, _ in+ continuation.resume(returning: reply)+ }+ }+ return reply+ }++ static func requireOk(_ reply: [String: Any]?, orElse error: SiriIntentError) throws -> [String: Any] {+ guard let reply else { throw SiriIntentError.notAnswering }+ guard reply["ok"] as? Bool == true else { throw error }+ return reply+ }++ static var skipBackSeconds: Int {+ let s = UserDefaults(suiteName: absorbAppGroup)?.integer(forKey: "widget_skip_back") ?? 0+ return s > 0 ? s : 10+ }++ static var skipForwardSeconds: Int {+ let s = UserDefaults(suiteName: absorbAppGroup)?.integer(forKey: "widget_skip_forward") ?? 0+ return s > 0 ? s : 30+ }++ static func spokenDuration(_ seconds: Int) -> String {+ let hours = seconds / 3600+ let minutes = (seconds % 3600) / 60+ func unit(_ n: Int, _ word: String) -> String { "\(n) \(word)\(n == 1 ? "" : "s")" }+ if hours > 0 && minutes > 0 { return "\(unit(hours, "hour")) and \(unit(minutes, "minute"))" }+ if hours > 0 { return unit(hours, "hour") }+ return unit(max(minutes, 1), "minute")+ }+}++@available(iOS 16.0, *)+struct ResumeListeningIntent: AudioPlaybackIntent {+ static let title: LocalizedStringResource = "Resume Listening"+ static let description = IntentDescription("Picks up the book or episode you were last listening to.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult {+ absorbClaimOwnershipIfOwnerDead()+ activateAbsorbAudioSession()+ let reply = await SiriControl.run("resume") { AbsorbPlayerCore.shared.play() }+ _ = try SiriControl.requireOk(reply, orElse: .nothingToResume)+ return .result()+ }+}++@available(iOS 16.0, *)+struct PauseListeningIntent: AudioPlaybackIntent {+ static let title: LocalizedStringResource = "Pause Listening"+ static let description = IntentDescription("Pauses what Absorb is playing.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult {+ let reply = await SiriControl.run("pause") { AbsorbPlayerCore.shared.pause() }+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ return .result()+ }+}++@available(iOS 16.0, *)+struct SkipBackIntent: AudioPlaybackIntent {+ static let title: LocalizedStringResource = "Skip Back"+ static let description = IntentDescription("Skips back by your skip amount.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult {+ let reply = await SiriControl.run("skipBack") {+ AbsorbPlayerCore.shared.skipBackward(seconds: SiriControl.skipBackSeconds)+ }+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ return .result()+ }+}++@available(iOS 16.0, *)+struct SkipForwardIntent: AudioPlaybackIntent {+ static let title: LocalizedStringResource = "Skip Forward"+ static let description = IntentDescription("Skips forward by your skip amount.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult {+ let reply = await SiriControl.run("skipForward") {+ AbsorbPlayerCore.shared.skipForward(seconds: SiriControl.skipForwardSeconds)+ }+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ return .result()+ }+}++@available(iOS 16.0, *)+struct NextChapterIntent: AudioPlaybackIntent {+ static let title: LocalizedStringResource = "Next Chapter"+ static let description = IntentDescription("Jumps to the next chapter.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult {+ let reply = await SiriControl.run("nextChapter")+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ return .result()+ }+}++@available(iOS 16.0, *)+struct PreviousChapterIntent: AudioPlaybackIntent {+ static let title: LocalizedStringResource = "Previous Chapter"+ static let description = IntentDescription("Jumps back to the start of the chapter, or the one before.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult {+ let reply = await SiriControl.run("previousChapter")+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ return .result()+ }+}++@available(iOS 16.0, *)+struct SetSleepTimerIntent: AppIntent {+ static let title: LocalizedStringResource = "Set Sleep Timer"+ static let description = IntentDescription("Stops playback after the time you choose.")+ static let openAppWhenRun = false++ @Parameter(+ title: "Duration",+ description: "How long to keep playing",+ defaultValue: 30,+ defaultUnit: .minutes,+ supportsNegativeNumbers: false+ )+ var duration: Measurement<UnitDuration>++ static var parameterSummary: some ParameterSummary {+ Summary("Set a sleep timer for \(\.$duration)")+ }++ init() {}++ func perform() async throws -> some IntentResult & ProvidesDialog {+ let minutes = Int((duration.converted(to: .minutes).value).rounded())+ guard minutes > 0 else { throw SiriIntentError.nothingPlaying }+ let reply = await SiriControl.run("sleepMinutes", ["minutes": minutes])+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ let message = "Sleep timer set for \(SiriControl.spokenDuration(minutes * 60))."+ return .result(dialog: IntentDialog(stringLiteral: message))+ }+}++@available(iOS 16.0, *)+struct SleepAtChapterEndIntent: AppIntent {+ static let title: LocalizedStringResource = "Sleep at End of Chapter"+ static let description = IntentDescription("Stops playback when the current chapter ends.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult & ProvidesDialog {+ let reply = await SiriControl.run("sleepChapterEnd")+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ return .result(dialog: "Absorb will stop at the end of this chapter.")+ }+}++@available(iOS 16.0, *)+struct CancelSleepTimerIntent: AppIntent {+ static let title: LocalizedStringResource = "Cancel Sleep Timer"+ static let description = IntentDescription("Turns off the sleep timer.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult & ProvidesDialog {+ let reply = await SiriControl.run("cancelSleep")+ _ = try SiriControl.requireOk(reply, orElse: .noTimer)+ return .result(dialog: "Sleep timer off.")+ }+}++@available(iOS 16.0, *)+struct AddBookmarkIntent: AppIntent {+ static let title: LocalizedStringResource = "Add Bookmark"+ static let description = IntentDescription("Bookmarks where you are in the book.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult & ProvidesDialog {+ let reply = await SiriControl.run("bookmark")+ _ = try SiriControl.requireOk(reply, orElse: .nothingPlaying)+ return .result(dialog: "Bookmarked.")+ }+}++@available(iOS 16.0, *)+struct WhatsPlayingIntent: AppIntent {+ static let title: LocalizedStringResource = "What's Playing"+ static let description = IntentDescription("Tells you the book, chapter and time left.")+ static let openAppWhenRun = false++ init() {}++ func perform() async throws -> some IntentResult & ProvidesDialog {+ var title = "", author = "", chapter = ""+ var position = 0, duration = 0+ if SiriBridge.shared.dartReady,+ let reply = await SiriControl.run("status"),+ reply["hasBook"] as? Bool == true {+ title = reply["title"] as? String ?? ""+ author = reply["author"] as? String ?? ""+ chapter = reply["chapter"] as? String ?? ""+ position = reply["position"] as? Int ?? 0+ duration = reply["duration"] as? Int ?? 0+ } else {+ let defaults = UserDefaults(suiteName: absorbAppGroup)+ title = defaults?.string(forKey: "np_title") ?? ""+ author = defaults?.string(forKey: "np_author") ?? ""+ position = Int(defaults?.double(forKey: "np_position_s") ?? 0)+ duration = Int(defaults?.double(forKey: "np_total_s") ?? 0)+ }+ guard !title.isEmpty else { throw SiriIntentError.nothingPlaying }+ var message = author.isEmpty ? "You're listening to \(title)." : "You're listening to \(title) by \(author)."+ if !chapter.isEmpty && chapter != title { message += " \(chapter)." }+ if duration > position && duration > 0 {+ message += " \(SiriControl.spokenDuration(duration - position)) left."+ }+ return .result(dialog: IntentDialog(stringLiteral: message))+ }+}++/// A book or show from the list Dart keeps for Siri, for the Shortcuts app.+@available(iOS 16.0, *)+struct AbsorbBookEntity: AppEntity {+ static var typeDisplayRepresentation: TypeDisplayRepresentation = "Book"+ static var defaultQuery = AbsorbBookQuery()++ var id: String+ var title: String+ var author: String++ var displayRepresentation: DisplayRepresentation {+ author.isEmpty+ ? DisplayRepresentation(title: "\(title)")+ : DisplayRepresentation(title: "\(title)", subtitle: "\(author)")+ }++ init(id: String, title: String, author: String) {+ self.id = id+ self.title = title+ self.author = author+ }++ init?(_ entry: [String: Any]) {+ guard let id = entry["id"] as? String, let title = entry["title"] as? String, !title.isEmpty else { return nil }+ self.init(id: id, title: title, author: entry["author"] as? String ?? "")+ }+}++@available(iOS 16.0, *)+struct AbsorbBookQuery: EntityStringQuery {+ init() {}++ private static func playable() -> [AbsorbBookEntity] {+ SiriLibrary.catalog().compactMap { entry in+ (entry["kind"] as? String) == "episode" ? nil : AbsorbBookEntity(entry)+ }+ }++ func entities(for identifiers: [AbsorbBookEntity.ID]) async throws -> [AbsorbBookEntity] {+ let wanted = Set(identifiers)+ return Self.playable().filter { wanted.contains($0.id) }+ }++ func entities(matching string: String) async throws -> [AbsorbBookEntity] {+ let query = SiriLibrary.normalize(string)+ guard !query.isEmpty else { return [] }+ return Self.playable().filter {+ SiriLibrary.normalize($0.title).contains(query) || SiriLibrary.normalize($0.author).contains(query)+ }+ }++ func suggestedEntities() async throws -> [AbsorbBookEntity] {+ Array(Self.playable().prefix(50))+ }+}++@available(iOS 16.0, *)+struct PlayBookIntent: AudioPlaybackIntent {+ static let title: LocalizedStringResource = "Play Book"+ static let description = IntentDescription("Plays a book, series or podcast from your library.")+ static let openAppWhenRun = false++ @Parameter(title: "Book")+ var book: AbsorbBookEntity++ static var parameterSummary: some ParameterSummary {+ Summary("Play \(\.$book)")+ }++ init() {}++ init(book: AbsorbBookEntity) {+ self.book = book+ }++ func perform() async throws -> some IntentResult {+ absorbClaimOwnershipIfOwnerDead()+ activateAbsorbAudioSession()+ let id = book.id+ let reply: ([String: Any]?, Bool) = await withCheckedContinuation { continuation in+ SiriBridge.shared.call("play", ["id": id], timeout: 12) { reply, sent in+ continuation.resume(returning: (reply, sent))+ }+ }+ if let result = reply.0 {+ guard result["ok"] as? Bool == true else { throw SiriIntentError.couldNotPlay }+ } else if !reply.1 {+ throw SiriIntentError.notAnswering+ }+ return .result()+ }+}++@available(iOS 17.0, *)+struct AbsorbSiriShortcuts: AppShortcutsProvider {+ static var appShortcuts: [AppShortcut] {+ AppShortcut(+ intent: ResumeListeningIntent(),+ phrases: [+ "Resume \(.applicationName)",+ "Continue \(.applicationName)",+ "Resume listening in \(.applicationName)",+ "Continue listening in \(.applicationName)",+ "Play my audiobook in \(.applicationName)",+ "Play my book in \(.applicationName)",+ "Continue my book in \(.applicationName)",+ "Resume my podcast in \(.applicationName)",+ ],+ shortTitle: "Resume",+ systemImageName: "play.fill"+ )+ AppShortcut(+ intent: PauseListeningIntent(),+ phrases: [+ "Pause \(.applicationName)",+ "Pause listening in \(.applicationName)",+ "Stop \(.applicationName)",+ ],+ shortTitle: "Pause",+ systemImageName: "pause.fill"+ )+ AppShortcut(+ intent: SkipBackIntent(),+ phrases: [+ "Skip back in \(.applicationName)",+ "Go back in \(.applicationName)",+ "Rewind \(.applicationName)",+ ],+ shortTitle: "Skip Back",+ systemImageName: "gobackward"+ )+ AppShortcut(+ intent: SkipForwardIntent(),+ phrases: [+ "Skip forward in \(.applicationName)",+ "Skip ahead in \(.applicationName)",+ "Fast forward \(.applicationName)",+ ],+ shortTitle: "Skip Forward",+ systemImageName: "goforward"+ )+ AppShortcut(+ intent: NextChapterIntent(),+ phrases: [+ "Next chapter in \(.applicationName)",+ "Skip to the next chapter in \(.applicationName)",+ ],+ shortTitle: "Next Chapter",+ systemImageName: "forward.end.fill"+ )+ AppShortcut(+ intent: PreviousChapterIntent(),+ phrases: [+ "Previous chapter in \(.applicationName)",+ "Go back a chapter in \(.applicationName)",+ ],+ shortTitle: "Previous Chapter",+ systemImageName: "backward.end.fill"+ )+ AppShortcut(+ intent: SetSleepTimerIntent(),+ phrases: [+ "Set a sleep timer in \(.applicationName)",+ "Set sleep timer in \(.applicationName)",+ "Start a sleep timer in \(.applicationName)",+ ],+ shortTitle: "Sleep Timer",+ systemImageName: "moon.zzz.fill"+ )+ AppShortcut(+ intent: CancelSleepTimerIntent(),+ phrases: [+ "Cancel the sleep timer in \(.applicationName)",+ "Turn off the sleep timer in \(.applicationName)",+ ],+ shortTitle: "Cancel Sleep Timer",+ systemImageName: "moon"+ )+ AppShortcut(+ intent: AddBookmarkIntent(),+ phrases: [+ "Add a bookmark in \(.applicationName)",+ "Bookmark this in \(.applicationName)",+ "Bookmark \(.applicationName)",+ ],+ shortTitle: "Add Bookmark",+ systemImageName: "bookmark.fill"+ )+ AppShortcut(+ intent: WhatsPlayingIntent(),+ phrases: [+ "What's playing in \(.applicationName)",+ "What am I listening to in \(.applicationName)",+ "How much is left in \(.applicationName)",+ ],+ shortTitle: "What's Playing",+ systemImageName: "info.circle"+ )+ }+}diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 3fc6977f..0a044d16 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -4923,6 +4923,16 @@"carConnectAutoplayOffSubtitle": "Playback waits for you to press play","sectionCar": "Android Auto","sectionCarIos": "CarPlay",+ "sectionSiri": "Siri",+ "siriUseWithSiri": "Use with Siri",+ "siriStatusOn": "On. Siri can find and play your books and podcasts by name.",+ "siriStatusAsk": "Let Siri find and play your books and podcasts by name.",+ "siriStatusOff": "Siri is turned off for Absorb. Turn it on in iOS Settings.",+ "siriAllow": "Allow",+ "siriOpenSettings": "Open Settings",+ "siriThingsToSay": "Things to say",+ "siriExamples": "\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"",+ "siriShortcutsNote": "Resume, pause, skips, chapters, the sleep timer, bookmarks and what's playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.","carBookOrder": "Book order in the car","carBookOrderReverse": "Reverse book order","carBookOrderReverseSubtitle": "Z to A, or oldest added first",@@ -5561,6 +5571,10 @@"readerPageLayout": "Page layout","readerPinTopBar": "Keep the title and progress bar on screen","readerPinTopBarHint": "Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.",+ "readerTopBarProgress": "Top bar progress",+ "readerTopBarProgressBook": "Book",+ "readerTopBarProgressChapter": "Chapter",+ "readerTopBarProgressBoth": "Both","readerScrollMode": "Scroll mode","readerScrollModeHint": "Scroll down through the book instead of turning pages. Applies to every book.","readerKeepAwake": "Keep the screen on",@@ -5654,6 +5668,14 @@}},"readerNoHighlights": "No highlights yet",+ "readerHistory": "History",+ "sessionReading": "Reading",+ "readerHistoryEmpty": "Pages you leave are listed here, so you can always get back to them.",+ "readerHistoryClosed": "Closed the book",+ "readerHistoryBeforeJump": "Before a jump",+ "readerHistoryBeforeSync": "Before matching the audio",+ "readerLogReading": "Count reading time in stats",+ "readerLogReadingHint": "Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.","readerNoBookmarks": "No bookmarks yet","readerBookmarkDefault": "Bookmark","readerNoteTitle": "Note",@@ -5865,9 +5887,36 @@"lyricsTurnOn": "Turn on","readAlong": "Read along","readAlongNeedsPlaying": "Play this book's audiobook first",+ "narrationListen": "Listen",+ "narrationPlayFromHere": "Play from here",+ "narrationPreparing": "Getting the narration ready",+ "narrationNone": "This ebook has no narration to play",+ "narrationDownloadTitle": "Download to listen",+ "narrationDownloadBody": "This book is an EPUB3 that reads itself aloud. Audiobookshelf can't stream its narration, so the audio needs to be downloaded before it plays.",+ "narrationDownloadStarted": "Downloading the narration. Tap Absorb when it finishes.",+ "narrationUpNextTitle": "Download what's up next",+ "narrationUpNextBody": "{title} is next in your queue. It's an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.",+ "@narrationUpNextBody": {+ "placeholders": {+ "title": {"type": "String"}+ }+ },+ "narrationQueueStopped": "Stopped before {title}. Download it to keep going.",+ "@narrationQueueStopped": {+ "placeholders": {+ "title": {"type": "String"}+ }+ },"transcriptionNeedsDownload": "This needs the audio on your phone. Download it now?","transcriptionDownloadStarted": "Downloading. Turn this on again when it finishes","readAlongFollow": "Read along follows",+ "syncReadingListening": "Keep reading and listening in sync",+ "syncReadingListeningHint": "For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.",+ "syncEbookMoved": "Ebook moved to where you stopped listening",+ "syncAudioMoved": "Audiobook moved to where you stopped reading",+ "syncAudioOffer": "Tap to jump to where you stopped reading",+ "syncFindingAudio": "Finding your page in the audiobook",+ "syncFindingEbook": "Finding your spot in the ebook","readAlongFollowHint": "Word timing is worked out between the transcript's timestamps, so it can drift slightly inside a sentence.","readAlongFollowWord": "Word","readAlongFollowSentence": "Sentence",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 1ab01d2b..087cc21f 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -14469,6 +14469,66 @@ abstract class AppLocalizations {/// **'CarPlay'**String get sectionCarIos;+ /// No description provided for @sectionSiri.+ ///+ /// In en, this message translates to:+ /// **'Siri'**+ String get sectionSiri;++ /// No description provided for @siriUseWithSiri.+ ///+ /// In en, this message translates to:+ /// **'Use with Siri'**+ String get siriUseWithSiri;++ /// No description provided for @siriStatusOn.+ ///+ /// In en, this message translates to:+ /// **'On. Siri can find and play your books and podcasts by name.'**+ String get siriStatusOn;++ /// No description provided for @siriStatusAsk.+ ///+ /// In en, this message translates to:+ /// **'Let Siri find and play your books and podcasts by name.'**+ String get siriStatusAsk;++ /// No description provided for @siriStatusOff.+ ///+ /// In en, this message translates to:+ /// **'Siri is turned off for Absorb. Turn it on in iOS Settings.'**+ String get siriStatusOff;++ /// No description provided for @siriAllow.+ ///+ /// In en, this message translates to:+ /// **'Allow'**+ String get siriAllow;++ /// No description provided for @siriOpenSettings.+ ///+ /// In en, this message translates to:+ /// **'Open Settings'**+ String get siriOpenSettings;++ /// No description provided for @siriThingsToSay.+ ///+ /// In en, this message translates to:+ /// **'Things to say'**+ String get siriThingsToSay;++ /// No description provided for @siriExamples.+ ///+ /// In en, this message translates to:+ /// **'\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"'**+ String get siriExamples;++ /// No description provided for @siriShortcutsNote.+ ///+ /// In en, this message translates to:+ /// **'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.'**+ String get siriShortcutsNote;+/// No description provided for @carBookOrder.////// In en, this message translates to:@@ -16977,6 +17037,30 @@ abstract class AppLocalizations {/// **'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.'**String get readerPinTopBarHint;+ /// No description provided for @readerTopBarProgress.+ ///+ /// In en, this message translates to:+ /// **'Top bar progress'**+ String get readerTopBarProgress;++ /// No description provided for @readerTopBarProgressBook.+ ///+ /// In en, this message translates to:+ /// **'Book'**+ String get readerTopBarProgressBook;++ /// No description provided for @readerTopBarProgressChapter.+ ///+ /// In en, this message translates to:+ /// **'Chapter'**+ String get readerTopBarProgressChapter;++ /// No description provided for @readerTopBarProgressBoth.+ ///+ /// In en, this message translates to:+ /// **'Both'**+ String get readerTopBarProgressBoth;+/// No description provided for @readerScrollMode.////// In en, this message translates to:@@ -17283,6 +17367,54 @@ abstract class AppLocalizations {/// **'No highlights yet'**String get readerNoHighlights;+ /// No description provided for @readerHistory.+ ///+ /// In en, this message translates to:+ /// **'History'**+ String get readerHistory;++ /// No description provided for @sessionReading.+ ///+ /// In en, this message translates to:+ /// **'Reading'**+ String get sessionReading;++ /// No description provided for @readerHistoryEmpty.+ ///+ /// In en, this message translates to:+ /// **'Pages you leave are listed here, so you can always get back to them.'**+ String get readerHistoryEmpty;++ /// No description provided for @readerHistoryClosed.+ ///+ /// In en, this message translates to:+ /// **'Closed the book'**+ String get readerHistoryClosed;++ /// No description provided for @readerHistoryBeforeJump.+ ///+ /// In en, this message translates to:+ /// **'Before a jump'**+ String get readerHistoryBeforeJump;++ /// No description provided for @readerHistoryBeforeSync.+ ///+ /// In en, this message translates to:+ /// **'Before matching the audio'**+ String get readerHistoryBeforeSync;++ /// No description provided for @readerLogReading.+ ///+ /// In en, this message translates to:+ /// **'Count reading time in stats'**+ String get readerLogReading;++ /// No description provided for @readerLogReadingHint.+ ///+ /// In en, this message translates to:+ /// **'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.'**+ String get readerLogReadingHint;+/// No description provided for @readerNoBookmarks.////// In en, this message translates to:@@ -18249,6 +18381,66 @@ abstract class AppLocalizations {/// **'Play this book\'s audiobook first'**String get readAlongNeedsPlaying;+ /// No description provided for @narrationListen.+ ///+ /// In en, this message translates to:+ /// **'Listen'**+ String get narrationListen;++ /// No description provided for @narrationPlayFromHere.+ ///+ /// In en, this message translates to:+ /// **'Play from here'**+ String get narrationPlayFromHere;++ /// No description provided for @narrationPreparing.+ ///+ /// In en, this message translates to:+ /// **'Getting the narration ready'**+ String get narrationPreparing;++ /// No description provided for @narrationNone.+ ///+ /// In en, this message translates to:+ /// **'This ebook has no narration to play'**+ String get narrationNone;++ /// No description provided for @narrationDownloadTitle.+ ///+ /// In en, this message translates to:+ /// **'Download to listen'**+ String get narrationDownloadTitle;++ /// No description provided for @narrationDownloadBody.+ ///+ /// In en, this message translates to:+ /// **'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.'**+ String get narrationDownloadBody;++ /// No description provided for @narrationDownloadStarted.+ ///+ /// In en, this message translates to:+ /// **'Downloading the narration. Tap Absorb when it finishes.'**+ String get narrationDownloadStarted;++ /// No description provided for @narrationUpNextTitle.+ ///+ /// In en, this message translates to:+ /// **'Download what\'s up next'**+ String get narrationUpNextTitle;++ /// No description provided for @narrationUpNextBody.+ ///+ /// In en, this message translates to:+ /// **'{title} is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.'**+ String narrationUpNextBody(String title);++ /// No description provided for @narrationQueueStopped.+ ///+ /// In en, this message translates to:+ /// **'Stopped before {title}. Download it to keep going.'**+ String narrationQueueStopped(String title);+/// No description provided for @transcriptionNeedsDownload.////// In en, this message translates to:@@ -18267,6 +18459,48 @@ abstract class AppLocalizations {/// **'Read along follows'**String get readAlongFollow;+ /// No description provided for @syncReadingListening.+ ///+ /// In en, this message translates to:+ /// **'Keep reading and listening in sync'**+ String get syncReadingListening;++ /// No description provided for @syncReadingListeningHint.+ ///+ /// In en, this message translates to:+ /// **'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.'**+ String get syncReadingListeningHint;++ /// No description provided for @syncEbookMoved.+ ///+ /// In en, this message translates to:+ /// **'Ebook moved to where you stopped listening'**+ String get syncEbookMoved;++ /// No description provided for @syncAudioMoved.+ ///+ /// In en, this message translates to:+ /// **'Audiobook moved to where you stopped reading'**+ String get syncAudioMoved;++ /// No description provided for @syncAudioOffer.+ ///+ /// In en, this message translates to:+ /// **'Tap to jump to where you stopped reading'**+ String get syncAudioOffer;++ /// No description provided for @syncFindingAudio.+ ///+ /// In en, this message translates to:+ /// **'Finding your page in the audiobook'**+ String get syncFindingAudio;++ /// No description provided for @syncFindingEbook.+ ///+ /// In en, this message translates to:+ /// **'Finding your spot in the ebook'**+ String get syncFindingEbook;+/// No description provided for @readAlongFollowHint.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex c663dc3a..4f72fa67 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -8558,6 +8558,41 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9973,6 +10008,18 @@ class AppLocalizationsDe extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10168,6 +10215,32 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get readerNoHighlights => 'Noch keine Hervorhebungen';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'Noch keine Lesezeichen';@@ -10727,6 +10800,42 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10738,6 +10847,28 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 7d2db394..597ea060 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -8459,6 +8459,41 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9856,6 +9891,18 @@ class AppLocalizationsEl extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10050,6 +10097,32 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10606,6 +10679,42 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10617,6 +10726,28 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex d18a83ec..cd5efd08 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -8459,6 +8459,41 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9856,6 +9891,18 @@ class AppLocalizationsEn extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10050,6 +10097,32 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10606,6 +10679,42 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10617,6 +10726,28 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex 79c38d2d..61afba72 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -8461,6 +8461,41 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9858,6 +9893,18 @@ class AppLocalizationsEs extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10052,6 +10099,32 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10608,6 +10681,42 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10619,6 +10728,28 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 44c57ae8..c81863e9 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -8510,6 +8510,41 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9907,6 +9942,18 @@ class AppLocalizationsFr extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10102,6 +10149,32 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'Aucun signet pour l\'instant';@@ -10659,6 +10732,42 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10670,6 +10779,28 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 2188674d..831a8119 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -8459,6 +8459,41 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9856,6 +9891,18 @@ class AppLocalizationsIt extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10050,6 +10097,32 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10606,6 +10679,42 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10617,6 +10726,28 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 124e915b..5ad37acb 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -8459,6 +8459,41 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9856,6 +9891,18 @@ class AppLocalizationsJa extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10050,6 +10097,32 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10606,6 +10679,42 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10617,6 +10726,28 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex 24f8f4e7..bb3b2435 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -8459,6 +8459,41 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9856,6 +9891,18 @@ class AppLocalizationsNo extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10050,6 +10097,32 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10606,6 +10679,42 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10617,6 +10726,28 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 714b92cf..d9d801fe 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -8459,6 +8459,41 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9856,6 +9891,18 @@ class AppLocalizationsPt extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10050,6 +10097,32 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10606,6 +10679,42 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10617,6 +10726,28 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 3d884768..8c76b884 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -8459,6 +8459,41 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9856,6 +9891,18 @@ class AppLocalizationsRo extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10050,6 +10097,32 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10606,6 +10679,42 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10617,6 +10726,28 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex 7a548d58..070711d3 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -8463,6 +8463,41 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn =>+ 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk =>+ 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff =>+ 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples =>+ '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote =>+ 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -9861,6 +9896,18 @@ class AppLocalizationsRu extends AppLocalizations {String get readerPinTopBarHint =>'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';+@overrideString get readerScrollMode => 'Scroll mode';@@ -10055,6 +10102,32 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty =>+ 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint =>+ 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -10611,6 +10684,42 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get readAlongNeedsPlaying => 'Play this book\'s audiobook first';+ @override+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody =>+ 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted =>+ 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }+@overrideString get transcriptionNeedsDownload =>'This needs the audio on your phone. Download it now?';@@ -10622,6 +10731,28 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get readAlongFollow => 'Read along follows';+ @override+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint =>+ 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';+@overrideString get readAlongFollowHint =>'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 5a8555f7..0b410649 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -27,26 +27,22 @@ class AppLocalizationsZh extends AppLocalizations {String get listsNone => 'No collections or playlists';@override- String get listsNoneHint =>- 'Collections and playlists are made on your Audiobookshelf server, and show up here.';+ String get listsNoneHint => 'Collections and playlists are made on your Audiobookshelf server, and show up here.';@overrideString get listsLoadFailed => 'Couldn\'t load your lists';@override- String get listsLoadFailedHint =>- 'Absorb couldn\'t reach your server for collections and playlists.';+ String get listsLoadFailedHint => 'Absorb couldn\'t reach your server for collections and playlists.';@overrideString get listsNoneBookOrbit => 'No collections or Smart Scopes';@override- String get listsNoneHintBookOrbit =>- 'Collections and Smart Scopes are made on your BookOrbit server, and show up here.';+ String get listsNoneHintBookOrbit => 'Collections and Smart Scopes are made on your BookOrbit server, and show up here.';@override- String get listsLoadFailedHintBookOrbit =>- 'Absorb couldn\'t reach your server for collections and Smart Scopes.';+ String get listsLoadFailedHintBookOrbit => 'Absorb couldn\'t reach your server for collections and Smart Scopes.';@overrideString get cancel => '取消';@@ -189,8 +185,7 @@ class AppLocalizationsZh extends AppLocalizations {String get loginCustomHttpHeaders => '自定义 HTTP 请求头';@override- String get loginCustomHeadersDescription =>- '用于需要额外请求头的 Cloudflare 隧道或反向代理。请在输入服务器 URL 之前添加请求头。';+ String get loginCustomHeadersDescription => '用于需要额外请求头的 Cloudflare 隧道或反向代理。请在输入服务器 URL 之前添加请求头。';@overrideString get loginHeaderName => '请求头名称';@@ -211,8 +206,7 @@ class AppLocalizationsZh extends AppLocalizations {String get loginApiKey => 'API 密钥';@override- String get loginApiKeyDescription =>- '使用管理员生成的 API 密钥代替用户名/密码。当账号的令牌刷新失败时很有用。';+ String get loginApiKeyDescription => '使用管理员生成的 API 密钥代替用户名/密码。当账号的令牌刷新失败时很有用。';@overrideString get loginWaitingForSso => '正在等待单点登录(SSO)...';@@ -260,12 +254,10 @@ class AppLocalizationsZh extends AppLocalizations {String get adminSetupFileServerUrl => 'Server URL the new user will use';@override- String get adminSetupFileNoteWithHeaders =>- 'A dedicated API key and your custom headers will be included so they can reach the server. Treat the link like a password.';+ String get adminSetupFileNoteWithHeaders => 'A dedicated API key and your custom headers will be included so they can reach the server. Treat the link like a password.';@override- String get adminSetupFileNote =>- 'A dedicated API key will be included. Treat the link like a password.';+ String get adminSetupFileNote => 'A dedicated API key will be included. Treat the link like a password.';@overrideString get adminSetupFileCreate => 'Create link';@@ -274,8 +266,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminSetupFileSaveTitle => 'Save setup file';@override- String get adminSetupFileKeyError =>- 'Could not create an API key for this user';+ String get adminSetupFileKeyError => 'Could not create an API key for this user';@overrideString adminSetupFileSaved(String username) {@@ -313,8 +304,7 @@ class AppLocalizationsZh extends AppLocalizations {String get setupLinkSaveFile => 'Save setup file';@override- String get setupLinkQrError =>- 'This setup link is too large for a QR code. Share the link instead.';+ String get setupLinkQrError => 'This setup link is too large for a QR code. Share the link instead.';@overrideString setupLinkShareSubject(String username) {@@ -347,8 +337,7 @@ class AppLocalizationsZh extends AppLocalizations {String get loginPasteLink => 'Paste login link';@override- String get loginPasteLinkHelp =>- 'Paste the complete sign-in link you received. Treat it like a password.';+ String get loginPasteLinkHelp => 'Paste the complete sign-in link you received. Treat it like a password.';@overrideString get loginFailed => '登录失败';@@ -444,8 +433,7 @@ class AppLocalizationsZh extends AppLocalizations {String get libraryNoBooksWithEbooks => '暂无包含电子书的书籍';@override- String get libraryNoBooksMissingMetadata =>- 'No books are missing this metadata';+ String get libraryNoBooksMissingMetadata => 'No books are missing this metadata';@overrideString get libraryNoItemsMatchingFilter => 'No items match this filter';@@ -1163,8 +1151,7 @@ class AppLocalizationsZh extends AppLocalizations {String get statsTimeSavedReset => 'Reset time saved';@override- String get statsTimeSavedResetConfirm =>- 'Time saved will start counting again from today.';+ String get statsTimeSavedResetConfirm => 'Time saved will start counting again from today.';@overrideString get statsTimeSavedResetDone => 'Time saved reset';@@ -1235,22 +1222,19 @@ class AppLocalizationsZh extends AppLocalizations {String get settingsPodcastTab => 'Podcasts tab';@override- String get settingsPodcastTabDesc =>- 'Give one podcast library its own tab in the bottom bar';+ String get settingsPodcastTabDesc => 'Give one podcast library its own tab in the bottom bar';@overrideString get settingsPodcastTabLibrary => 'Podcasts tab library';@override- String get settingsMergeImpliedByPodcastTab =>- 'Always on while the Podcasts tab is enabled';+ String get settingsMergeImpliedByPodcastTab => 'Always on while the Podcasts tab is enabled';@overrideString get settingsEpisodeNotifs => 'Notification settings';@override- String get settingsEpisodeNotifsDesc =>- 'New podcast episodes and upcoming book releases, checked in the background';+ String get settingsEpisodeNotifsDesc => 'New podcast episodes and upcoming book releases, checked in the background';@overrideString get notifIntervalOff => '关闭';@@ -1272,8 +1256,7 @@ class AppLocalizationsZh extends AppLocalizations {String get settingsBatteryUnrestricted => '允许不受限制地使用电池';@override- String get settingsBatteryUnrestrictedDesc =>- 'Keeps the system from pausing background checks on some phones';+ String get settingsBatteryUnrestrictedDesc => 'Keeps the system from pausing background checks on some phones';@overrideString get appShellPressBackToExit => '再按一次返回键退出';@@ -1330,8 +1313,7 @@ class AppLocalizationsZh extends AppLocalizations {String get colorSourceManual => '手动';@override- String get colorSourceManualDescription =>- 'Use a fixed app color you choose below';+ String get colorSourceManualDescription => 'Use a fixed app color you choose below';@overrideString get colorSourceCustom => '自定义';@@ -1340,26 +1322,22 @@ class AppLocalizationsZh extends AppLocalizations {String get useColorEverywhereLabel => 'Use this color everywhere';@override- String get useColorEverywhereSubtitle =>- 'Also color book detail pages and the player card with your set color instead of each book\'s cover';+ String get useColorEverywhereSubtitle => 'Also color book detail pages and the player card with your set color instead of each book\'s cover';@overrideString get flatBackgroundLabel => 'Flat background';@override- String get flatBackgroundSubtitle =>- 'Remove the background gradient. Pure black in dark mode for OLED screens.';+ String get flatBackgroundSubtitle => 'Remove the background gradient. Pure black in dark mode for OLED screens.';@overrideString get einkModeLabel => 'E-ink mode';@override- String get einkModeSubtitle =>- 'High-contrast black and white with no animations, made for e-ink screens';+ String get einkModeSubtitle => 'High-contrast black and white with no animations, made for e-ink screens';@override- String get einkModeIntroBody =>- 'Made for e-ink screens. The app switches to a flat black-and-white look with high contrast, animations are turned off, the playing card loses its background, and the live server connection stays off to save battery. Playback and progress still sync normally. Your appearance settings are kept and come back when you turn this off.';+ String get einkModeIntroBody => 'Made for e-ink screens. The app switches to a flat black-and-white look with high contrast, animations are turned off, the playing card loses its background, and the live server connection stays off to save battery. Playback and progress still sync normally. Your appearance settings are kept and come back when you turn this off.';@overrideString get einkModeIntroConfirm => 'Turn on';@@ -1485,8 +1463,7 @@ class AppLocalizationsZh extends AppLocalizations {String get whenAbsorbedInfoTitle => '当收听完成时';@override- String get whenAbsorbedInfoContent =>- '控制当您完成一本书或一集后收听卡片的行为。\n\n已完成的卡片会自动从从您的“正在收听”屏幕中移除。';+ String get whenAbsorbedInfoContent => '控制当您完成一本书或一集后收听卡片的行为。\n\n已完成的卡片会自动从从您的“正在收听”屏幕中移除。';@overrideString get whenAbsorbedSubtitle => '听完一本书或或一集后收听卡片的处理方式';@@ -1504,8 +1481,7 @@ class AppLocalizationsZh extends AppLocalizations {String get mergeLibrariesInfoTitle => '合并媒体库';@override- String get mergeLibrariesInfoContent =>- '启用后,“正在收听”界面会将您所有媒体库中正在进行的书籍和播客集中显示在一个视图中。禁用时,仅显示您当前所选媒体库中的项目。';+ String get mergeLibrariesInfoContent => '启用后,“正在收听”界面会将您所有媒体库中正在进行的书籍和播客集中显示在一个视图中。禁用时,仅显示您当前所选媒体库中的项目。';@overrideString get mergeLibrariesOnSubtitle => '正在收听页面显示来自所有媒体库的项目';@@ -1529,8 +1505,7 @@ class AppLocalizationsZh extends AppLocalizations {String get queueModeInfoManual => '手动队列';@override- String get queueModeInfoManualDesc =>- '你的收听卡片将作为播放列表使用。当一个播放完成时,会自动播放下一个未完成的卡片。通过书籍或单集详情页的\"添加至正在收听\"按钮添加项目,并在收听界面重新排序。';+ String get queueModeInfoManualDesc => '你的收听卡片将作为播放列表使用。当一个播放完成时,会自动播放下一个未完成的卡片。通过书籍或单集详情页的\"添加至正在收听\"按钮添加项目,并在收听界面重新排序。';@overrideString get queueModeOff => '关闭';@@ -1565,8 +1540,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get queueModePlaylistHint =>- 'Start a playlist queue by opening a playlist on the home page.';+ String get queueModePlaylistHint => 'Start a playlist queue by opening a playlist on the home page.';@overrideString get exit => '退出';@@ -1645,19 +1619,16 @@ class AppLocalizationsZh extends AppLocalizations {String get skipForward => '快进';@override- String get iosLockScreenSkipHint =>- 'The lock screen only draws the numbers iOS has icons for (5, 10, 15, 30, 45, 60, 75, 90). Other amounts show + on the button but still skip by your setting.';+ String get iosLockScreenSkipHint => 'The lock screen only draws the numbers iOS has icons for (5, 10, 15, 30, 45, 60, 75, 90). Other amounts show + on the button but still skip by your setting.';@overrideString get longSkipButtons => 'Long skip buttons';@override- String get longSkipButtonsOnSubtitle =>- 'On - the player shows a second, bigger skip pair';+ String get longSkipButtonsOnSubtitle => 'On - the player shows a second, bigger skip pair';@override- String get longSkipButtonsOffSubtitle =>- 'Off - just the regular skip buttons';+ String get longSkipButtonsOffSubtitle => 'Off - just the regular skip buttons';@overrideString get longSkipBack => 'Long skip back';@@ -1681,12 +1652,10 @@ class AppLocalizationsZh extends AppLocalizations {String get showSubtitles => 'Show subtitles';@override- String get showSubtitlesOnSubtitle =>- 'Subtitles show under book titles in the library and on home';+ String get showSubtitlesOnSubtitle => 'Subtitles show under book titles in the library and on home';@override- String get showSubtitlesOffSubtitle =>- 'Off - subtitles only on the book details sheet';+ String get showSubtitlesOffSubtitle => 'Off - subtitles only on the book details sheet';@overrideString get subtitleVisibilityLabel => 'Subtitles';@@ -1709,12 +1678,10 @@ class AppLocalizationsZh extends AppLocalizations {String get currentLibrarySkipOverride => 'Custom skip amounts';@override- String get currentLibrarySkipOverrideOnSubtitle =>- 'On - this library uses its own skip amounts';+ String get currentLibrarySkipOverrideOnSubtitle => 'On - this library uses its own skip amounts';@override- String get currentLibrarySkipOverrideOffSubtitle =>- 'Off - this library uses the global skip amounts';+ String get currentLibrarySkipOverrideOffSubtitle => 'Off - this library uses the global skip amounts';@overrideString get currentLibrarySkipBack => 'Skip back';@@ -1732,19 +1699,16 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterProgressOffSubtitle => '关闭 - 锁屏显示全书进度';@override- String get chapterProgressInNotificationIos =>- 'Chapter progress on lock screen & CarPlay';+ String get chapterProgressInNotificationIos => 'Chapter progress on lock screen & CarPlay';@override- String get chapterProgressOnSubtitleIos =>- 'On - lock screen & CarPlay show chapter progress';+ String get chapterProgressOnSubtitleIos => 'On - lock screen & CarPlay show chapter progress';@overrideString get nowPlayingText => 'Now playing text';@override- String get nowPlayingTextSubtitle =>- 'Choose what the media controls show on each line';+ String get nowPlayingTextSubtitle => 'Choose what the media controls show on each line';@overrideString get nowPlayingTopLine => 'Top line';@@ -1756,8 +1720,7 @@ class AppLocalizationsZh extends AppLocalizations {String get nowPlayingNotShown => 'Not shown';@override- String get nowPlayingTopLineRequired =>- 'The top line needs at least one item';+ String get nowPlayingTopLineRequired => 'The top line needs at least one item';@overrideString get nowPlayingPieceChapter => 'Chapter';@@ -1938,15 +1901,13 @@ class AppLocalizationsZh extends AppLocalizations {String get bookDockPickLibrary => 'Add to which library?';@override- String get bookDockNoLibraries =>- 'Your account can\'t add books to a library';+ String get bookDockNoLibraries => 'Your account can\'t add books to a library';@overrideString get bookDockFileFailed => 'Couldn\'t add this file to the library';@override- String get bookDockDuplicateBody =>- 'A file with this name is already in that library. Remove it from Book Dock?';+ String get bookDockDuplicateBody => 'A file with this name is already in that library. Remove it from Book Dock?';@overrideString get bookDockDetailsUpdated => 'Details updated';@@ -1986,8 +1947,7 @@ class AppLocalizationsZh extends AppLocalizations {String get bomatchSearching => 'Searching...';@override- String get bomatchSearchFailed =>- 'Couldn\'t search for matches. Check your connection and try again.';+ String get bomatchSearchFailed => 'Couldn\'t search for matches. Check your connection and try again.';@overrideString get bomatchNoResults => 'No matches found';@@ -2141,8 +2101,7 @@ class AppLocalizationsZh extends AppLocalizations {String get breqTabAll => 'All requests';@override- String get breqNoAccess =>- 'Your account can\'t request books on this server.';+ String get breqNoAccess => 'Your account can\'t request books on this server.';@overrideString get breqTitleHint => 'Book title';@@ -2166,12 +2125,10 @@ class AppLocalizationsZh extends AppLocalizations {String get breqSearching => 'Searching...';@override- String get breqSearchFailed =>- 'Couldn\'t search. Check your connection and try again.';+ String get breqSearchFailed => 'Couldn\'t search. Check your connection and try again.';@override- String get breqSearchPrompt =>- 'Search for a book the library does not have yet to request it.';+ String get breqSearchPrompt => 'Search for a book the library does not have yet to request it.';@overrideString get breqNoResults => 'No matching books found';@@ -2324,8 +2281,7 @@ class AppLocalizationsZh extends AppLocalizations {String get breqOpenBook => 'Open book';@override- String get breqCancelConfirm =>- 'Cancel this request? A download in progress stops too.';+ String get breqCancelConfirm => 'Cancel this request? A download in progress stops too.';@overrideString get breqDeleteConfirm => 'Delete this request? This can\'t be undone.';@@ -2340,8 +2296,7 @@ class AppLocalizationsZh extends AppLocalizations {String get breqApproveTitle => 'Approve request';@override- String get breqApproveLibraryNeeded =>- 'Choose the library this book goes into.';+ String get breqApproveLibraryNeeded => 'Choose the library this book goes into.';@overrideString get breqApprovedToast => 'Request approved';@@ -2392,8 +2347,7 @@ class AppLocalizationsZh extends AppLocalizations {String get breqLibraryCta => 'Request a book';@override- String get breqSettingsSubtitle =>- 'Ask for books the library does not have yet';+ String get breqSettingsSubtitle => 'Ask for books the library does not have yet';@overrideString get navHoldBookRequests => 'Book requests';@@ -2471,15 +2425,13 @@ class AppLocalizationsZh extends AppLocalizations {String get breqStopDownload => 'Stop download';@override- String get breqStopDownloadConfirm =>- 'Stop this download? The request goes back to approved so another release can be picked.';+ String get breqStopDownloadConfirm => 'Stop this download? The request goes back to approved so another release can be picked.';@overrideString get breqDiscardImport => 'Discard download';@override- String get breqDiscardConfirm =>- 'Discard this download? The request is marked failed and can be tried again with another release.';+ String get breqDiscardConfirm => 'Discard this download? The request is marked failed and can be tried again with another release.';@overrideString get breqFileAnyway => 'Add to library';@@ -2506,16 +2458,13 @@ class AppLocalizationsZh extends AppLocalizations {String get breqGrabFailed => 'Couldn\'t start that download';@override- String get breqReleaseVipWarning =>- 'This tracker only lets VIP accounts download it.';+ String get breqReleaseVipWarning => 'This tracker only lets VIP accounts download it.';@override- String get breqReleaseNoBookFile =>- 'This release has no book file BookOrbit can add to a library.';+ String get breqReleaseNoBookFile => 'This release has no book file BookOrbit can add to a library.';@override- String get breqReleaseCheckFailed =>- 'Couldn\'t check what\'s in this release. Try again or pick another one.';+ String get breqReleaseCheckFailed => 'Couldn\'t check what\'s in this release. Try again or pick another one.';@overrideString get breqCheckingRelease => 'Checking the files...';@@ -2530,8 +2479,7 @@ class AppLocalizationsZh extends AppLocalizations {String get breqIsbnHint => 'Leave empty to search by title and author';@override- String get breqSearchingIndexers =>- 'Searching your indexers. This can take up to a minute.';+ String get breqSearchingIndexers => 'Searching your indexers. This can take up to a minute.';@overrideString get breqReleasesFailed => 'Couldn\'t search for releases.';@@ -2540,12 +2488,10 @@ class AppLocalizationsZh extends AppLocalizations {String get breqNoSourcesSetUp => 'No search sources are set up in BookOrbit.';@override- String get breqNoSourcesOn =>- 'Every search source is switched off in BookOrbit.';+ String get breqNoSourcesOn => 'Every search source is switched off in BookOrbit.';@override- String get breqNoSourceCarries =>- 'None of your search sources carry this kind of book.';+ String get breqNoSourceCarries => 'None of your search sources carry this kind of book.';@overrideString get breqNoReleases => 'No releases found. Try different search terms.';@@ -2623,12 +2569,10 @@ class AppLocalizationsZh extends AppLocalizations {String get breqReviewFailed => 'Couldn\'t load the download details.';@override- String get breqReviewDockGone =>- 'The downloaded files are no longer in the Book Dock.';+ String get breqReviewDockGone => 'The downloaded files are no longer in the Book Dock.';@override- String get breqReviewNoLibrary =>- 'This request has no library to add the book to.';+ String get breqReviewNoLibrary => 'This request has no library to add the book to.';@overrideString breqGrabFailedReason(String reason) {@@ -2755,37 +2699,31 @@ class AppLocalizationsZh extends AppLocalizations {String get breqPairSubmitted => 'Requested the e-book and the audiobook';@override- String get breqPairOneJoined =>- 'Requested both. One was already on its way, so you were added to that request';+ String get breqPairOneJoined => 'Requested both. One was already on its way, so you were added to that request';@overrideString get breqJoinedBoth => 'Added you to both requests';@override- String get breqJoinsOwned =>- 'Requested. It will join the copy already in your library';+ String get breqJoinsOwned => 'Requested. It will join the copy already in your library';@overrideString get speedBookmarkInControls => 'Speed & bookmark in media controls';@override- String get speedBookmarkOnSubtitle =>- 'On - notification shows speed & bookmark; chapter skip stays in Android Auto';+ String get speedBookmarkOnSubtitle => 'On - notification shows speed & bookmark; chapter skip stays in Android Auto';@override- String get speedBookmarkOffSubtitle =>- 'Off - notification shows chapter skip; speed & bookmark stay in Android Auto';+ String get speedBookmarkOffSubtitle => 'Off - notification shows chapter skip; speed & bookmark stay in Android Auto';@overrideString get lockSeekBar => '锁定搜索栏';@override- String get lockSeekBarOnSubtitle =>- 'On - the scrubber in the notification, lockscreen and car shows progress but can\'t be dragged';+ String get lockSeekBarOnSubtitle => 'On - the scrubber in the notification, lockscreen and car shows progress but can\'t be dragged';@override- String get lockSeekBarOffSubtitle =>- 'Off - drag the scrubber in the notification, lockscreen and car to jump around';+ String get lockSeekBarOffSubtitle => 'Off - drag the scrubber in the notification, lockscreen and car to jump around';@overrideString get autoRewindOnResume => '恢复播放时自动倒退';@@ -2894,8 +2832,7 @@ class AppLocalizationsZh extends AppLocalizations {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.';+ String get buttonDuringSleepTimerHint => 'In the final wind-down moments, one press resets the timer instead of pausing. Double press still skips.';@overrideString get resetTimerOnPause => '暂停时重置定时器';@@ -2981,8 +2918,7 @@ class AppLocalizationsZh extends AppLocalizations {String get autoDownloadOnWifiInfoTitle => 'Wi-Fi 下自动下载';@override- String get autoDownloadOnWifiInfoContent =>- '当您开始在线播放书籍时,系统会在后台同步下载完整内容,无需手动操作即可实现离线收听。后台下载将严格遵循上方的“下载网络设置”,若您希望在移动网络下也能自动下载,请将其设置为“任意网络”。';+ String get autoDownloadOnWifiInfoContent => '当您开始在线播放书籍时,系统会在后台同步下载完整内容,无需手动操作即可实现离线收听。后台下载将严格遵循上方的“下载网络设置”,若您希望在移动网络下也能自动下载,请将其设置为“任意网络”。';@overrideString get autoDownloadOnWifiOnSubtitle => '在 Wi-Fi 下开始流式播放时,书籍将在后台下载';@@ -3015,8 +2951,7 @@ class AppLocalizationsZh extends AppLocalizations {String get keepNextInfoTitle => '保留接下来';@override- String get keepNextInfoContent =>- '要保留下载的项目数量,包括你当前正在收听的项目。例如,\"保留接下来3个\"意味着当前书籍加上系列或播客中的下2本将保持下载状态。';+ String get keepNextInfoContent => '要保留下载的项目数量,包括你当前正在收听的项目。例如,\"保留接下来3个\"意味着当前书籍加上系列或播客中的下2本将保持下载状态。';@overrideString get deleteAbsorbedDownloads => '删除已完成的下载';@@ -3025,8 +2960,7 @@ class AppLocalizationsZh extends AppLocalizations {String get deleteAbsorbedDownloadsInfoTitle => '删除已完成的下载';@override- String get deleteAbsorbedDownloadsInfoContent =>- '启用后,在 Absorb 中听完的已下载书籍或剧集会自动从此设备删除。如果你在网页端或其他设备上听完,保存在此设备上的下载不会被删除。';+ String get deleteAbsorbedDownloadsInfoContent => '启用后,在 Absorb 中听完的已下载书籍或剧集会自动从此设备删除。如果你在网页端或其他设备上听完,保存在此设备上的下载不会被删除。';@overrideString get deleteAbsorbedOnSubtitle => '已完成项目将被移除以节省空间';@@ -3060,8 +2994,7 @@ class AppLocalizationsZh extends AppLocalizations {String get streamingCacheInfoTitle => '流式缓存';@override- String get streamingCacheInfoContent =>- '将流式播放的音频缓存到磁盘,以便在快退或重复收听时无需重新下载。缓存会自动管理 - 达到大小限制时,最旧的文件会被移除。这与完全下载的书籍是分开的';+ String get streamingCacheInfoContent => '将流式播放的音频缓存到磁盘,以便在快退或重复收听时无需重新下载。缓存会自动管理 - 达到大小限制时,最旧的文件会被移除。这与完全下载的书籍是分开的';@overrideString get streamingCacheOff => '关闭';@@ -3179,8 +3112,7 @@ class AppLocalizationsZh extends AppLocalizations {String get clearLogsQuestion => 'Clear logs?';@override- String get clearLogsContent =>- 'This can\'t be undone. Send them first if you might want them.';+ String get clearLogsContent => 'This can\'t be undone. Send them first if you might want them.';@overrideString get sectionAdvanced => '高级';@@ -3192,8 +3124,7 @@ class AppLocalizationsZh extends AppLocalizations {String get localServerInfoTitle => '本地服务器';@override- String get localServerInfoContent =>- '如果你在家运行 Audiobookshelf 服务器,可以在此设置本地/局域网 URL。Absorb 在检测到您处于家庭网络时会自动切换到更快的本地连接,而在外出时则回退到远程 URL。';+ String get localServerInfoContent => '如果你在家运行 Audiobookshelf 服务器,可以在此设置本地/局域网 URL。Absorb 在检测到您处于家庭网络时会自动切换到更快的本地连接,而在外出时则回退到远程 URL。';@overrideString get localServerOnConnectedSubtitle => '已通过本地服务器连接';@@ -3220,8 +3151,7 @@ class AppLocalizationsZh extends AppLocalizations {String get disableAudioFocusInfoTitle => '音频焦点';@override- String get disableAudioFocusInfoContent =>- '默认情况下,Android 一次只给一个应用音频“焦点” - 当 Absorb 播放时,其他音频(音乐、视频)会暂停。禁用音频焦点可让 Absorb 与其他应用同时播放。无论此设置如何,来电时始终会暂停播放。';+ String get disableAudioFocusInfoContent => '默认情况下,Android 一次只给一个应用音频“焦点” - 当 Absorb 播放时,其他音频(音乐、视频)会暂停。禁用音频焦点可让 Absorb 与其他应用同时播放。无论此设置如何,来电时始终会暂停播放。';@overrideString get disableAudioFocusOnSubtitle => '开启 - 与其他音频同时播放(来电时仍会暂停)';@@ -3251,19 +3181,16 @@ class AppLocalizationsZh extends AppLocalizations {String get mp3IndexSeekingInfoTitle => 'MP3 Index Seeking';@override- String get mp3IndexSeekingInfoContent =>- 'Only enable this if you have MP3 files that don\'t seek to the right position. Inaccurate seeking usually comes from variable bitrate (VBR) MP3s. Index seeking builds an exact time map as the file is read, so jumping near the end of a large MP3 can take a moment - especially when streaming, since the file has to be read up to that point. Takes effect the next time a book or podcast episode starts.';+ String get mp3IndexSeekingInfoContent => 'Only enable this if you have MP3 files that don\'t seek to the right position. Inaccurate seeking usually comes from variable bitrate (VBR) MP3s. Index seeking builds an exact time map as the file is read, so jumping near the end of a large MP3 can take a moment - especially when streaming, since the file has to be read up to that point. Takes effect the next time a book or podcast episode starts.';@override- String get mp3IndexSeekingOnSubtitle =>- 'On - exact seeking for VBR MP3 files';+ String get mp3IndexSeekingOnSubtitle => 'On - exact seeking for VBR MP3 files';@overrideString get mp3IndexSeekingOffSubtitle => 'Off - normal seeking';@override- String get trustAllCertificatesInfoContent =>- '如果你的 Audiobookshelf 服务器使用自签名证书或自定义根 CA,请启用此选项。启用后,Absorb 将跳过所有连接的 TLS 证书验证。仅在您信任当前网络环境时启用。';+ String get trustAllCertificatesInfoContent => '如果你的 Audiobookshelf 服务器使用自签名证书或自定义根 CA,请启用此选项。启用后,Absorb 将跳过所有连接的 TLS 证书验证。仅在您信任当前网络环境时启用。';@overrideString get trustAllCertificatesOnSubtitle => '开启 - 接受所有证书';@@ -3323,8 +3250,7 @@ class AppLocalizationsZh extends AppLocalizations {String get includeLoginInfoTitle => '包含登录信息?';@override- String get includeLoginInfoContent =>- '你是否希望在备份中包含所有已保存账号的登录凭据?\n\n这会让在新设备上恢复变得容易,但文件中将包含您的身份验证令牌。';+ String get includeLoginInfoContent => '你是否希望在备份中包含所有已保存账号的登录凭据?\n\n这会让在新设备上恢复变得容易,但文件中将包含您的身份验证令牌。';@overrideString get noSettingsOnly => '否,仅设置';@@ -3391,8 +3317,7 @@ class AppLocalizationsZh extends AppLocalizations {String get changePasswordTitle => 'Change Password';@override- String get changePasswordSubtitle =>- 'Update your Audiobookshelf password safely';+ String get changePasswordSubtitle => 'Update your Audiobookshelf password safely';@overrideString get currentPassword => 'Current password';@@ -3404,8 +3329,7 @@ class AppLocalizationsZh extends AppLocalizations {String get confirmNewPassword => 'Confirm new password';@override- String get passwordChangeEffect =>- 'Changing your password signs out your other Audiobookshelf sessions. This device stays signed in.';+ String get passwordChangeEffect => 'Changing your password signs out your other Audiobookshelf sessions. This device stays signed in.';@overrideString get passwordFieldsRequired => 'Fill in all password fields';@@ -3414,29 +3338,25 @@ class AppLocalizationsZh extends AppLocalizations {String get passwordsDoNotMatch => 'New passwords do not match';@override- String get passwordChanged =>- 'Password changed. Other signed-in devices were disconnected.';+ String get passwordChanged => 'Password changed. Other signed-in devices were disconnected.';@overrideString get passwordInvalid => 'The current password is incorrect';@override- String get passwordChangeUnsupported =>- 'This server version does not support safe password changes in Absorb';+ String get passwordChangeUnsupported => 'This server version does not support safe password changes in Absorb';@overrideString get passwordChangeFailed => 'Could not change your password';@override- String get otherUserPasswordResetWarning =>- 'Changing this password signs the user out on every device.';+ String get otherUserPasswordResetWarning => 'Changing this password signs the user out on every device.';@overrideString get manageSessionsTitle => 'Signed-in Devices';@override- String get manageSessionsSubtitle =>- 'Review and remove Audiobookshelf sessions';+ String get manageSessionsSubtitle => 'Review and remove Audiobookshelf sessions';@overrideString get sessionsCurrent => 'Current device';@@ -3456,15 +3376,13 @@ class AppLocalizationsZh extends AppLocalizations {String get sessionsLoadMore => 'Load more';@override- String get sessionsUnsupported =>- 'Session management requires Audiobookshelf 2.36 or newer.';+ String get sessionsUnsupported => 'Session management requires Audiobookshelf 2.36 or newer.';@overrideString get sessionsLoadFailed => 'Could not load signed-in devices';@override- String get sessionsLegacyNotice =>- 'This login does not have a refresh session, so Absorb cannot identify this device in the list.';+ String get sessionsLegacyNotice => 'This login does not have a refresh session, so Absorb cannot identify this device in the list.';@overrideString get sessionsRemove => 'Sign out device';@@ -3473,8 +3391,7 @@ class AppLocalizationsZh extends AppLocalizations {String get sessionsRemoveTitle => 'Sign out this device?';@override- String get sessionsRemoveContent =>- 'This removes its refresh session. Its current access may keep working until that short-lived token expires.';+ String get sessionsRemoveContent => 'This removes its refresh session. Its current access may keep working until that short-lived token expires.';@overrideString get sessionsRemoved => 'Device signed out';@@ -3489,8 +3406,7 @@ class AppLocalizationsZh extends AppLocalizations {String get sessionsSignOutAllTitle => 'Sign out everywhere?';@override- String get sessionsSignOutAllContent =>- 'This removes every refresh session, including this device. Existing access tokens may work until they expire.';+ String get sessionsSignOutAllContent => 'This removes every refresh session, including this device. Existing access tokens may work until they expire.';@overrideString podcastScheduleServerTime(String timeZone) {@@ -3538,8 +3454,7 @@ class AppLocalizationsZh extends AppLocalizations {String get editServerConnectionFailed => 'Couldn\'t update server connection';@override- String get editCustomHeadersDescription =>- 'Used for Cloudflare tunnels or reverse proxies. These headers apply only to this saved account.';+ String get editCustomHeadersDescription => 'Used for Cloudflare tunnels or reverse proxies. These headers apply only to this saved account.';@overrideString get removeAccountAction => 'Remove account';@@ -3609,10 +3524,8 @@ class AppLocalizationsZh extends AppLocalizations {String _temp0 = intl.Intl.pluralLogic(count,locale: localeName,- other:- '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',- one:- '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',+ other: '$count downloads are in an old custom folder that can no longer be opened. Re-download them or dismiss this notice.',+ one: '1 download is in an old custom folder that can no longer be opened. Re-download it or dismiss this notice.',);return '$_temp0';}@@ -3766,23 +3679,19 @@ class AppLocalizationsZh extends AppLocalizations {String get adminRmabAskAdmin => '请向您的服务器管理员获取登录 URL';@override- String get adminRmabUrlHelpUser =>- '请向您的服务器管理员获取登录 URL,管理员可在 RMAB 的管理 -> 用户中生成。';+ String get adminRmabUrlHelpUser => '请向您的服务器管理员获取登录 URL,管理员可在 RMAB 的管理 -> 用户中生成。';@override- String get adminRmabSettingsInfo =>- 'ReadMeABook 是一个用于请求和下载有声书的自托管服务,需要由您的服务器管理员安装和设置。';+ String get adminRmabSettingsInfo => 'ReadMeABook 是一个用于请求和下载有声书的自托管服务,需要由您的服务器管理员安装和设置。';@overrideString get rmabConfigTitle => 'Connect ReadMeABook';@override- String get rmabConfigExplainerAdmin =>- 'ReadMeABook is a self-hosted service for requesting audiobooks. Generate an API token in RMAB under Admin Dashboard > Settings > API, then paste the server URL and token below. Absorb doesn\'t host or download any content, it just sends requests to your server.';+ String get rmabConfigExplainerAdmin => 'ReadMeABook is a self-hosted service for requesting audiobooks. Generate an API token in RMAB under Admin Dashboard > Settings > API, then paste the server URL and token below. Absorb doesn\'t host or download any content, it just sends requests to your server.';@override- String get rmabConfigExplainerUser =>- 'ReadMeABook is a self-hosted service for requesting audiobooks. Ask your server admin for the RMAB URL and an API token. Absorb doesn\'t host or download any content, it just sends requests to your server.';+ String get rmabConfigExplainerUser => 'ReadMeABook is a self-hosted service for requesting audiobooks. Ask your server admin for the RMAB URL and an API token. Absorb doesn\'t host or download any content, it just sends requests to your server.';@overrideString get rmabConfigLearnMore => 'Learn more about ReadMeABook';@@ -3806,12 +3715,10 @@ class AppLocalizationsZh extends AppLocalizations {String get rmabConfigLegacyUrlHint => 'https://rmab.example.com/?token=...';@override- String get rmabConfigLegacyUrlHelp =>- 'Paste your auto-login URL so \'Open in browser view\' lands you signed in. Leave blank to use a regular login.';+ String get rmabConfigLegacyUrlHelp => 'Paste your auto-login URL so \'Open in browser view\' lands you signed in. Leave blank to use a regular login.';@override- String get rmabConfigHeadersHelp =>- 'Extra headers sent with every ReadMeABook request, for reverse proxies like Cloudflare Access.';+ String get rmabConfigHeadersHelp => 'Extra headers sent with every ReadMeABook request, for reverse proxies like Cloudflare Access.';@overrideString get rmabConfigConnect => 'Connect';@@ -3837,8 +3744,7 @@ class AppLocalizationsZh extends AppLocalizations {String get rmabConfigErrorUnauthorized => 'Token rejected by server';@override- String get rmabConfigErrorForbidden =>- 'This token isn\'t allowed for that action';+ String get rmabConfigErrorForbidden => 'This token isn\'t allowed for that action';@overrideString get rmabConfigErrorNetwork => 'Couldn\'t reach RMAB. Check the URL.';@@ -3879,8 +3785,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get rmabBookDetailExplainer =>- 'This request will be sent through your ReadMeABook server. The admin will review and process it. You can track it under My Requests on the ReadMeABook tile.';+ String get rmabBookDetailExplainer => 'This request will be sent through your ReadMeABook server. The admin will review and process it. You can track it under My Requests on the ReadMeABook tile.';@overrideString get rmabBookAlreadyAvailable => 'Already in your library';@@ -3907,8 +3812,7 @@ class AppLocalizationsZh extends AppLocalizations {String get rmabRequestErrorValidation => 'Couldn\'t send the request';@override- String get rmabRequestErrorUserNotFound =>- 'Token user no longer exists. Reconnect ReadMeABook.';+ String get rmabRequestErrorUserNotFound => 'Token user no longer exists. Reconnect ReadMeABook.';@overrideString get rmabRequestErrorIgnored => 'This book is on your ignore list';@@ -3917,8 +3821,7 @@ class AppLocalizationsZh extends AppLocalizations {String get rmabRequestErrorGeneric => 'Couldn\'t send the request';@override- String get rmabRequestErrorTokenRejected =>- 'Token rejected by server. Reconnect ReadMeABook.';+ String get rmabRequestErrorTokenRejected => 'Token rejected by server. Reconnect ReadMeABook.';@overrideString get rmabMyRequestsTab => 'My Requests';@@ -4003,8 +3906,7 @@ class AppLocalizationsZh extends AppLocalizations {String get absorbAudioNotDownloaded => 'Audio not downloaded';@override- String get absorbAudioNotDownloadedEbookOnly =>- 'Audio not downloaded, ebook only';+ String get absorbAudioNotDownloadedEbookOnly => 'Audio not downloaded, ebook only';@overrideString get fullyAbsorbed => '已完成';@@ -4131,8 +4033,7 @@ class AppLocalizationsZh extends AppLocalizations {String get encodeTimeNote => 'Encoding can take up to 30 minutes.';@override- String get encodeRescanNote =>- 'If you have the watcher disabled you will need to re-scan this audiobook afterwards.';+ String get encodeRescanNote => 'If you have the watcher disabled you will need to re-scan this audiobook afterwards.';@overrideString get aboutSection => '关于';@@ -4474,8 +4375,7 @@ class AppLocalizationsZh extends AppLocalizations {String get coverRemove => 'Remove cover';@override- String get coverRemoveConfirm =>- 'Remove this book\'s cover? It will show the generated title card instead.';+ String get coverRemoveConfirm => 'Remove this book\'s cover? It will show the generated title card instead.';@overrideString get coverRemoved => 'Cover removed';@@ -4580,19 +4480,16 @@ class AppLocalizationsZh extends AppLocalizations {String get deleteCollectionFailed => 'Couldn\'t delete the collection';@override- String get deletePermissionRequired =>- 'Delete permission required. Ask the root admin to grant you the delete permission.';+ String get deletePermissionRequired => 'Delete permission required. Ask the root admin to grant you the delete permission.';@overrideString get deleteFilesCheckbox => 'Also delete the files on the server';@override- String get deleteFilesCheckedHint =>- 'The files are deleted from the server for good.';+ String get deleteFilesCheckedHint => 'The files are deleted from the server for good.';@override- String get deleteFilesUncheckedHint =>- 'The files stay on the server, so the next library scan can add this back.';+ String get deleteFilesUncheckedHint => 'The files stay on the server, so the next library scan can add this back.';@overrideString get deleteFromServerAction => 'Delete from Server';@@ -4611,8 +4508,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get deleteFromServerFailed =>- 'Couldn\'t delete that. Check the server logs.';+ String get deleteFromServerFailed => 'Couldn\'t delete that. Check the server logs.';@overrideString get playlistNotFound => '未找到播放列表';@@ -4647,8 +4543,7 @@ class AppLocalizationsZh extends AppLocalizations {String get listsNewCollectionSubtitle => 'Group books into a list you keep';@override- String get listsNewCollectionNeedsBookSubtitle =>- 'Start it with at least one book';+ String get listsNewCollectionNeedsBookSubtitle => 'Start it with at least one book';@overrideString get listsNewPlaylistSubtitle => 'Line up books to listen to in order';@@ -4657,15 +4552,13 @@ class AppLocalizationsZh extends AppLocalizations {String get listsAddBooksNow => 'Add books now';@override- String get listsPickBooksNext =>- 'You\'ll pick books next. A collection on this server needs at least one.';+ String get listsPickBooksNext => 'You\'ll pick books next. A collection on this server needs at least one.';@overrideString get listsCreate => 'Create';@override- String get listsCollectionNeedsBook =>- 'A collection needs at least one book, so nothing was created.';+ String get listsCollectionNeedsBook => 'A collection needs at least one book, so nothing was created.';@overrideString get listsCreateFailed => 'Couldn\'t create it';@@ -4716,15 +4609,13 @@ class AppLocalizationsZh extends AppLocalizations {String get welcomeGettingAroundTitle => '界面操作';@override- String get welcomeGettingAroundBody =>- '点击任意封面打开详情。继续收听卡片不一样 - 点击立即播放,长按打开详情。';+ String get welcomeGettingAroundBody => '点击任意封面打开详情。继续收听卡片不一样 - 点击立即播放,长按打开详情。';@overrideString get welcomeMakeItYoursTitle => '个性化设置';@override- String get welcomeMakeItYoursBody =>- '在设置中自定义 Absorb 以符合你的喜好。其中的「技巧与隐藏功能」区块值得一看。';+ String get welcomeMakeItYoursBody => '在设置中自定义 Absorb 以符合你的喜好。其中的「技巧与隐藏功能」区块值得一看。';@overrideString get getStarted => '开始使用';@@ -4870,16 +4761,13 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterBarrierInfoTitle => 'Chapter barrier';@override- String get chapterBarrierInfoContent =>- 'When skipping back, the playback will snap to the start of the current chapter instead of crossing into the previous one.\n\nDouble-tap the skip back button within 2 seconds to break through the barrier.';+ String get chapterBarrierInfoContent => 'When skipping back, the playback will snap to the start of the current chapter instead of crossing into the previous one.\n\nDouble-tap the skip back button within 2 seconds to break through the barrier.';@override- String get chapterBarrierOnRewindOnSubtitle =>- 'On - rewind snaps to chapter start';+ String get chapterBarrierOnRewindOnSubtitle => 'On - rewind snaps to chapter start';@override- String get chapterBarrierOnRewindOffSubtitle =>- 'Off - rewind crosses chapter boundaries';+ String get chapterBarrierOnRewindOffSubtitle => 'Off - rewind crosses chapter boundaries';@overrideString autoRewindOnSubtitleFormat(String min, String max) {@@ -4890,8 +4778,7 @@ class AppLocalizationsZh extends AppLocalizations {String get rewindOnSessionStart => 'Rewind on session start';@override- String get rewindOnSessionStartInfoContent =>- 'Normal auto-rewind triggers when you resume from a pause within an active session. This setting adds a rewind when starting a completely new session - for example after the app was closed, playback was stopped, or you open the app fresh.\n\nWhen enabled, playback rewinds by the full max rewind amount at the start of every new session so you can re-hear where you left off.';+ String get rewindOnSessionStartInfoContent => 'Normal auto-rewind triggers when you resume from a pause within an active session. This setting adds a rewind when starting a completely new session - for example after the app was closed, playback was stopped, or you open the app fresh.\n\nWhen enabled, playback rewinds by the full max rewind amount at the start of every new session so you can re-hear where you left off.';@overrideString rewindOnSessionStartOnSubtitle(String seconds) {@@ -4964,11 +4851,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String autoSleepTimerEnabledSubtitle(- String start,- String end,- String duration,- ) {+ String autoSleepTimerEnabledSubtitle(String start, String end, String duration) {return '$start – $end · $duration';}@@ -4994,8 +4877,7 @@ class AppLocalizationsZh extends AppLocalizations {String get showEbookBadge => 'Show ebook badge';@override- String get showEbookBadgeOnSubtitle =>- 'Books with an ebook show a book icon on the cover';+ String get showEbookBadgeOnSubtitle => 'Books with an ebook show a book icon on the cover';@overrideString get showEbookBadgeOffSubtitle => 'Off - ebook badge hidden';@@ -5007,15 +4889,13 @@ class AppLocalizationsZh extends AppLocalizations {String get preReleaseUpdatesInfoTitle => 'Pre-release Updates';@override- String get preReleaseUpdatesInfoContent =>- 'When enabled, the update checker will also notify you about alpha and pre-release builds from GitHub. These may be less stable but include the latest features and fixes.';+ String get preReleaseUpdatesInfoContent => 'When enabled, the update checker will also notify you about alpha and pre-release builds from GitHub. These may be less stable but include the latest features and fixes.';@overrideString get includePreReleases => 'Include pre-releases';@override- String get includePreReleasesOnSubtitle =>- 'On - checking for alpha & pre-release builds';+ String get includePreReleasesOnSubtitle => 'On - checking for alpha & pre-release builds';@overrideString get includePreReleasesOffSubtitle => 'Off - stable releases only';@@ -5056,8 +4936,7 @@ class AppLocalizationsZh extends AppLocalizations {String get updateDownloading => 'Downloading update...';@override- String get updateInstallPermissionDenied =>- 'Install permission denied. Enable \"Install unknown apps\" for Absorb in system settings.';+ String get updateInstallPermissionDenied => 'Install permission denied. Enable \"Install unknown apps\" for Absorb in system settings.';@overrideString get updateOpeningInBrowser => 'In-app update failed, opening browser';@@ -5211,8 +5090,7 @@ class AppLocalizationsZh extends AppLocalizations {String get backupDetailsSeparator => ' · ';@override- String get bookmarksSortedByPositionReversed =>- 'Sorted by position (reversed)';+ String get bookmarksSortedByPositionReversed => 'Sorted by position (reversed)';@overrideString bookmarksJumpShortContent(String title, String position) {@@ -5286,8 +5164,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get resetMayNotHaveSynced =>- 'Reset may not have synced - check your server';+ String get resetMayNotHaveSynced => 'Reset may not have synced - check your server';@overrideString failedToDownloadEbook(int code) {@@ -5295,8 +5172,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get serverReturnedErrorPage =>- 'Server returned an error page instead of the ebook file';+ String get serverReturnedErrorPage => 'Server returned an error page instead of the ebook file';@overrideString ebookSaved(String filename) {@@ -5664,12 +5540,10 @@ class AppLocalizationsZh extends AppLocalizations {String get adminPodcastsCheckNewEpisodesTitle => 'Check for New Episodes';@override- String get adminPodcastsCheckNewEpisodesContent =>- 'This will check RSS feeds for all podcasts and download any new episodes found (if auto-download is enabled).';+ String get adminPodcastsCheckNewEpisodesContent => 'This will check RSS feeds for all podcasts and download any new episodes found (if auto-download is enabled).';@override- String get adminPodcastsCheckNewEpisodesSubtitle =>- 'Scan RSS feed and download new episodes';+ String get adminPodcastsCheckNewEpisodesSubtitle => 'Scan RSS feed and download new episodes';@overrideString get adminPodcastsCheck => 'Check';@@ -5944,8 +5818,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get adminPodcastsFailedToCheckNew =>- 'Failed to check for new episodes';+ String get adminPodcastsFailedToCheckNew => 'Failed to check for new episodes';@overrideString get adminPodcastsCheckAndDownload => 'Check & Download';@@ -5954,31 +5827,25 @@ class AppLocalizationsZh extends AppLocalizations {String get adminPodcastsMatchPodcast => 'Match Podcast';@override- String get adminPodcastsMatchPodcastSubtitle =>- 'Search iTunes to update cover and metadata';+ String get adminPodcastsMatchPodcastSubtitle => 'Search iTunes to update cover and metadata';@override- String get adminPodcastsAutoDownloadNewEpisodes =>- 'Auto-Download New Episodes';+ String get adminPodcastsAutoDownloadNewEpisodes => 'Auto-Download New Episodes';@override- String get adminPodcastsAutoDownloadOnSubtitle =>- 'Server downloads new episodes automatically';+ String get adminPodcastsAutoDownloadOnSubtitle => 'Server downloads new episodes automatically';@override- String get adminPodcastsAutoDownloadOffSubtitle =>- 'New episodes are not auto-downloaded';+ String get adminPodcastsAutoDownloadOffSubtitle => 'New episodes are not auto-downloaded';@override- String get adminPodcastsFailedAutoDownloadUpdate =>- 'Failed to update auto-download setting';+ String get adminPodcastsFailedAutoDownloadUpdate => 'Failed to update auto-download setting';@overrideString get adminPodcastsMaxEpisodesToKeep => 'Max episodes to keep';@override- String get adminPodcastsMaxEpisodesToKeepHelp =>- '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';+ String get adminPodcastsMaxEpisodesToKeepHelp => '0 keeps every episode. After a new episode is auto-downloaded, Audiobookshelf removes the oldest episode when the show is over this limit.';@overrideString get adminPodcastsNoEpisodeLimit => 'No limit';@@ -6081,8 +5948,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminPodcastsEditInfo => 'Edit Info';@override- String get adminPodcastsEditInfoSubtitle =>- 'Change title, description, cover and more';+ String get adminPodcastsEditInfoSubtitle => 'Change title, description, cover and more';@overrideString get adminPodcastsEditTitle => 'Edit Podcast';@@ -6125,8 +5991,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get episodeListUnsubscribeFromNewEpisodes =>- 'Unsubscribe from New Episodes';+ String get episodeListUnsubscribeFromNewEpisodes => 'Unsubscribe from New Episodes';@overrideString get episodeListSubscribeToNewEpisodes => 'Subscribe to New Episodes';@@ -6135,8 +6000,7 @@ class AppLocalizationsZh extends AppLocalizations {String get episodeListSubscribeTitle => 'Subscribe to this podcast?';@override- String get episodeListSubscribeContent =>- 'New episodes will be automatically downloaded and added to your absorbing queue when they appear on the server.';+ String get episodeListSubscribeContent => 'New episodes will be automatically downloaded and added to your absorbing queue when they appear on the server.';@overrideString get episodeListSubscribe => 'Subscribe';@@ -6229,12 +6093,10 @@ class AppLocalizationsZh extends AppLocalizations {String get episodeDetailMarkedFinishedNice => 'Marked as finished - nice!';@override- String get episodeDetailMarkAbsorbedContent =>- 'This will set your progress to 100% for this episode.';+ String get episodeDetailMarkAbsorbedContent => 'This will set your progress to 100% for this episode.';@override- String get episodeDetailResetProgressContent =>- 'This will erase all progress for this episode and set it back to the beginning. This can\'t be undone.';+ String get episodeDetailResetProgressContent => 'This will erase all progress for this episode and set it back to the beginning. This can\'t be undone.';@overrideString get episodeDetailToday => 'Today';@@ -6295,20 +6157,17 @@ class AppLocalizationsZh extends AppLocalizations {String get seriesBooksFindMissingTitle => '扫描缺失书籍';@override- String get seriesBooksFindMissingContent =>- '此功能将检索 Audible以查找该系列中你的媒体库可能缺失的书籍。\n\n系统会优先通过 ASIN 进行匹配(取决于你的服务器中书籍是否包含 ASIN),若无则通过书名进行匹配。搜索结果可能不会完全准确。';+ String get seriesBooksFindMissingContent => '此功能将检索 Audible以查找该系列中你的媒体库可能缺失的书籍。\n\n系统会优先通过 ASIN 进行匹配(取决于你的服务器中书籍是否包含 ASIN),若无则通过书名进行匹配。搜索结果可能不会完全准确。';@override- String get seriesBooksCouldNotFindOnAudible =>- 'Could not find this series on Audible';+ String get seriesBooksCouldNotFindOnAudible => 'Could not find this series on Audible';@overrideString seriesBooksMarkAllNotFinishedContent(int count) {String _temp0 = intl.Intl.pluralLogic(count,locale: localeName,- other:- 'This will clear the finished status for all $count books in this series.',+ other: 'This will clear the finished status for all $count books in this series.',one: 'This will clear the finished status for the 1 book in this series.',);return '$_temp0';@@ -6460,8 +6319,7 @@ class AppLocalizationsZh extends AppLocalizations {String get sessionEndPosition => 'Ending position';@override- String get sessionEndPositionHint =>- 'Changing this may also update your current progress.';+ String get sessionEndPositionHint => 'Changing this may also update your current progress.';@overrideString get statsViewSessions => 'View sessions';@@ -6472,8 +6330,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get statsNoSessionsForDate =>- 'No listening sessions found for this day';+ String get statsNoSessionsForDate => 'No listening sessions found for this day';@overrideString get statsSearchSessions => 'Search sessions';@@ -6488,8 +6345,7 @@ class AppLocalizationsZh extends AppLocalizations {String get sessionDeleteConfirmTitle => 'Delete session?';@override- String get sessionDeleteConfirmBody =>- 'This removes the session and lowers your listening totals by its time. It cannot be undone.';+ String get sessionDeleteConfirmBody => 'This removes the session and lowers your listening totals by its time. It cannot be undone.';@overrideString get sessionSaved => 'Session updated';@@ -6558,14 +6414,7 @@ class AppLocalizationsZh extends AppLocalizations {String get statsScreenPmLabel => 'PM';@override- String statsScreenDateAtTime(- String month,- int day,- int year,- int hour,- String minute,- String ampm,- ) {+ String statsScreenDateAtTime(String month, int day, int year, int hour, String minute, String ampm) {return '$month $day, $year at $hour:$minute $ampm';}@@ -6713,12 +6562,10 @@ class AppLocalizationsZh extends AppLocalizations {String get upcomingReleasesScanSettingsTitle => 'Scan settings';@override- String get upcomingReleasesFinishedAfterTitle =>- 'Consider a series finished after';+ String get upcomingReleasesFinishedAfterTitle => 'Consider a series finished after';@override- String get upcomingReleasesFinishedAfterDesc =>- 'Series whose last book is older than this are skipped during scans and only re-checked every month or two.';+ String get upcomingReleasesFinishedAfterDesc => 'Series whose last book is older than this are skipped during scans and only re-checked every month or two.';@overrideString upcomingReleasesFinishedAfterYears(int count) {@@ -6764,8 +6611,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get upcomingReleasesSkippedUnmatched =>- 'Couldn\'t match this series on Audible';+ String get upcomingReleasesSkippedUnmatched => 'Couldn\'t match this series on Audible';@overrideString get upcomingReleasesSkippedScanNow => 'Scan now';@@ -6787,8 +6633,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get upcomingReleasesSkippedOtherLibrary =>- 'This list came from a different library. Run a rescan to refresh it.';+ String get upcomingReleasesSkippedOtherLibrary => 'This list came from a different library. Run a rescan to refresh it.';@overrideString get upcomingReleasesChipUpcoming => 'Upcoming';@@ -6815,19 +6660,16 @@ class AppLocalizationsZh extends AppLocalizations {String get upcomingReleasesScanUpcomingOption => 'Upcoming releases';@override- String get upcomingReleasesScanUpcomingOptionDesc =>- 'Quick scan for new and upcoming books';+ String get upcomingReleasesScanUpcomingOptionDesc => 'Quick scan for new and upcoming books';@overrideString get upcomingReleasesScanDeepOption => 'Deep scan';@override- String get upcomingReleasesScanDeepOptionDesc =>- 'Also finds missing books in every series - takes longer';+ String get upcomingReleasesScanDeepOptionDesc => 'Also finds missing books in every series - takes longer';@override- String get upcomingReleasesFirstScanNote =>- 'The first scan checks every series on Audible and can take a few minutes. Later scans get much quicker once your series are sorted.';+ String get upcomingReleasesFirstScanNote => 'The first scan checks every series on Audible and can take a few minutes. Later scans get much quicker once your series are sorted.';@overrideString get upcomingReleasesLastScanReport => 'Last scan report';@@ -6858,11 +6700,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String upcomingReleasesReportFoundDeep(- int upcoming,- int recent,- int missing,- ) {+ String upcomingReleasesReportFoundDeep(int upcoming, int recent, int missing) {return 'Found $upcoming upcoming, $recent recent, $missing missing';}@@ -6884,8 +6722,7 @@ class AppLocalizationsZh extends AppLocalizations {String get upcomingReleasesSetSeriesAsin => 'Set series ASIN';@override- String get upcomingReleasesSetAsinInstructions =>- 'Find the series on audible.com and copy the page link - the ASIN is the 10-character code starting with B0 (like B08S2YN3YS). Pasting the whole link works too.';+ String get upcomingReleasesSetAsinInstructions => 'Find the series on audible.com and copy the page link - the ASIN is the 10-character code starting with B0 (like B08S2YN3YS). Pasting the whole link works too.';@overrideString get upcomingReleasesSetAsinHint => 'B0… or audible.com link';@@ -6914,20 +6751,16 @@ class AppLocalizationsZh extends AppLocalizations {String get upcomingReleasesRemoveThisScan => 'Remove from this scan';@override- String get upcomingReleasesRemoveThisScanDesc =>- 'Can come back on a future scan';+ String get upcomingReleasesRemoveThisScanDesc => 'Can come back on a future scan';@override- String get upcomingReleasesRemoveForever =>- 'Remove from this and future scans';+ String get upcomingReleasesRemoveForever => 'Remove from this and future scans';@override- String get upcomingReleasesRemoveForeverDesc =>- 'Goes to the removed list, restore any time';+ String get upcomingReleasesRemoveForeverDesc => 'Goes to the removed list, restore any time';@override- String get upcomingReleasesRemovedForeverToast =>- 'Removed - won\'t show on future scans';+ String get upcomingReleasesRemovedForeverToast => 'Removed - won\'t show on future scans';@overrideString get upcomingReleasesRemovedBooksTitle => 'Removed books';@@ -6953,8 +6786,7 @@ class AppLocalizationsZh extends AppLocalizations {String get upcomingReleasesRestoredToast => 'Restored';@override- String get upcomingReleasesRestoredNextScan =>- 'Restored - it will show after the next scan';+ String get upcomingReleasesRestoredNextScan => 'Restored - it will show after the next scan';@overrideString upcomingReleasesSelectedCount(int count) {@@ -7077,8 +6909,7 @@ class AppLocalizationsZh extends AppLocalizations {String get smartScopeNew => 'New Smart Scope';@override- String get smartScopeNewSubtitle =>- 'Save a set of filters as a list that keeps itself up to date';+ String get smartScopeNewSubtitle => 'Save a set of filters as a list that keeps itself up to date';@overrideString get smartScopeEditTitle => 'Edit Smart Scope';@@ -7162,8 +6993,7 @@ class AppLocalizationsZh extends AppLocalizations {String get smartScopeLoadFailed => 'Couldn\'t load the Smart Scope';@override- String get smartScopeUnsupportedRule =>- 'This rule can only be changed on the BookOrbit web. It\'s kept as it is.';+ String get smartScopeUnsupportedRule => 'This rule can only be changed on the BookOrbit web. It\'s kept as it is.';@overrideString get smartScopeAnd => 'and';@@ -7441,11 +7271,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String audibleSeriesSummaryWithUpcoming(- int total,- int missing,- int upcoming,- ) {+ String audibleSeriesSummaryWithUpcoming(int total, int missing, int upcoming) {return '$total on Audible · $missing missing · $upcoming upcoming';}@@ -7594,8 +7420,7 @@ class AppLocalizationsZh extends AppLocalizations {String get librarySortFilterUpcomingReleases => '即将发布';@override- String get librarySortFilterMatchAllAuthorsSubtitle =>- 'Fetch a photo and bio for every author from the metadata provider';+ String get librarySortFilterMatchAllAuthorsSubtitle => 'Fetch a photo and bio for every author from the metadata provider';@overrideString get librarySortFilterUpcomingReleasesSubtitle => 'Audible 中检查系列新书';@@ -7810,8 +7635,7 @@ class AppLocalizationsZh extends AppLocalizations {String get tipsSheetCoverPlayPauseTitle => '点击封面播放/暂停';@override- String get tipsSheetCoverPlayPauseDesc =>- '点击任意卡片的封面即可播放或暂停。可在设置的“收听卡片”中切换此功能。播放时会显示淡淡的暂停图标,提示封面可点击。';+ String get tipsSheetCoverPlayPauseDesc => '点击任意卡片的封面即可播放或暂停。可在设置的“收听卡片”中切换此功能。播放时会显示淡淡的暂停图标,提示封面可点击。';@overrideString get tipsSheetFullScreenPlayerTitle => '全屏播放器';@@ -7823,92 +7647,79 @@ class AppLocalizationsZh extends AppLocalizations {String get tipsSheetQuickAddAbsorbingTitle => '快速加入收听卡片';@override- String get tipsSheetQuickAddAbsorbingDesc =>- '在列表页(系列、作者、搜索结果)中向右滑动任意书籍,即可将其立即加入收听队列。';+ String get tipsSheetQuickAddAbsorbingDesc => '在列表页(系列、作者、搜索结果)中向右滑动任意书籍,即可将其立即加入收听队列。';@overrideString get tipsSheetShakeExtendSleepTitle => '摇一摇延长睡眠定时';@override- String get tipsSheetShakeExtendSleepDesc =>- '如果睡眠定时器正在运行,摇动手机即可延长时间。可在设置中的“睡眠定时器”调整延长的分钟数。';+ String get tipsSheetShakeExtendSleepDesc => '如果睡眠定时器正在运行,摇动手机即可延长时间。可在设置中的“睡眠定时器”调整延长的分钟数。';@overrideString get tipsSheetSeriesNavigationTitle => '系列导航';@override- String get tipsSheetSeriesNavigationDesc =>- '在任意书籍的详情弹窗中点击系列名称,即可查看该系列的所有书籍,并按阅读顺序排序,每本书的封面都会显示序号徽章。';+ String get tipsSheetSeriesNavigationDesc => '在任意书籍的详情弹窗中点击系列名称,即可查看该系列的所有书籍,并按阅读顺序排序,每本书的封面都会显示序号徽章。';@overrideString get tipsSheetSwipeBetweenBooksTitle => '滑动切换书籍';@override- String get tipsSheetSwipeBetweenBooksDesc =>- '在收听界面左右滑动即可切换你正在收听的书籍。开启手动队列模式后,卡片也会作为你的队列使用,因此当前书籍播放结束时会自动播放下一本。';+ String get tipsSheetSwipeBetweenBooksDesc => '在收听界面左右滑动即可切换你正在收听的书籍。开启手动队列模式后,卡片也会作为你的队列使用,因此当前书籍播放结束时会自动播放下一本。';@overrideString get tipsSheetTapToSeekTitle => '点击跳转';@override- String get tipsSheetTapToSeekDesc =>- '点击章节或书籍进度条的任意位置即可直接跳转到对应进度。你也可以拖动进度条以进行更精细的控制。';+ String get tipsSheetTapToSeekDesc => '点击章节或书籍进度条的任意位置即可直接跳转到对应进度。你也可以拖动进度条以进行更精细的控制。';@overrideString get tipsSheetSpeedAdjustedTimeTitle => '实际播放时长';@override- String get tipsSheetSpeedAdjustedTimeDesc =>- '剩余时间和章节时长会根据你的播放速度自动调整。用 1.5×倍播放?界面显示的时间就是你实际需要的时长。';+ String get tipsSheetSpeedAdjustedTimeDesc => '剩余时间和章节时长会根据你的播放速度自动调整。用 1.5×倍播放?界面显示的时间就是你实际需要的时长。';@overrideString get tipsSheetPlaybackHistoryTitle => '播放历史';@override- String get tipsSheetPlaybackHistoryDesc =>- '点击任意卡片上的历史按钮即可查看所有播放、暂停、跳转和倍速调整的时间线。点击任意事件即可跳回对应位置。';+ String get tipsSheetPlaybackHistoryDesc => '点击任意卡片上的历史按钮即可查看所有播放、暂停、跳转和倍速调整的时间线。点击任意事件即可跳回对应位置。';@overrideString get tipsSheetAutoRewindTitle => '自动回退';@override- String get tipsSheetAutoRewindDesc =>- '暂停后恢复播放时,Absorb 会自动回退几秒,确保你不会错过内容。回退时长会根据你离开的时间自动调整。你可以在设置中进行修改。';+ String get tipsSheetAutoRewindDesc => '暂停后恢复播放时,Absorb 会自动回退几秒,确保你不会错过内容。回退时长会根据你离开的时间自动调整。你可以在设置中进行修改。';@overrideString get tipsSheetSeriesQueueModeTitle => '系列连播模式';@override- String get tipsSheetSeriesQueueModeDesc =>- '当你听完某个系列中的一本书时,Absorb 可以自动播放下一本书。请在“设置”中将队列模式更改为“系列”。';+ String get tipsSheetSeriesQueueModeDesc => '当你听完某个系列中的一本书时,Absorb 可以自动播放下一本书。请在“设置”中将队列模式更改为“系列”。';@overrideString get tipsSheetOfflineModeTitle => '离线模式';@override- String get tipsSheetOfflineModeDesc =>- '点击“正在收听”界面上的同步图标即可进入离线模式。这将暂停同步并节省流量,且仅显示你已下载的书籍。非常适合在飞机上或信号较弱的区域使用。';+ String get tipsSheetOfflineModeDesc => '点击“正在收听”界面上的同步图标即可进入离线模式。这将暂停同步并节省流量,且仅显示你已下载的书籍。非常适合在飞机上或信号较弱的区域使用。';@overrideString get tipsSheetUpcomingReleasesTitle => '即将上架';@override- String get tipsSheetUpcomingReleasesDesc =>- '在“系列”标签页中,再次点击该标签即可打开其排序与筛选面板,然后选择“即将上架”,即可按出版日期查看当前系列中已推出和即将推出的新书。';+ String get tipsSheetUpcomingReleasesDesc => '在“系列”标签页中,再次点击该标签即可打开其排序与筛选面板,然后选择“即将上架”,即可按出版日期查看当前系列中已推出和即将推出的新书。';@overrideString get tipsSheetPerBookEqTitle => '为每本书单独配置均衡器';@override- String get tipsSheetPerBookEqDesc =>- 'Each book remembers its own equalizer settings. Tweak EQ once for a sci-fi epic and the next time you play it, it sounds the same.';+ String get tipsSheetPerBookEqDesc => 'Each book remembers its own equalizer settings. Tweak EQ once for a sci-fi epic and the next time you play it, it sounds the same.';@overrideString get tipsSheetPerBookSpeedTitle => '针对单本有声书的语速设置';@override- String get tipsSheetPerBookSpeedDesc =>- '播放速度支持书籍单独配置。非虚构内容 1.5x 效率拉满,有声剧 1.0x 原汁原味,省去频繁调整的麻烦。';+ String get tipsSheetPerBookSpeedDesc => '播放速度支持书籍单独配置。非虚构内容 1.5x 效率拉满,有声剧 1.0x 原汁原味,省去频繁调整的麻烦。';@overrideString get tipsSheetAutoSleepWindowTitle => '自动睡眠时间段';@@ -7920,8 +7731,7 @@ class AppLocalizationsZh extends AppLocalizations {String get tipsSheetSleepFadeChimeTitle => '睡眠淡出与提示音';@override- String get tipsSheetSleepFadeChimeDesc =>- '睡眠定时结束时,音频将逐渐淡出并伴有可选提示音,避免在听书时突然中断。';+ String get tipsSheetSleepFadeChimeDesc => '睡眠定时结束时,音频将逐渐淡出并伴有可选提示音,避免在听书时突然中断。';@overrideString get tipsSheetCarModeTitle => '车载模式';@@ -7933,65 +7743,55 @@ class AppLocalizationsZh extends AppLocalizations {String get tipsSheetAudibleSeriesTitle => '获取 Audible 系列信息';@override- String get tipsSheetAudibleSeriesDesc =>- '打开任意系列,点击右上角的“更多”图标(三个点),即可从 Audible 获取完整的系列清单,包含缺失以及您尚未开始阅读的书籍。';+ String get tipsSheetAudibleSeriesDesc => '打开任意系列,点击右上角的“更多”图标(三个点),即可从 Audible 获取完整的系列清单,包含缺失以及您尚未开始阅读的书籍。';@overrideString get tipsSheetTranscribeBookmarkTitle => 'Transcribe Bookmarks';@override- String get tipsSheetTranscribeBookmarkDesc =>- 'Turn the audio at any bookmark into text, fully on your device. Enable it in Settings under Advanced > Transcription and download a model, then tap Transcribe on a bookmark - the text lands in its note, ready to fix up or share.';+ String get tipsSheetTranscribeBookmarkDesc => 'Turn the audio at any bookmark into text, fully on your device. Enable it in Settings under Advanced > Transcription and download a model, then tap Transcribe on a bookmark - the text lands in its note, ready to fix up or share.';@override- String get tipsSheetFindBetweenFormatsTitle =>- 'Jump Between Audiobook and Ebook';+ String get tipsSheetFindBetweenFormatsTitle => 'Jump Between Audiobook and Ebook';@override- String get tipsSheetFindBetweenFormatsDesc =>- 'With transcription on and the book downloaded, pause and tap Find position in ebook on the player to open the ebook at the passage you just heard. In the reader, select some text and tap the headphones to start the audiobook right there.';+ String get tipsSheetFindBetweenFormatsDesc => 'With transcription on and the book downloaded, pause and tap Find position in ebook on the player to open the ebook at the passage you just heard. In the reader, select some text and tap the headphones to start the audiobook right there.';@overrideString get tipsSheetShareQuoteTitle => 'Share Quotes';@override- String get tipsSheetShareQuoteDesc =>- 'Share an ebook highlight or a bookmark note as an image with the quote over the book cover. Look for the share option on highlights and in the bookmark sheet.';+ String get tipsSheetShareQuoteDesc => 'Share an ebook highlight or a bookmark note as an image with the quote over the book cover. Look for the share option on highlights and in the bookmark sheet.';@overrideString get tipsSheetClipExportTitle => 'Export Audio Clips';@override- String get tipsSheetClipExportDesc =>- 'Open a bookmark and tap Export clip to trim and save a short audio snippet of the book, cover art included - great for sharing a favorite scene.';+ String get tipsSheetClipExportDesc => 'Open a bookmark and tap Export clip to trim and save a short audio snippet of the book, cover art included - great for sharing a favorite scene.';@overrideString get tipsSheetAllHighlightsTitle => 'All Highlights in One Place';@override- String get tipsSheetAllHighlightsDesc =>- 'The All Bookmarks page has a Highlights tab collecting every ebook highlight from every book. Tap one to share it or jump back into the book.';+ String get tipsSheetAllHighlightsDesc => 'The All Bookmarks page has a Highlights tab collecting every ebook highlight from every book. Tap one to share it or jump back into the book.';@overrideString get tipsSheetVolumeKeyPagesTitle => 'Volume-Key Page Turns';@override- String get tipsSheetVolumeKeyPagesDesc =>- 'Turn ebook pages with the volume keys. Enable it in the reader\'s settings - normal or mirrored direction, and it can stay on even while audio is playing.';+ String get tipsSheetVolumeKeyPagesDesc => 'Turn ebook pages with the volume keys. Enable it in the reader\'s settings - normal or mirrored direction, and it can stay on even while audio is playing.';@overrideString get tipsSheetSettingsSyncTitle => 'Settings Sync';@override- String get tipsSheetSettingsSyncDesc =>- 'Keep your settings, per-book speeds and Absorbing order in step across devices through your own WebDAV server. Set it up in Settings under Backup and sync.';+ String get tipsSheetSettingsSyncDesc => 'Keep your settings, per-book speeds and Absorbing order in step across devices through your own WebDAV server. Set it up in Settings under Backup and sync.';@overrideString get tipsSheetNavLongPressTitle => 'Long-Press the Bottom Tabs';@override- String get tipsSheetNavLongPressDesc =>- 'Hold the Home tab to switch libraries from any page. Hold the Library tab to jump straight into search.';+ String get tipsSheetNavLongPressDesc => 'Hold the Home tab to switch libraries from any page. Hold the Library tab to jump straight into search.';@overrideString get bookCardUnknownTitle => 'Unknown Title';@@ -8144,8 +7944,7 @@ class AppLocalizationsZh extends AppLocalizations {String get authInvalidApiKey => 'Invalid API key';@override- String get authLoginFailedDetail =>- 'Login failed - check your server address and credentials';+ String get authLoginFailedDetail => 'Login failed - check your server address and credentials';@overrideString get authUnexpectedServerResponse => 'Unexpected server response';@@ -8256,15 +8055,13 @@ class AppLocalizationsZh extends AppLocalizations {String get downloadNotifProgressChannelName => 'Download Progress';@override- String get downloadNotifProgressChannelDesc =>- 'Shows progress during audiobook downloads';+ String get downloadNotifProgressChannelDesc => 'Shows progress during audiobook downloads';@overrideString get downloadNotifAlertChannelName => 'Download Alerts';@override- String get downloadNotifAlertChannelDesc =>- 'Notifications when downloads finish or fail';+ String get downloadNotifAlertChannelDesc => 'Notifications when downloads finish or fail';@overrideString get downloadNotifDownloadingTitle => 'Downloading…';@@ -8312,11 +8109,7 @@ class AppLocalizationsZh extends AppLocalizations {String get upcomingNotifStartingScan => 'Starting scan…';@override- String upcomingNotifCheckingSeries(- String seriesName,- int current,- int total,- ) {+ String upcomingNotifCheckingSeries(String seriesName, int current, int total) {return 'Checking $seriesName… ($current/$total)';}@@ -8356,12 +8149,10 @@ class AppLocalizationsZh extends AppLocalizations {String get carConnectAutoplayIos => 'Start playback when CarPlay connects';@override- String get carConnectAutoplayOnSubtitle =>- 'The last book you were listening to starts by itself when the car connects';+ String get carConnectAutoplayOnSubtitle => 'The last book you were listening to starts by itself when the car connects';@override- String get carConnectAutoplayOffSubtitle =>- 'Playback waits for you to press play';+ String get carConnectAutoplayOffSubtitle => 'Playback waits for you to press play';@overrideString get sectionCar => 'Android Auto';@@ -8369,6 +8160,36 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get sectionCarIos => 'CarPlay';+ @override+ String get sectionSiri => 'Siri';++ @override+ String get siriUseWithSiri => 'Use with Siri';++ @override+ String get siriStatusOn => 'On. Siri can find and play your books and podcasts by name.';++ @override+ String get siriStatusAsk => 'Let Siri find and play your books and podcasts by name.';++ @override+ String get siriStatusOff => 'Siri is turned off for Absorb. Turn it on in iOS Settings.';++ @override+ String get siriAllow => 'Allow';++ @override+ String get siriOpenSettings => 'Open Settings';++ @override+ String get siriThingsToSay => 'Things to say';++ @override+ String get siriExamples => '\"Play [book title] on Absorb\"\n\"Play [series name] on Absorb\"\n\"Play something by [author] on Absorb\"\n\"Play the latest episode of [podcast] on Absorb\"\n\"Resume Absorb\"\n\"Skip back in Absorb\"\n\"Next chapter in Absorb\"\n\"Set a sleep timer in Absorb\"\n\"Add a bookmark in Absorb\"\n\"What am I listening to in Absorb\"';++ @override+ String get siriShortcutsNote => 'Resume, pause, skips, chapters, the sleep timer, bookmarks and what\'s playing work even without this permission. They are also in the Shortcuts app for automations and the Action button.';+@overrideString get carBookOrder => 'Book order in the car';@@ -8385,8 +8206,7 @@ class AppLocalizationsZh extends AppLocalizations {String get carEpisodesOldestFirst => 'Oldest episodes first';@override- String get carEpisodesOldestFirstSubtitle =>- 'For shows you listen to from the start';+ String get carEpisodesOldestFirstSubtitle => 'For shows you listen to from the start';@overrideString get androidAutoCatBooks => 'Books';@@ -8437,8 +8257,7 @@ class AppLocalizationsZh extends AppLocalizations {String get authorRemoveImageTitle => 'Remove author image?';@override- String get authorRemoveImageConfirm =>- 'This deletes the image on the server.';+ String get authorRemoveImageConfirm => 'This deletes the image on the server.';@overrideString get authorImageRemoved => 'Image removed';@@ -8464,8 +8283,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get authorQuickMatchHint =>- 'Pull name, ASIN, description and image from Audible for the chosen region.';+ String get authorQuickMatchHint => 'Pull name, ASIN, description and image from Audible for the chosen region.';@overrideString get region => 'Region';@@ -8492,8 +8310,7 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterErrorFirstNotZero => 'First chapter must start at 0:00';@override- String get chapterErrorStartAfterPrevious =>- 'Start must come after the previous chapter';+ String get chapterErrorStartAfterPrevious => 'Start must come after the previous chapter';@overrideString get chapterErrorStartBeforeEnd => 'Start must be before the book ends';@@ -8568,8 +8385,7 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterRemoveAllTitle => 'Remove all chapters?';@override- String get chapterRemoveAllMessage =>- 'This removes every chapter from this book.';+ String get chapterRemoveAllMessage => 'This removes every chapter from this book.';@overrideString get chapterAllRemoved => 'All chapters removed';@@ -8628,8 +8444,7 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterFindStartWider => 'Search wider';@override- String get chapterFindStartCeiling =>- 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';+ String get chapterFindStartCeiling => 'Searched half an hour around the marker. The start is further off than that, or there\'s no chapter announcement to hear.';@overrideString get chapterFindStartStrong => 'Sounds like this chapter';@@ -8648,8 +8463,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get chapterFindStartNeedsModel =>- 'Turn on transcription in Settings and download a model first';+ String get chapterFindStartNeedsModel => 'Turn on transcription in Settings and download a model first';@overrideString get chapterFindStartUseThis => 'Use this';@@ -8663,8 +8477,7 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterShiftBySeconds => 'Shift by (seconds)';@override- String get chapterShiftHint =>- 'Shifts every unlocked chapter. Use a negative value to move them earlier.';+ String get chapterShiftHint => 'Shifts every unlocked chapter. Use a negative value to move them earlier.';@overrideString get chapterTitleHint => 'Chapter title';@@ -8696,8 +8509,7 @@ class AppLocalizationsZh extends AppLocalizations {String get chapterFindTitle => 'Find chapters';@override- String get chapterFindSubtitle =>- 'Looks up chapters from Audible/Audnexus by ASIN.';+ String get chapterFindSubtitle => 'Looks up chapters from Audible/Audnexus by ASIN.';@overrideString get chapterEnterAsin => 'Enter an ASIN';@@ -8722,12 +8534,10 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get chapterAudibleLonger =>- 'The Audible version is longer than your file - later chapters may not line up.';+ String get chapterAudibleLonger => 'The Audible version is longer than your file - later chapters may not line up.';@override- String get chapterAudibleShorter =>- 'The Audible version is shorter than your file - chapters may not line up.';+ String get chapterAudibleShorter => 'The Audible version is shorter than your file - chapters may not line up.';@overrideString get chapterTitlesOnly => 'Titles only';@@ -8739,8 +8549,7 @@ class AppLocalizationsZh extends AppLocalizations {String get coverSearchTitle => 'Search for a cover';@override- String get coverSearchRefineHint =>- 'Refine the title/author to clean up results - this does not change the book.';+ String get coverSearchRefineHint => 'Refine the title/author to clean up results - this does not change the book.';@overrideString get coverNoneFound => 'No covers found';@@ -8761,23 +8570,19 @@ class AppLocalizationsZh extends AppLocalizations {String get coverUnknownResolution => 'Unknown resolution';@override- String get embedIntro =>- 'Embed metadata into audio files including cover image and chapters.';+ String get embedIntro => 'Embed metadata into audio files including cover image and chapters.';@overrideString get embedBackupOption => 'Back up audio files first';@override- String get embedNoteInFolder =>- 'Metadata will be embedded in the audio tracks inside your audiobook folder.';+ String get embedNoteInFolder => 'Metadata will be embedded in the audio tracks inside your audiobook folder.';@override- String get embedNoteMultiTrack =>- 'Chapters are not embedded in multi-track audiobooks.';+ String get embedNoteMultiTrack => 'Chapters are not embedded in multi-track audiobooks.';@override- String get embedNoteNavigateAway =>- 'Once the task is started you can navigate away from this page.';+ String get embedNoteNavigateAway => 'Once the task is started you can navigate away from this page.';@overrideString get embedStartButton => 'Start Metadata Embed';@@ -8799,8 +8604,7 @@ class AppLocalizationsZh extends AppLocalizations {String get taskStarting => 'Starting...';@override- String get embedBackupNoteIntro =>- 'A backup of your original audio files will be stored on the server in ';+ String get embedBackupNoteIntro => 'A backup of your original audio files will be stored on the server in ';@overrideString embedBackupNotePath(String itemId) {@@ -8808,8 +8612,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get embedBackupNoteOutro =>- '. Make sure to periodically purge the items cache.';+ String get embedBackupNoteOutro => '. Make sure to periodically purge the items cache.';@overrideString get embedDialogTitle => 'Embed metadata';@@ -8900,8 +8703,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminApiKeysTokenLabel => 'Your new API key';@override- String get adminApiKeysCopyWarning =>- 'Copy this key now. For security it won\'t be shown again.';+ String get adminApiKeysCopyWarning => 'Copy this key now. For security it won\'t be shown again.';@overrideString get adminApiKeysCopy => 'Copy';@@ -8940,8 +8742,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminApiKeysEmpty => 'No API keys yet';@override- String get adminApiKeysEmptySub =>- 'Create one to let apps and scripts reach your server';+ String get adminApiKeysEmptySub => 'Create one to let apps and scripts reach your server';@overrideString get adminApiKeysNeverUsed => 'Never used';@@ -9030,15 +8831,13 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get clipExportClamped =>- 'Clip saved, shortened to the end of this track';+ String get clipExportClamped => 'Clip saved, shortened to the end of this track';@overrideString get clipExportFailed => 'Couldn\'t export the clip.';@override- String get clipDownloadToExport =>- 'Download this book first to export a clip on iPhone.';+ String get clipDownloadToExport => 'Download this book first to export a clip on iPhone.';@overrideString get fsPickerTitle => 'Select folder';@@ -9065,8 +8864,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminUploadSubtitle => 'Add books and podcasts from files';@override- String get adminUploadNoLibraries =>- 'Create a library before uploading media.';+ String get adminUploadNoLibraries => 'Create a library before uploading media.';@overrideString get adminUploadDestination => 'Destination';@@ -9084,8 +8882,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminUploadAutoMetadata => 'Auto-fetch metadata';@override- String get adminUploadAutoMetadataSubtitle =>- 'Fill title, author and series from the best match';+ String get adminUploadAutoMetadataSubtitle => 'Fill title, author and series from the best match';@overrideString get adminUploadMetadataProvider => 'Metadata provider';@@ -9094,12 +8891,10 @@ class AppLocalizationsZh extends AppLocalizations {String get adminUploadMetadataSearching => 'Searching for metadata...';@override- String get adminUploadMetadataNoResults =>- 'No metadata match found. You can still upload this item.';+ String get adminUploadMetadataNoResults => 'No metadata match found. You can still upload this item.';@override- String get adminUploadMetadataFailed =>- 'Couldn\'t search for metadata. You can still upload this item.';+ String get adminUploadMetadataFailed => 'Couldn\'t search for metadata. You can still upload this item.';@overrideString get adminUploadDestinationPreview => 'Server destination';@@ -9125,20 +8920,16 @@ class AppLocalizationsZh extends AppLocalizations {String get adminUploadAddFiles => 'Add files';@override- String get adminUploadBookFilesHint =>- 'Choose audio or ebook files. You can also include covers and metadata files.';+ String get adminUploadBookFilesHint => 'Choose audio or ebook files. You can also include covers and metadata files.';@override- String get adminUploadPodcastFilesHint =>- 'Choose one or more audio files. You can also include covers and metadata files.';+ String get adminUploadPodcastFilesHint => 'Choose one or more audio files. You can also include covers and metadata files.';@override- String get adminUploadUnsupportedFiles =>- 'Some selected files are not supported by Audiobookshelf.';+ String get adminUploadUnsupportedFiles => 'Some selected files are not supported by Audiobookshelf.';@override- String get adminUploadFilePickerFailed =>- 'Couldn\'t open the selected files.';+ String get adminUploadFilePickerFailed => 'Couldn\'t open the selected files.';@overrideString get adminUploadTitleRequired => 'Enter a title';@@ -9153,20 +8944,16 @@ class AppLocalizationsZh extends AppLocalizations {String get adminUploadFilesRequired => 'Choose at least one file';@override- String get adminUploadPodcastFileRequired =>- 'Choose at least one audio file for this podcast.';+ String get adminUploadPodcastFileRequired => 'Choose at least one audio file for this podcast.';@override- String get adminUploadBookFileRequired =>- 'Choose at least one audio or ebook file for this book.';+ String get adminUploadBookFileRequired => 'Choose at least one audio or ebook file for this book.';@override- String get adminUploadPathCheckFailed =>- 'Couldn\'t check the destination folder. Nothing was uploaded.';+ String get adminUploadPathCheckFailed => 'Couldn\'t check the destination folder. Nothing was uploaded.';@override- String get adminUploadDestinationExists =>- 'That destination folder already exists on the server.';+ String get adminUploadDestinationExists => 'That destination folder already exists on the server.';@overrideString adminUploadDestinationUsedBy(String title) {@@ -9182,8 +8969,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get adminUploadAddToExistingNoItem =>- 'That folder already exists on the server. Add the files to it?';+ String get adminUploadAddToExistingNoItem => 'That folder already exists on the server. Add the files to it?';@overrideString get adminUploadAddToBook => 'Add to an existing book';@@ -9205,8 +8991,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get adminUploadTargetNoFolder =>- 'Couldn\'t find that book\'s folder on the server.';+ String get adminUploadTargetNoFolder => 'Couldn\'t find that book\'s folder on the server.';@overrideString adminUploadTargetFolderMismatch(String preview, String folder) {@@ -9238,8 +9023,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get adminUploadReselectFiles =>- 'Choose the files again before retrying.';+ String get adminUploadReselectFiles => 'Choose the files again before retrying.';@overrideString get adminServerSettings => 'Server settings';@@ -9251,8 +9035,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminAuthentication => 'Authentication';@override- String get adminAuthenticationSubtitle =>- 'Password and OpenID Connect sign-in';+ String get adminAuthenticationSubtitle => 'Password and OpenID Connect sign-in';@overrideString get adminStats => 'Statistics';@@ -9264,8 +9047,7 @@ class AppLocalizationsZh extends AppLocalizations {String get adminAllSessions => 'All sessions';@override- String get adminAllSessionsSubtitle =>- 'View and manage all listening sessions';+ String get adminAllSessionsSubtitle => 'View and manage all listening sessions';@overrideString get adminSessionsAllUsers => 'All users';@@ -9448,8 +9230,7 @@ class AppLocalizationsZh extends AppLocalizations {String get authSetRedirectUris => 'Allowed mobile redirect URIs';@override- String get authSetRedirectUrisInfo =>- 'Apps can only return to these addresses after sign-in. Absorb uses absorb://oauth. An asterisk (*) as the only entry allows any address.';+ String get authSetRedirectUrisInfo => 'Apps can only return to these addresses after sign-in. Absorb uses absorb://oauth. An asterisk (*) as the only entry allows any address.';@overrideString get authSetAddRedirectUri => 'Add URI';@@ -9464,8 +9245,7 @@ class AppLocalizationsZh extends AppLocalizations {String get authSetSubfolderNone => 'None';@override- String get authSetWebRedirectInfo =>- 'Allow these URLs in your OAuth provider so sign-in can return to the web app:';+ String get authSetWebRedirectInfo => 'Allow these URLs in your OAuth provider so sign-in can return to the web app:';@overrideString get authSetButtonText => 'Button text';@@ -9483,44 +9263,37 @@ class AppLocalizationsZh extends AppLocalizations {String get authSetMatchUsername => 'Username';@override- String get authSetMatchExistingInfo =>- 'Used to link existing users. Once linked, users are matched by their unique ID from the provider.';+ String get authSetMatchExistingInfo => 'Used to link existing users. Once linked, users are matched by their unique ID from the provider.';@overrideString get authSetAutoLaunch => 'Auto launch';@override- String get authSetAutoLaunchInfo =>- 'Open the provider automatically from the web login page. /login?autoLaunch=0 skips it.';+ String get authSetAutoLaunchInfo => 'Open the provider automatically from the web login page. /login?autoLaunch=0 skips it.';@overrideString get authSetAutoRegister => 'Auto register';@override- String get authSetAutoRegisterInfo =>- 'Create new users automatically after they sign in';+ String get authSetAutoRegisterInfo => 'Create new users automatically after they sign in';@override- String get authSetClaimsInfo =>- 'Leave these empty to turn off group and permission assignment. New users then get the User role.';+ String get authSetClaimsInfo => 'Leave these empty to turn off group and permission assignment. New users then get the User role.';@overrideString get authSetGroupClaim => 'Group claim';@override- String get authSetGroupClaimInfo =>- 'Claim that lists the user\'s groups, usually groups. Groups named admin, user or guest set the role, and the highest one wins. If no group matches, sign-in is refused.';+ String get authSetGroupClaimInfo => 'Claim that lists the user\'s groups, usually groups. Groups named admin, user or guest set the role, and the highest one wins. If no group matches, sign-in is refused.';@overrideString get authSetPermsClaim => 'Advanced permission claim';@override- String get authSetPermsClaimInfo =>- 'Claim with permissions for non-admin users. If the claim is missing, sign-in is refused, and a missing option counts as off. Expected format:';+ String get authSetPermsClaimInfo => 'Claim with permissions for non-admin users. If the claim is missing, sign-in is refused, and a missing option counts as off. Expected format:';@override- String get authSetRestartNote =>- 'Restart the server after saving to apply OpenID Connect changes.';+ String get authSetRestartNote => 'Restart the server after saving to apply OpenID Connect changes.';@overrideString get authSetNoChanges => 'No changes to save';@@ -9539,8 +9312,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get authSetAsteriskAlone =>- 'An asterisk (*) must be the only redirect URI';+ String get authSetAsteriskAlone => 'An asterisk (*) must be the only redirect URI';@overrideString authSetInvalidClaim(String field) {@@ -9562,8 +9334,7 @@ class AppLocalizationsZh extends AppLocalizations {String get libDeleteTitle => 'Delete library?';@override- String get libDeleteBody =>- 'This permanently removes the library and all of its items from the server.';+ String get libDeleteBody => 'This permanently removes the library and all of its items from the server.';@overrideString get libDeleted => 'Library deleted';@@ -9685,8 +9456,7 @@ class AppLocalizationsZh extends AppLocalizations {String get libRemoveFoldersTitle => 'Remove folders?';@override- String get libRemoveFoldersBody =>- 'Removing a folder deletes its items from the library. This can\'t be undone.';+ String get libRemoveFoldersBody => 'Removing a folder deletes its items from the library. This can\'t be undone.';@overrideString get readEbook => 'Read';@@ -9713,16 +9483,13 @@ class AppLocalizationsZh extends AppLocalizations {String get ebookSaveToDeviceTitle => 'Save to device?';@override- String get ebookSaveToDeviceBody =>- 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+ String get ebookSaveToDeviceBody => 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';@override- String get readerFormatUnsupported =>- 'This ebook format can\'t be opened in the reader yet';+ String get readerFormatUnsupported => 'This ebook format can\'t be opened in the reader yet';@override- String get readerCouldNotOpen =>- 'This ebook couldn\'t be opened. The file may be damaged.';+ String get readerCouldNotOpen => 'This ebook couldn\'t be opened. The file may be damaged.';@overrideString get moreActions => 'More';@@ -9761,22 +9528,31 @@ class AppLocalizationsZh extends AppLocalizations {String get readerPinTopBar => 'Keep the title and progress bar on screen';@override- String get readerPinTopBarHint =>- 'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';+ String get readerPinTopBarHint => 'Pins them above the page instead of showing them on tap. The page gets a little shorter so no text is covered.';++ @override+ String get readerTopBarProgress => 'Top bar progress';++ @override+ String get readerTopBarProgressBook => 'Book';++ @override+ String get readerTopBarProgressChapter => 'Chapter';++ @override+ String get readerTopBarProgressBoth => 'Both';@overrideString get readerScrollMode => 'Scroll mode';@override- String get readerScrollModeHint =>- 'Scroll down through the book instead of turning pages. Applies to every book.';+ String get readerScrollModeHint => 'Scroll down through the book instead of turning pages. Applies to every book.';@overrideString get readerKeepAwake => 'Keep the screen on';@override- String get readerKeepAwakeHint =>- 'Stops the screen timing out while you read at your own pace. Auto scroll and read along always keep it on.';+ String get readerKeepAwakeHint => 'Stops the screen timing out while you read at your own pace. Auto scroll and read along always keep it on.';@overrideString get readerLayoutAuto => 'Auto';@@ -9809,8 +9585,7 @@ class AppLocalizationsZh extends AppLocalizations {String get readerAutoScroll => 'Auto scroll';@override- String get readerAutoScrollSubtitle =>- 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';+ String get readerAutoScrollSubtitle => 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';@overrideString get readerAutoScrollStarted => 'Auto scroll started';@@ -9839,8 +9614,7 @@ class AppLocalizationsZh extends AppLocalizations {String get readerAutoScrollSleep => 'Auto scroll sleep timer';@override- String get readerAutoScrollSleepHint =>- 'Stops the scrolling after a while and lets the screen go dark.';+ String get readerAutoScrollSleepHint => 'Stops the scrolling after a while and lets the screen go dark.';@overrideString readerAutoScrollSleepMinutes(int minutes) {@@ -9958,6 +9732,30 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get readerNoHighlights => 'No highlights yet';+ @override+ String get readerHistory => 'History';++ @override+ String get sessionReading => 'Reading';++ @override+ String get readerHistoryEmpty => 'Pages you leave are listed here, so you can always get back to them.';++ @override+ String get readerHistoryClosed => 'Closed the book';++ @override+ String get readerHistoryBeforeJump => 'Before a jump';++ @override+ String get readerHistoryBeforeSync => 'Before matching the audio';++ @override+ String get readerLogReading => 'Count reading time in stats';++ @override+ String get readerLogReadingHint => 'Logs your time in the reader as a session so it shows in your stats. On Audiobookshelf it counts as listening time.';+@overrideString get readerNoBookmarks => 'No bookmarks yet';@@ -9974,22 +9772,19 @@ class AppLocalizationsZh extends AppLocalizations {String get backupAndSync => 'Backup and sync';@override- String get backupAndSyncSubtitle =>- 'Save a backup file, or keep settings in step across devices';+ String get backupAndSyncSubtitle => 'Save a backup file, or keep settings in step across devices';@overrideString get syncSettingsExperimental => 'Experimental';@override- String get syncSettingsExperimentalBody =>- 'Sync is new and still being worked on. If two devices change things while they are apart, one side can lose its changes. Keep a backup file as your safe copy.';+ String get syncSettingsExperimentalBody => 'Sync is new and still being worked on. If two devices change things while they are apart, one side can lose its changes. Keep a backup file as your safe copy.';@overrideString get syncSettingsNeedServer => 'Need a server?';@override- String get syncSettingsNeedServerSub =>- 'Any WebDAV server works. Nextcloud is a free self-hosted one.';+ String get syncSettingsNeedServerSub => 'Any WebDAV server works. Nextcloud is a free self-hosted one.';@overrideString get syncSettingsConnection => 'Connection';@@ -10001,12 +9796,10 @@ class AppLocalizationsZh extends AppLocalizations {String get syncSettingsBackupFile => 'Backup file';@override- String get syncSettingsBackupFilePlain =>- 'Save everything to a file you keep.';+ String get syncSettingsBackupFilePlain => 'Save everything to a file you keep.';@override- String get syncSettingsBackupFileWithSync =>- 'Save everything to a file you keep. Include login info and restoring it on another phone turns sync on there too.';+ String get syncSettingsBackupFileWithSync => 'Save everything to a file you keep. Include login info and restoring it on another phone turns sync on there too.';@overrideString get syncSettingsStatusOff => 'Not syncing';@@ -10024,12 +9817,10 @@ class AppLocalizationsZh extends AppLocalizations {String get syncSettingsIncludeRmab => 'ReadMeABook settings';@override- String get syncSettingsIncludeRmabSub =>- 'Puts your ReadMeABook API token in the synced file';+ String get syncSettingsIncludeRmabSub => 'Puts your ReadMeABook API token in the synced file';@override- String get syncSettingsSubtitle =>- 'Keep your settings in step through your own WebDAV server';+ String get syncSettingsSubtitle => 'Keep your settings in step through your own WebDAV server';@overrideString get syncSettingsEnable => 'Sync settings';@@ -10038,8 +9829,7 @@ class AppLocalizationsZh extends AppLocalizations {String get syncSettingsServerUrl => 'WebDAV folder URL';@override- String get syncSettingsServerUrlHint =>- 'https://cloud.example.com/remote.php/dav/files/you/Absorb';+ String get syncSettingsServerUrlHint => 'https://cloud.example.com/remote.php/dav/files/you/Absorb';@overrideString get syncSettingsUsername => 'Username';@@ -10051,8 +9841,7 @@ class AppLocalizationsZh extends AppLocalizations {String get syncSettingsHeaders => 'Custom headers (optional)';@override- String get syncSettingsHeadersHint =>- 'One per line, like CF-Access-Client-Id: abc123';+ String get syncSettingsHeadersHint => 'One per line, like CF-Access-Client-Id: abc123';@overrideString get syncSettingsTest => 'Test connection';@@ -10079,8 +9868,7 @@ class AppLocalizationsZh extends AppLocalizations {String get syncSettingsNetworkError => 'Could not reach that address';@override- String get syncSettingsNotConfigured =>- 'Fill in the address, username and password first';+ String get syncSettingsNotConfigured => 'Fill in the address, username and password first';@overrideString get syncSettingsTooLarge => 'Your settings are too big to sync';@@ -10119,8 +9907,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get navHoldPickBody =>- 'Choose what a long press on this tab does. You can change it later in Settings.';+ String get navHoldPickBody => 'Choose what a long press on this tab does. You can change it later in Settings.';@overrideString get navHoldSettingTitle => 'Tab hold shortcuts';@@ -10216,8 +10003,7 @@ class AppLocalizationsZh extends AppLocalizations {String get bookStatsNobody => 'Nobody has started this yet';@override- String get bookStatsScanning =>- 'Scanning through sessions, this could take a while...';+ String get bookStatsScanning => 'Scanning through sessions, this could take a while...';@overrideString bookStatsScanningCount(int done, int total) {@@ -10267,8 +10053,7 @@ class AppLocalizationsZh extends AppLocalizations {String get syncSourceTitle => 'Which copy should sync keep?';@override- String get syncSourceBody =>- 'This backup turned settings sync on. Use the server\'s last sync, or make this backup the source of truth? Choosing the backup replaces the copy on the server for all your synced devices.';+ String get syncSourceBody => 'This backup turned settings sync on. Use the server\'s last sync, or make this backup the source of truth? Choosing the backup replaces the copy on the server for all your synced devices.';@overrideString get syncSourceUseServer => 'Server\'s last sync';@@ -10277,16 +10062,13 @@ class AppLocalizationsZh extends AppLocalizations {String get syncSourceUseBackup => 'This backup';@override- String get syncSettingsWhatTravels =>- 'Your preferences, per-book speeds, home layout, Absorbing order, notes and ebook highlights travel. Logins, download folders, auto-download switches, reader looks and anything not yet sent to your server stay on this device.';+ String get syncSettingsWhatTravels => 'Your preferences, per-book speeds, home layout, Absorbing order, notes and ebook highlights travel. Logins, download folders, auto-download switches, reader looks and anything not yet sent to your server stay on this device.';@override- String get syncSettingsDownloadWarnTitle =>- 'Replace this device\'s settings?';+ String get syncSettingsDownloadWarnTitle => 'Replace this device\'s settings?';@override- String get syncSettingsDownloadWarnBody =>- 'The synced copy will overwrite the settings on this device.';+ String get syncSettingsDownloadWarnBody => 'The synced copy will overwrite the settings on this device.';@overrideString get syncSettingsDownloadWarnConfirm => 'Replace';@@ -10298,8 +10080,7 @@ class AppLocalizationsZh extends AppLocalizations {String get dictionaryNotFound => 'No definition found for this word.';@override- String get dictionaryError =>- 'Couldn\'t reach the dictionary. Check your connection.';+ String get dictionaryError => 'Couldn\'t reach the dictionary. Check your connection.';@overrideString get dictionaryRetry => 'Retry';@@ -10342,23 +10123,19 @@ class AppLocalizationsZh extends AppLocalizations {String get transcriptionTitle => 'Transcription';@override- String get transcriptionAdvancedSubtitle =>- 'For transcribing bookmarks and finding your spot between audiobook and ebook';+ String get transcriptionAdvancedSubtitle => 'For transcribing bookmarks and finding your spot between audiobook and ebook';@overrideString get transcriptionEnable => 'Enable transcription';@override- String get transcriptionEnableSubtitle =>- 'Adds Transcribe to bookmarks, Find position in ebook to the player, and Find in audiobook to the reader';+ String get transcriptionEnableSubtitle => 'Adds Transcribe to bookmarks, Find position in ebook to the player, and Find in audiobook to the reader';@override- String get transcriptionDisclaimer =>- 'Runs entirely on your device, nothing is sent anywhere. It uses extra battery and processing while it works, and only downloaded books can be transcribed.';+ String get transcriptionDisclaimer => 'Runs entirely on your device, nothing is sent anywhere. It uses extra battery and processing while it works, and only downloaded books can be transcribed.';@override- String get transcriptionNeedModelHint =>- 'Download a model below to start transcribing.';+ String get transcriptionNeedModelHint => 'Download a model below to start transcribing.';@overrideString get transcriptionModelSection => 'Models';@@ -10367,8 +10144,7 @@ class AppLocalizationsZh extends AppLocalizations {String get transcriptionModelTiny => 'Tiny';@override- String get transcriptionModelTinyDesc =>- 'Quickest, less accurate. About 31 MB.';+ String get transcriptionModelTinyDesc => 'Quickest, less accurate. About 31 MB.';@overrideString get transcriptionModelBase => 'Base';@@ -10380,19 +10156,16 @@ class AppLocalizationsZh extends AppLocalizations {String get transcriptionModelSmall => 'Small';@override- String get transcriptionModelSmallDesc =>- 'Slower but most accurate - best on a high-end phone. About 182 MB.';+ String get transcriptionModelSmallDesc => 'Slower but most accurate - best on a high-end phone. About 182 MB.';@override- String get transcriptionAutoHint =>- 'With more than one downloaded, each job picks between them. Books with an ebook get the quickest one, since the exact words come from the ebook anyway. Books without one get the most accurate - except read along, which stays below Small so it can keep up with the narration.';+ String get transcriptionAutoHint => 'With more than one downloaded, each job picks between them. Books with an ebook get the quickest one, since the exact words come from the ebook anyway. Books without one get the most accurate - except read along, which stays below Small so it can keep up with the narration.';@overrideString get transcriptionDownload => 'Download';@override- String get transcriptionDownloadFailed =>- 'Download failed. Check your connection and try again.';+ String get transcriptionDownloadFailed => 'Download failed. Check your connection and try again.';@overrideString get transcribe => 'Transcribe';@@ -10410,31 +10183,25 @@ class AppLocalizationsZh extends AppLocalizations {String get transcriptionSavedToNote => 'Saved to bookmark note';@override- String get transcriptionDisabledHint =>- 'Turn on bookmark transcription in Settings, under Advanced.';+ String get transcriptionDisabledHint => 'Turn on bookmark transcription in Settings, under Advanced.';@override- String get transcriptionNoModelDownloaded =>- 'Download a transcription model in Settings first.';+ String get transcriptionNoModelDownloaded => 'Download a transcription model in Settings first.';@override- String get transcriptionNotDownloadedBook =>- 'Download this book or connect to your server to transcribe it.';+ String get transcriptionNotDownloadedBook => 'Download this book or connect to your server to transcribe it.';@override- String get transcriptionNoMetadataMsg =>- 'Can\'t locate this spot in the download. Try re-downloading the book.';+ String get transcriptionNoMetadataMsg => 'Can\'t locate this spot in the download. Try re-downloading the book.';@override- String get transcriptionBusyMsg =>- 'Already transcribing something. Give it a moment.';+ String get transcriptionBusyMsg => 'Already transcribing something. Give it a moment.';@overrideString get transcriptionEmptyMsg => 'No speech was found at this spot.';@override- String get transcriptionFailedMsg =>- 'Couldn\'t transcribe this spot. Please try again.';+ String get transcriptionFailedMsg => 'Couldn\'t transcribe this spot. Please try again.';@overrideString get transcriptionPlaySnippet => 'Listen';@@ -10443,12 +10210,10 @@ class AppLocalizationsZh extends AppLocalizations {String get transcriptionPauseSnippet => 'Pause';@override- String get transcriptionIntroBody =>- 'This listens to the chosen amount of audio, starting just before the bookmark, and turns it into text on your device. Longer clips take longer, and transcription isn\'t 100% accurate. The text is saved into the bookmark\'s note when it\'s done, ready to fix up or share.';+ String get transcriptionIntroBody => 'This listens to the chosen amount of audio, starting just before the bookmark, and turns it into text on your device. Longer clips take longer, and transcription isn\'t 100% accurate. The text is saved into the bookmark\'s note when it\'s done, ready to fix up or share.';@override- String get transcriptionUseEbookText =>- 'Use the ebook\'s exact text when it can be matched';+ String get transcriptionUseEbookText => 'Use the ebook\'s exact text when it can be matched';@overrideString get lyricsMode => 'Live transcript';@@ -10469,12 +10234,10 @@ class AppLocalizationsZh extends AppLocalizations {String get lyricsFullCover => 'Use the whole cover';@override- String get lyricsFullCoverHint =>- 'Shows the transcript in place of the artwork while it runs, fitting as many lines as there is room for.';+ String get lyricsFullCoverHint => 'Shows the transcript in place of the artwork while it runs, fitting as many lines as there is room for.';@override- String get lyricsBatteryInfo =>- 'Live transcript and read along use extra battery and processing while they run. On phones with slower processors, lines can take longer to appear.';+ String get lyricsBatteryInfo => 'Live transcript and read along use extra battery and processing while they run. On phones with slower processors, lines can take longer to appear.';@overrideString get lyricsClearCache => 'Clear transcript cache';@@ -10485,15 +10248,13 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get lyricsClearCacheConfirm =>- 'Delete the saved transcripts for every book and episode? They rebuild automatically as you listen.';+ String get lyricsClearCacheConfirm => 'Delete the saved transcripts for every book and episode? They rebuild automatically as you listen.';@overrideString get lyricsCacheCleared => 'Transcript cache cleared';@override- String get lyricsIntroBody =>- 'This listens a little ahead of the narration and shows each line as it is spoken, transcribed on your phone - nothing leaves the device. After turning it on, hold off on pressing play for a few seconds while it gets ahead. The transcript appears once its head start is ready, and starting paused gives it the smoothest run. It uses extra battery and processing while it runs.';+ String get lyricsIntroBody => 'This listens a little ahead of the narration and shows each line as it is spoken, transcribed on your phone - nothing leaves the device. After turning it on, hold off on pressing play for a few seconds while it gets ahead. The transcript appears once its head start is ready, and starting paused gives it the smoothest run. It uses extra battery and processing while it runs.';@overrideString lyricsBuildingLead(String percent) {@@ -10515,19 +10276,71 @@ class AppLocalizationsZh extends AppLocalizations {String get readAlongNeedsPlaying => 'Play this book\'s audiobook first';@override- String get transcriptionNeedsDownload =>- 'This needs the audio on your phone. Download it now?';+ String get narrationListen => 'Listen';++ @override+ String get narrationPlayFromHere => 'Play from here';++ @override+ String get narrationPreparing => 'Getting the narration ready';++ @override+ String get narrationNone => 'This ebook has no narration to play';++ @override+ String get narrationDownloadTitle => 'Download to listen';++ @override+ String get narrationDownloadBody => 'This book is an EPUB3 that reads itself aloud. Audiobookshelf can\'t stream its narration, so the audio needs to be downloaded before it plays.';++ @override+ String get narrationDownloadStarted => 'Downloading the narration. Tap Absorb when it finishes.';++ @override+ String get narrationUpNextTitle => 'Download what\'s up next';++ @override+ String narrationUpNextBody(String title) {+ return '$title is next in your queue. It\'s an EPUB3 that reads itself aloud, so it needs to be downloaded before it can play.';+ }++ @override+ String narrationQueueStopped(String title) {+ return 'Stopped before $title. Download it to keep going.';+ }++ @override+ String get transcriptionNeedsDownload => 'This needs the audio on your phone. Download it now?';@override- String get transcriptionDownloadStarted =>- 'Downloading. Turn this on again when it finishes';+ String get transcriptionDownloadStarted => 'Downloading. Turn this on again when it finishes';@overrideString get readAlongFollow => 'Read along follows';@override- String get readAlongFollowHint =>- 'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';+ String get syncReadingListening => 'Keep reading and listening in sync';++ @override+ String get syncReadingListeningHint => 'For books with an audiobook and an ebook. When you stop listening, the ebook moves to where you stopped. When you leave the reader, the audiobook moves to your page. Only moves forward.';++ @override+ String get syncEbookMoved => 'Ebook moved to where you stopped listening';++ @override+ String get syncAudioMoved => 'Audiobook moved to where you stopped reading';++ @override+ String get syncAudioOffer => 'Tap to jump to where you stopped reading';++ @override+ String get syncFindingAudio => 'Finding your page in the audiobook';++ @override+ String get syncFindingEbook => 'Finding your spot in the ebook';++ @override+ String get readAlongFollowHint => 'Word timing is worked out between the transcript\'s timestamps, so it can drift slightly inside a sentence.';@overrideString get readAlongFollowWord => 'Word';@@ -10563,31 +10376,25 @@ class AppLocalizationsZh extends AppLocalizations {String get findInAudiobook => 'Find in audiobook';@override- String get findInAudiobookSearching =>- 'Finding this spot in the audiobook...';+ String get findInAudiobookSearching => 'Finding this spot in the audiobook...';@override- String get findInAudiobookStillSearching =>- 'Still searching the audio for this spot...';+ String get findInAudiobookStillSearching => 'Still searching the audio for this spot...';@override- String get findInAudiobookSearchingLong =>- 'Long chapter, still searching. This can take a minute or two...';+ String get findInAudiobookSearchingLong => 'Long chapter, still searching. This can take a minute or two...';@override- String get findInAudiobookNotFound =>- 'Couldn\'t find this spot in the audiobook.';+ String get findInAudiobookNotFound => 'Couldn\'t find this spot in the audiobook.';@override- String get transcriptionWhisperInfo =>- 'Transcription is powered by Whisper, an open speech recognition model that listens to the narration and writes out the words - all on this device.';+ String get transcriptionWhisperInfo => 'Transcription is powered by Whisper, an open speech recognition model that listens to the narration and writes out the words - all on this device.';@overrideString get transcriptionWhisperLearnMore => 'Learn more about Whisper';@override- String get findInAudiobookIntroBody =>- 'This listens to the audiobook near where you\'re reading and matches it to this passage, all on your device. It can take up to a minute. If the spot can\'t be matched confidently, nothing moves.';+ String get findInAudiobookIntroBody => 'This listens to the audiobook near where you\'re reading and matches it to this passage, all on your device. It can take up to a minute. If the spot can\'t be matched confidently, nothing moves.';@overrideString get findInAudiobookAfterLabel => 'When the spot is found';@@ -10602,12 +10409,10 @@ class AppLocalizationsZh extends AppLocalizations {String get findInAudiobookPlaying => 'Playing this passage in the audiobook';@override- String get catchUpAudioAhead =>- 'The audiobook is further along. Tap to go there.';+ String get catchUpAudioAhead => 'The audiobook is further along. Tap to go there.';@override- String get catchUpPageAhead =>- 'This page is ahead of the audiobook. Tap to move the audiobook here.';+ String get catchUpPageAhead => 'This page is ahead of the audiobook. Tap to move the audiobook here.';@overrideString get readerShortcutButton => 'Shortcut button';@@ -10619,66 +10424,55 @@ class AppLocalizationsZh extends AppLocalizations {String get keepScreenOnActive => 'Screen stays on';@override- String get keepScreenOnUntilClosed =>- 'Screen stays on until you close the app';+ String get keepScreenOnUntilClosed => 'Screen stays on until you close the app';@overrideString get keepScreenOnOff => 'Screen can turn off again';@override- String get keepScreenOnOffUntilRestart =>- 'Off until the app restarts. The Settings switch stays on';+ String get keepScreenOnOffUntilRestart => 'Off until the app restarts. The Settings switch stays on';@overrideString get keepScreenOnPlayer => 'Keep the screen on in the player';@override- String get keepScreenOnPlayerSubtitle =>- 'The screen stays on while the player is open';+ String get keepScreenOnPlayerSubtitle => 'The screen stays on while the player is open';@overrideString get keepScreenOnCarMode => 'Keep the screen on in car mode';@override- String get keepScreenOnCarModeSubtitle =>- 'The screen stays on while car mode is open';+ String get keepScreenOnCarModeSubtitle => 'The screen stays on while car mode is open';@overrideString get loginServerType => 'Server type';@override- String get authBookOrbitDefaultPassword =>- 'This account still has its default password. Change it in BookOrbit, then sign in again.';+ String get authBookOrbitDefaultPassword => 'This account still has its default password. Change it in BookOrbit, then sign in again.';@override- String get authBookOrbitPasswordOff =>- 'Password sign-in is turned off on this server. Sign in with a magic link or single sign-on.';+ String get authBookOrbitPasswordOff => 'Password sign-in is turned off on this server. Sign in with a magic link or single sign-on.';@override- String get authServerIsBookOrbit =>- 'This is a BookOrbit server. Choose BookOrbit above the server address.';+ String get authServerIsBookOrbit => 'This is a BookOrbit server. Choose BookOrbit above the server address.';@override- String get authServerIsAudiobookshelf =>- 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';+ String get authServerIsAudiobookshelf => 'This is an Audiobookshelf server. Choose Audiobookshelf above the server address.';@override- String get castNotAvailableBookOrbit =>- 'Casting is not available with BookOrbit servers';+ String get castNotAvailableBookOrbit => 'Casting is not available with BookOrbit servers';@overrideString get loginMagicLink => 'Magic link';@override- String get loginMagicLinkDescription =>- 'Sign in with a BookOrbit magic link instead of a password.';+ String get loginMagicLinkDescription => 'Sign in with a BookOrbit magic link instead of a password.';@overrideString get collectionPublicTitle => 'Public';@override- String get collectionPublicSubtitle =>- 'Everyone on this server can see this collection';+ String get collectionPublicSubtitle => 'Everyone on this server can see this collection';@overrideString loginSignInWithProvider(String provider) {@@ -10692,15 +10486,13 @@ class AppLocalizationsZh extends AppLocalizations {String get loginChooseSsoProvider => 'Choose how to sign in';@override- String get loginRedirectUriBookOrbit =>- 'Redirect URI: bookorbit://oauth2-callback';+ String get loginRedirectUriBookOrbit => 'Redirect URI: bookorbit://oauth2-callback';@overrideString get readStatusTitle => 'Reading status';@override- String get readStatusHint =>- 'BookOrbit keeps a status you pick here until you change it.';+ String get readStatusHint => 'BookOrbit keeps a status you pick here until you change it.';@overrideString get readStatusUnread => 'Unread';@@ -10748,8 +10540,7 @@ class AppLocalizationsZh extends AppLocalizations {String get cardButtonFill => 'Button background';@override- String get cardButtonFillSubtitle =>- 'How the buttons on the player card are filled';+ String get cardButtonFillSubtitle => 'How the buttons on the player card are filled';@overrideString get cardButtonFillClear => 'Clear';@@ -10761,15 +10552,13 @@ class AppLocalizationsZh extends AppLocalizations {String get cardButtonFillSolid => 'Solid';@override- String get loginBookOrbitPreview =>- 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';+ String get loginBookOrbitPreview => 'BookOrbit support is new. Playback, downloads and browsing work, but some screens may still look or act like Audiobookshelf. Follow the progress on GitHub, and let us know if something seems off.';@overrideString get signedOutTapToSignIn => 'Signed out. Tap to sign in again.';@override- String get authSignedOutKeepListening =>- 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';+ String get authSignedOutKeepListening => 'You\'ve been signed out. Downloads still play. Tap the red cloud to sign in again.';@overrideString signedOutSyncNote(String username, String server) {@@ -10785,8 +10574,7 @@ class AppLocalizationsZh extends AppLocalizations {}@override- String get comicBookmarkRemoveFailed =>- 'Couldn\'t remove the bookmark from the server. Try again when you\'re online.';+ String get comicBookmarkRemoveFailed => 'Couldn\'t remove the bookmark from the server. Try again when you\'re online.';@overrideString get comicLeftToRight => 'Left to right';@@ -10795,8 +10583,7 @@ class AppLocalizationsZh extends AppLocalizations {String get comicRightToLeft => 'Right to left (manga)';@override- String get comicNeedsConnection =>- 'This comic opens page by page from your server, so it needs a connection.';+ String get comicNeedsConnection => 'This comic opens page by page from your server, so it needs a connection.';@overrideString get comicNoPages => 'No pages found in this comic.';diff --git a/lib/main.dart b/lib/main.dartindex ad1e6ed7..c26de5e6 100644--- a/lib/main.dart+++ b/lib/main.dart@@ -34,6 +34,9 @@ import 'services/carplay_service.dart';import 'services/chromecast_service.dart';import 'services/episode_notification_service.dart';import 'services/home_widget_service.dart';+import 'services/siri_service.dart';+import 'services/narrated_books.dart';+import 'services/read_listen_sync.dart';import 'services/log_service.dart';import 'services/quick_actions_service.dart';import 'services/setup_link_service.dart';@@ -204,6 +207,10 @@ Future<void> applyOrientationLock() async {void main() async {HttpOverrides.global = _CertOverrides();final widgetsBinding = WidgetsFlutterBinding.ensureInitialized();+ ReadListenSync.instance.start();+ try {+ await NarratedBooks.load().timeout(const Duration(seconds: 2));+ } catch (_) {}final appLinks = AppLinks();// These calls use platform channels that require an Activity. When Android@@ -832,6 +839,10 @@ class _AuthGateState extends State<AuthGate> {// Initialize homescreen widgetawait HomeWidgetService().init();}+ if (Platform.isIOS) {+ // Siri requests wait on this; a Siri launch reaches it headless.+ await SiriService().init();+ }// App-icon long-press shortcuts. On Android the service registers// dynamic shortcuts + handler; on iOS it only wires the handler since// shortcut items themselves are declared statically in Info.plistdiff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dartindex 55c5a66c..31cbbbab 100644--- a/lib/providers/_lp_absorbing.dart+++ b/lib/providers/_lp_absorbing.dart@@ -959,6 +959,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final title = metadata['title'] as String? ?? '';final author = metadata['authorName'] as String? ?? '';+ if (UpNextNarration.instance.needsDownload(key)) {+ unawaited(UpNextNarration.instance.stopped(key, title));+ return;+ }if (key.length > 36) {final showId = key.substring(0, 36);@@ -1141,6 +1145,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {final nextData = next.value;final media = nextData['media'] as Map<String, dynamic>? ?? {};final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ if (UpNextNarration.instance.needsDownload(nextKey)) {+ unawaited(UpNextNarration.instance.stopped(nextKey, metadata['title'] as String? ?? ''));+ return;+ }debugPrint('[Absorbing] Auto-playing next series book $nextKey after $finishedBookId');AudioPlayerService().playItem(api: _api!,@@ -1513,6 +1521,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {final key = _playlistItemKey(m);if (key.isEmpty) continue;if (self.isItemFinishedByKey(key)) continue;+ if (UpNextNarration.instance.needsDownload(key)) {+ unawaited(UpNextNarration.instance.stopped(key, _playlistItemTitle(m) ?? ''));+ return;+ }final ok = await _playPlaylistItem(m);if (ok) {debugPrint('[AutoAdvance] Playlist advanced to $key (index $i)');@@ -1955,6 +1967,10 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {final key = _playlistItemKey(items[i]);if (key.isEmpty) continue;if (self.isItemFinishedByKey(key)) continue;+ if (UpNextNarration.instance.needsDownload(key)) {+ unawaited(UpNextNarration.instance.stopped(key, _playlistItemTitle(items[i]) ?? ''));+ return;+ }if (await _playPlaylistItem(items[i])) return;}}@@ -2125,7 +2141,12 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {/// Returns a short label describing what would play next given the current/// queue mode and player state, or null when nothing is queued. Used by the/// "Up next: ..." chip under the queue-mode pill on the absorbing page.- Future<String?> peekUpNext({required String? currentItemId}) async {+ Future<String?> peekUpNext({required String? currentItemId}) async =>+ (await upNextEntry(currentItemId: currentItemId))?.title;++ /// What would play next: its key, the chip's label, and the book's own+ /// title. Null when nothing is queued.+ Future<({String key, String title, String bookTitle})?> upNextEntry({required String? currentItemId}) async {final self = this as LibraryProvider;if (currentItemId == null) return null;@@ -2159,8 +2180,8 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {final key = _playlistItemKey(m);if (key.isEmpty) continue;if (self.isItemFinishedByKey(key)) continue;- final title = _playlistItemTitle(m);- return playlistName.isNotEmpty ? '$playlistName - $title' : title;+ final title = _playlistItemTitle(m) ?? '';+ return (key: key, title: playlistName.isNotEmpty ? '$playlistName - $title' : title, bookTitle: title);}return null;}@@ -2181,8 +2202,8 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {final key = _playlistItemKey(items[i]);if (key.isEmpty) continue;if (self.isItemFinishedByKey(key)) continue;- final title = _playlistItemTitle(items[i]);- return name.isNotEmpty ? '$name - $title' : title;+ final title = _playlistItemTitle(items[i]) ?? '';+ return (key: key, title: name.isNotEmpty ? '$name - $title' : title, bookTitle: title);}return null;}@@ -2228,7 +2249,8 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {}}debugPrint('[Queue] peek [$i] $key PICK - ${candidateIsPodcast ? "podcast" : "book"} (lib=${cached['libraryId']})');- return _entryTitle(cached);+ final title = _entryTitle(cached) ?? '';+ return (key: key, title: title, bookTitle: title);}debugPrint('[Queue] peek: no eligible item found');return null;@@ -2236,12 +2258,13 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {// auto_nextif (isPodCurrent) {- return await _peekNextPodcastEpisode(currentItemId);+ final title = await _peekNextPodcastEpisode(currentItemId);+ return title == null ? null : (key: '', title: title, bookTitle: title);}return await _peekNextBookInSeries(currentItemId);}- Future<String?> _peekNextBookInSeries(String currentBookId) async {+ Future<({String key, String title, String bookTitle})?> _peekNextBookInSeries(String currentBookId) async {final self = this as LibraryProvider;var data = _itemDataWithSeries(currentBookId);var (seriesId, currentSeq) =@@ -2311,7 +2334,9 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {'(server list=$usedServerList, finished skipped: ''${skippedFinished.isEmpty ? 'none' : skippedFinished.take(8).join(', ')})');if (candidates.isEmpty) return null;- return _entryTitle(candidates[nextSeq.first]!);+ final next = candidates[nextSeq.first]!;+ final title = _entryTitle(next) ?? '';+ return (key: next['id'] as String? ?? '', title: title, bookTitle: title);}Future<String?> _peekNextPodcastEpisode(String currentCompoundKey) async {diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex d3eb3dcc..c4484c5e 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -1966,6 +1966,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {// Snapshot after injection so a tab flip restores the full shelf set._sectionsByLibrary[_selectedLibraryId!] = _personalizedSections;_sectionsFetchedAt[_selectedLibraryId!] = DateTime.now();+ SiriService().scheduleCatalogUpdate();if (isPodcastLibrary) {_hydrateRssFeedFieldsDeferred();diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex e0c59b4e..0b1da534 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -23,12 +23,14 @@ import '../services/socket_service.dart';import '../services/book_search_index.dart';import '../services/home_widget_service.dart';import '../services/queue_download_policy.dart';+import '../services/siri_service.dart';import '../utils/absorbing_inclusion.dart';import '../l10n/app_localizations.dart';import '../main.dart' show rootNavigatorKey;import '../widgets/overlay_toast.dart';import '../services/ebook_cache.dart';import '../services/screen_wake.dart';+import '../services/up_next_narration.dart';part '_lp_state.dart';part '_lp_core.dart';@@ -48,12 +50,27 @@ class LibraryProvider extends ChangeNotifierif (completer != null && !completer.isCompleted) completer.complete();}+ Iterable<Map<String, dynamic>> _itemsForSiri() sync* {+ yield* _absorbingItemCache.values;+ for (final sections in _sectionsByLibrary.values) {+ for (final section in sections) {+ if (section is! Map) continue;+ for (final e in (section['entities'] as List<dynamic>? ?? const [])) {+ if (e is Map<String, dynamic>) yield e;+ }+ }+ }+ yield* BookSearchIndex().indexedItems;+ }+LibraryProvider() {+ SiriService.libraryItems = _itemsForSiri;// Registered once at provider construction so the audio service can// notify this provider on completion/playback events even when the// Flutter UI wasn't foregrounded yet (e.g. Android Auto cold-start,// where updateAuth may not run until much later).AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);+ AudioPlayerService.onAppPlay = (itemId) => unawaited(UpNextNarration.instance.checkOnPlay(this, itemId));AudioPlayerService.setOnAutoQueueAdvancedCallback((oldItemId) {// Pre-buffer auto-advance already loaded and started the next item.// Mark the old one finished WITHOUT triggering normal auto-advancediff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex eedb7301..7c0517cb 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -12,6 +12,7 @@ import '../providers/library_provider.dart';import '../services/audio_player_service.dart';import '../services/download_service.dart';import '../services/android_auto_service.dart';+import '../services/siri_service.dart';import '../services/episode_notification_service.dart';import '../services/sleep_timer_service.dart';import '../services/user_account_service.dart';@@ -104,6 +105,7 @@ class _SettingsScreenState extends State<SettingsScreen> {bool _carBookSortReverse = false;String _carPodcastSort = 'title';bool _carEpisodesOldestFirst = false;+ String _siriStatus = 'notDetermined';bool _lockSeekBar = false;bool _mp3IndexSeeking = false;bool _speedAdjustedTime = true;@@ -1206,6 +1208,12 @@ class _SettingsScreenState extends State<SettingsScreen> {});final libId = mounted ? context.read<LibraryProvider>().selectedLibraryId : null;if (libId != null) _loadCurrentLibraryOverrides(libId);+ if (Platform.isIOS) _refreshSiriStatus();+ }++ Future<void> _refreshSiriStatus() async {+ final status = await SiriService().authorizationStatus();+ if (mounted) setState(() => _siriStatus = status);}/// (Re)loads the cover-shape + skip overrides for whichever library is@@ -3245,6 +3253,60 @@ class _SettingsScreenState extends State<SettingsScreen> {),const SizedBox(height: 16),+ if (Platform.isIOS) ...[+ // ── Siri ──+ CollapsibleSection(+ key: _keyFor('Siri'),+ icon: Icons.mic_rounded,+ title: l.sectionSiri,+ cs: cs,+ isExpanded: _expandedSection == 'Siri',+ onExpansionChanged: (v) {+ _onSectionExpanded('Siri', v);+ if (v) _refreshSiriStatus();+ },+ children: [+ ListTile(+ title: Text(l.siriUseWithSiri),+ subtitle: Text(+ switch (_siriStatus) {+ 'authorized' => l.siriStatusOn,+ 'denied' || 'restricted' => l.siriStatusOff,+ _ => l.siriStatusAsk,+ },+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ trailing: _siriStatus == 'authorized'+ ? Icon(Icons.check_circle_rounded, color: cs.primary)+ : FilledButton.tonal(+ onPressed: () async {+ if (_siriStatus == 'notDetermined') {+ await SiriService().requestAuthorization();+ } else {+ await SiriService().openSystemSettings();+ }+ await _refreshSiriStatus();+ },+ child: Text(_siriStatus == 'notDetermined'+ ? l.siriAllow+ : l.siriOpenSettings),+ ),+ ),+ const Divider(height: 1, indent: 16, endIndent: 16),+ ListTile(+ title: Text(l.siriThingsToSay),+ subtitle: Text(l.siriExamples,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),+ child: Text(l.siriShortcutsNote,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ ),+ ],+ ),+ const SizedBox(height: 16),+ ],+// ── Sleep Timer ──CollapsibleSection(key: _keyFor('Sleep Timer'),diff --git a/lib/screens/settings_search_index.dart b/lib/screens/settings_search_index.dartindex a5303eb3..22ef27de 100644--- a/lib/screens/settings_search_index.dart+++ b/lib/screens/settings_search_index.dart@@ -87,6 +87,12 @@ List<SettingSearchEntry> settingsSearchEntries(BuildContext context) {SettingSearchEntry('Car', Platform.isIOS ? l.sectionCarIos : l.sectionCar, l.carPodcastOrder, [l.title, l.dateAdded]),SettingSearchEntry('Car', Platform.isIOS ? l.sectionCarIos : l.sectionCar, l.carEpisodesOldestFirst, [l.carEpisodesOldestFirstSubtitle]),+ // ── Siri ──+ if (Platform.isIOS) ...[+ SettingSearchEntry('Siri', l.sectionSiri, l.siriUseWithSiri, [l.siriStatusAsk, 'Shortcuts', 'voice']),+ SettingSearchEntry('Siri', l.sectionSiri, l.siriThingsToSay, [l.siriExamples]),+ ],+// ── Sleep Timer ──SettingSearchEntry('Sleep Timer', l.sectionSleepTimer, l.shakeDuringSleepTimer, [l.shakeOff, l.shakeAddTime, l.shakeReset]),SettingSearchEntry('Sleep Timer', l.sectionSleepTimer, l.shakeSensitivity, [l.shakeSensitivityVeryLow, l.shakeSensitivityLow, l.shakeSensitivityMedium, l.shakeSensitivityHigh, l.shakeSensitivityVeryHigh]),@@ -154,6 +160,6 @@ List<SettingSearchEntry> settingsSearchEntries(BuildContext context) {if (const bool.fromEnvironment('GITHUB_BUILD'))SettingSearchEntry('Advanced', l.sectionAdvanced, l.includePreReleases, [l.includePreReleasesOnSubtitle, l.includePreReleasesOffSubtitle]),SettingSearchEntry('Advanced', l.sectionAdvanced, l.adminRmab, [l.adminRmabConnected, l.adminRmabAskAdmin]),- SettingSearchEntry('Advanced', l.sectionAdvanced, l.transcriptionTitle, [l.transcriptionAdvancedSubtitle]),+ SettingSearchEntry('Advanced', l.sectionAdvanced, l.transcriptionTitle, [l.transcriptionAdvancedSubtitle, l.syncReadingListening]),];}diff --git a/lib/screens/transcription_settings_screen.dart b/lib/screens/transcription_settings_screen.dartindex 71662c62..501392cd 100644--- a/lib/screens/transcription_settings_screen.dart+++ b/lib/screens/transcription_settings_screen.dart@@ -29,6 +29,7 @@ class _TranscriptionSettingsScreenStatedouble _lyricsFontSize = 16;int _lyricsMaxLines = 3;bool _lyricsFullCover = true;+ bool _syncReadingListening = false;String _readAlongMode = 'word';int _readAlongColor = PlayerSettings.defaultReadAlongColor;final Map<TranscriptionModelSize, bool> _downloaded = {};@@ -48,6 +49,7 @@ class _TranscriptionSettingsScreenState_lyricsMaxLines = await PlayerSettings.getLyricsMaxLines();_lyricsFullCover = await PlayerSettings.getLyricsFullCover();_readAlongMode = await PlayerSettings.getReadAlongMode();+ _syncReadingListening = await PlayerSettings.getSyncReadingListening();_readAlongColor = await PlayerSettings.getReadAlongColor();for (final s in TranscriptionModelSize.values) {_downloaded[s] = await TranscriptionService.instance.isModelDownloaded(s);@@ -328,6 +330,17 @@ class _TranscriptionSettingsScreenState},),),+ SwitchListTile(+ title: Text(l.syncReadingListening),+ subtitle: Text(l.syncReadingListeningHint,+ style: tt.bodySmall+ ?.copyWith(color: cs.onSurfaceVariant, height: 1.35)),+ value: _syncReadingListening,+ onChanged: (v) async {+ setState(() => _syncReadingListening = v);+ await PlayerSettings.setSyncReadingListening(v);+ },+ ),ListTile(title: Text(l.readAlongFollow),subtitle: Text(l.readAlongFollowHint,diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dartindex 34de4e20..67c2a0e6 100644--- a/lib/services/android_auto_service.dart+++ b/lib/services/android_auto_service.dart@@ -384,6 +384,9 @@ class AndroidAutoService {/// AndroidAuto uses notifyChildrenChanged below independently.static void Function()? onServerDataChanged;+ /// Further listeners for the same moment (Siri's list of books).+ static final List<void Function()> serverDataListeners = [];+Future<void> refresh({bool force = false}) async {// Always populate downloads immediately — no server needed.// This ensures Android Auto / CarPlay can show the Downloads tab even@@ -455,6 +458,13 @@ class AndroidAutoService {} catch (e) {debugPrint('[AutoBrowse] onServerDataChanged listener threw: $e');}+ for (final listener in serverDataListeners) {+ try {+ listener();+ } catch (e) {+ debugPrint('[AutoBrowse] server data listener threw: $e');+ }+ }}}diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex a1fd555d..084693bf 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -10,6 +10,8 @@ import 'book_dock.dart';import 'book_requests.dart';import 'bookorbit_match.dart';import 'bookorbit_mapper.dart';+import 'media_overlay.dart';+import 'narrated_books.dart';import 'bookorbit_media_proxy_stub.dart'if (dart.library.io) 'bookorbit_media_proxy.dart';import 'player_settings.dart';@@ -365,6 +367,10 @@ class ApiService {String buildEbookUrl(String itemId, String ino) =>'$_cleanBaseUrl/api/items/$itemId/file/$ino?token=$token';+ /// The ebook the reader caches, which may leave out what reading doesn't+ /// need (BookOrbit's narrated EPUBs come without their audio).+ String buildReaderEbookUrl(String itemId, String ino) => buildEbookUrl(itemId, ino);+/// How many pages a comic file has, when the server hands them out one at/// a time (BookOrbit, which opens CBR and CB7 too). Null means the archive/// has to be opened on the phone.@@ -421,6 +427,10 @@ class ApiService {/// Called once before a book's files are queued for download.Future<void> prepareDownload(String itemId) async {}+ /// Where a download fetches a narrated EPUB's audio file from, for track+ /// [contentUrl]; null when this server has no such tracks.+ String? buildNarrationDownloadUrl(String itemId, String contentUrl) => null;+/// Show a collection to everyone on the server or only its owner. Only/// BookOrbit has this; Audiobookshelf collections are always shared.Future<bool> setCollectionPublic(String collectionId, bool isPublic) async => false;@@ -2093,6 +2103,18 @@ class ApiService {'model': deviceModel,};+ /// Time spent reading shows up on the server as its own client: "Absorb+ /// (ebook)" with its own device id, since the server keeps one name per+ /// device id and would otherwise rename this phone's listening too.+ Map<String, dynamic> get _readingDeviceInfo => {+ ..._deviceInfo,+ 'clientName': 'Absorb (ebook)',+ 'deviceId': '$deviceId-ebook',+ };++ /// The media player a reading session is marked with.+ static const readingMediaPlayer = 'ebook-reader';+/// Start a playback session for a library item./// POST /api/items/:id/play/// Returns the full session object including audioTracks with contentUrl.@@ -2282,11 +2304,15 @@ class ApiService {/// [session] is a fully-built session map; deviceInfo/mediaPlayer/playMethod/// are stamped here so they can't be omitted.Future<LocalSessionResult> syncLocalSession(Map<String, dynamic> session) async {+ final reading = session['keepProgress'] == true;+ final kept = await _besideProgress(session);+ if (kept == null) return const LocalSessionResult(ok: false, serverTooOld: false);+ session = kept;try {final body = {...session,- 'deviceInfo': _deviceInfo,- 'mediaPlayer': 'exo-player',+ 'deviceInfo': reading ? _readingDeviceInfo : _deviceInfo,+ 'mediaPlayer': reading ? readingMediaPlayer : 'exo-player','playMethod': 3, // LOCAL};final resp = await _authPost(@@ -2306,7 +2332,18 @@ class ApiService {/// POST /api/session/local-allFuture<LocalSessionResult> syncLocalSessionsAll(List<Map<String, dynamic>> sessions) async {- if (sessions.isEmpty) return const LocalSessionResult(ok: true, serverTooOld: false);+ // Reading time goes one at a time: the batch carries a single device.+ var readingOk = true;+ for (final s in sessions.where((s) => s['keepProgress'] == true)) {+ if (!(await syncLocalSession(s)).ok) readingOk = false;+ }+ final kept = <Map<String, dynamic>>[];+ for (final s in sessions.where((s) => s['keepProgress'] != true)) {+ final k = await _besideProgress(s);+ if (k != null) kept.add(k);+ }+ sessions = kept;+ if (sessions.isEmpty) return LocalSessionResult(ok: readingOk, serverTooOld: false);try {final body = {'sessions': sessions@@ -2319,7 +2356,7 @@ class ApiService {body: jsonEncode(body),timeout: const Duration(seconds: 20));return LocalSessionResult(- ok: resp.statusCode == 200,+ ok: resp.statusCode == 200 && readingOk,serverTooOld: resp.statusCode == 404 || resp.statusCode == 501,);} catch (_) {@@ -2327,6 +2364,103 @@ class ApiService {}}+ /// A phone-made session whose numbers aren't the book's listening position:+ /// an EPUB's narration (the server sizes a new session by the item's own+ /// length, zero for an ebook) or time spent reading (`keepProgress`). The+ /// server copies a session's position onto the progress row unless the+ /// row is newer, so the session is dated just before the row's last save:+ /// the time is logged and the progress is left as it is. Null when there+ /// is no row to keep yet for a reading session.+ Future<Map<String, dynamic>?> _besideProgress(Map<String, dynamic> session) async {+ final reading = session['keepProgress'] == true;+ final out = Map<String, dynamic>.from(session)..remove('keepProgress');+ final id = session['libraryItemId'];+ final narration = id is String ? NarratedBooks.duration(id) : null;+ if (isBookOrbit || id is! String || (!reading && narration == null)) return out;+ var row = await getItemProgress(id);+ if (row == null && reading) debugPrint('[Session] $id: no progress row yet - reading time waits');+ if (row == null && narration != null) {+ try {+ await updateProgress(id,+ currentTime: (session['currentTime'] as num?)?.toDouble() ?? 0, duration: narration);+ } catch (_) {}+ row = await getItemProgress(id);+ }+ final rowAt = (row?['lastUpdate'] as num?)?.toInt();+ if (rowAt == null) return reading ? null : out;+ if (narration != null) out['duration'] = narration;+ final at = (session['updatedAt'] as num?)?.toInt() ?? DateTime.now().millisecondsSinceEpoch;+ if (at >= rowAt) out['updatedAt'] = rowAt - 1000;+ if (_besideLogged.add('${session['id']}')) {+ debugPrint('[Session] $id: ${reading ? 'reading time' : 'narration'} session ${session['id']} '+ 'logged beside the progress row (${at >= rowAt ? 'dated before it' : 'already older'})');+ }+ return out;+ }++ static final Set<String> _besideLogged = {};++ static const _weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];++ /// Time spent reading, as the local listening session Audiobookshelf takes+ /// it in: at the audiobook's current spot ([audioAt], 0 for an ebook with+ /// no audio) and marked to leave the progress as it is.+ static Map<String, dynamic> readingSession(+ String itemId, {+ required String sessionId,+ required DateTime startedAt,+ required int seconds,+ required double audioAt,+ required double audioDuration,+ String? title,+ }) {+ String day(DateTime d) =>+ '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';+ return {+ 'id': sessionId,+ 'libraryItemId': itemId,+ 'episodeId': null,+ 'mediaType': 'book',+ 'displayTitle': title,+ 'duration': audioDuration,+ 'startTime': audioAt,+ 'currentTime': audioAt,+ 'timeListening': seconds,+ 'startedAt': startedAt.millisecondsSinceEpoch,+ 'updatedAt': DateTime.now().millisecondsSinceEpoch,+ 'date': day(startedAt),+ 'dayOfWeek': _weekdays[startedAt.weekday - 1],+ 'keepProgress': true,+ };+ }++ /// Time spent reading [itemId]'s ebook, kept as a session [sessionId] so it+ /// counts in stats (sent again as it grows, the same id each time).+ /// Audiobookshelf has no reading sessions, so it goes in as a listening+ /// session that leaves the listening progress as it is.+ Future<bool> logReadingTime(+ String itemId, {+ required String sessionId,+ required DateTime startedAt,+ required int seconds,+ required double audioAt,+ required double audioDuration,+ String? title,+ double? ebookStart,+ double? ebookEnd,+ }) async {+ final r = await syncLocalSession(readingSession(+ itemId,+ sessionId: sessionId,+ startedAt: startedAt,+ seconds: seconds,+ audioAt: audioAt,+ audioDuration: audioDuration,+ title: title,+ ));+ return r.ok;+ }+/// Edit an existing listening session by re-POSTing it through the local/// upsert. The server honors timeListening, currentTime, and updatedAt (it/// re-derives the session's day from updatedAt); other fields on an existing@@ -2376,6 +2510,12 @@ class ApiService {return null;}+ /// The server's place in an item's ebook, for opening the reader there:+ /// ebookLocation, ebookProgress and, when the server keeps one apart from+ /// listening, ebookUpdatedAt (ms).+ Future<Map<String, dynamic>?> getEbookPosition(String itemId) =>+ getItemProgress(itemId);+Map<String, dynamic>? _progressRecreationBody(Map<String, dynamic> progress, {required int startedAt,@@ -2604,8 +2744,11 @@ class ApiService {if (progressId != null) await deleteMediaProgress(progressId);- // Start session at 0 and close — forces server to update position- final sessionData = await startPlaybackSession(apiItemId, episodeId: episodeId);+ // Start session at 0 and close — forces server to update position. An+ // EPUB's narration has no server audio to open a session on.+ final sessionData = NarratedBooks.contains(apiItemId) && episodeId == null+ ? null+ : await startPlaybackSession(apiItemId, episodeId: episodeId);if (sessionData != null) {final sessionId = sessionData['id'] as String?;if (sessionId != null) {diff --git a/lib/services/audio_file_duration.dart b/lib/services/audio_file_duration.dartnew file mode 100644index 00000000..076d0069--- /dev/null+++ b/lib/services/audio_file_duration.dart@@ -0,0 +1,130 @@+import 'dart:io';+import 'dart:math';+import 'dart:typed_data';++import 'remote_audio_slice.dart';++/// Reads [count] bytes at [offset] of an audio file, wherever it lives.+typedef AudioBytes = Future<Uint8List> Function(int offset, int count);++/// How long an audio file plays, from its headers: exact for MP4/M4A (the+/// movie header) and for an MP3 with a Xing, Info or VBRI frame count,+/// estimated from the bitrate for a plain MP3. Null when it can't tell.+Future<double?> audioFileDuration(String path) async {+ RandomAccessFile? raf;+ try {+ final f = raf = await File(path).open();+ return await audioDuration((offset, count) async {+ await f.setPosition(offset);+ return f.read(count);+ }, await f.length());+ } catch (_) {+ return null;+ } finally {+ await raf?.close();+ }+}++/// [audioFileDuration] for a file of [length] bytes read through [read],+/// such as one inside an EPUB on the server.+Future<double?> audioDuration(AudioBytes read, int length) async {+ try {+ final head = await read(0, min(length, 16));+ if (head.length >= 8 && String.fromCharCodes(head.sublist(4, 8)) == 'ftyp') {+ return await _mp4(read, length);+ }+ return await _mp3(read, length);+ } catch (_) {+ return null;+ }+}++Future<double?> _mp4(AudioBytes read, int length) async {+ Future<({int size, String type, int header})?> box(int at, int limit) async {+ if (at + 8 > limit) return null;+ final h = await read(at, min(16, limit - at));+ if (h.length < 8) return null;+ final d = ByteData.sublistView(h);+ var size = d.getUint32(0);+ var header = 8;+ if (size == 1 && h.length >= 16) {+ size = d.getUint64(8);+ header = 16;+ } else if (size == 0) {+ size = limit - at;+ }+ if (size < header) return null;+ return (size: size, type: String.fromCharCodes(h.sublist(4, 8)), header: header);+ }++ var at = 0;+ while (true) {+ final top = await box(at, length);+ if (top == null) return null;+ if (top.type == 'moov') {+ var child = at + top.header;+ final end = at + top.size;+ while (true) {+ final b = await box(child, end);+ if (b == null) return null;+ if (b.type == 'mvhd') {+ final body = await read(child + b.header, 32);+ final d = ByteData.sublistView(body);+ final v1 = body.isNotEmpty && body[0] == 1;+ if (body.length < (v1 ? 32 : 20)) return null;+ final scale = v1 ? d.getUint32(20) : d.getUint32(12);+ final duration = v1 ? d.getUint64(24) : d.getUint32(16);+ return scale > 0 && duration > 0 ? duration / scale : null;+ }+ child += b.size;+ }+ }+ at += top.size;+ }+}++const _bitratesV1L3 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];+const _bitratesV2L3 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];++Future<double?> _mp3(AudioBytes read, int length) async {+ final id3 = await read(0, min(length, 10));+ final start = Mp3Probe.audioStart(id3);+ if (start >= length) return null;+ final window = await read(start, min(length - start, 16 * 1024));+ final frame = Mp3Probe.firstFrame(window);+ if (frame + 4 > window.length || window[frame] != 0xFF) return null;+ final b1 = window[frame + 1], b2 = window[frame + 2], b3 = window[frame + 3];+ final version = (b1 >> 3) & 3; // 3 = MPEG 1, 2 = MPEG 2, 0 = MPEG 2.5+ if (((b1 >> 1) & 3) != 1 || version == 1) return null; // Layer III only+ final rates = switch (version) {+ 3 => const [44100, 48000, 32000],+ 2 => const [22050, 24000, 16000],+ _ => const [11025, 12000, 8000],+ };+ final srIndex = (b2 >> 2) & 3;+ if (srIndex == 3) return null;+ final sampleRate = rates[srIndex];+ final mpeg1 = version == 3;+ final samplesPerFrame = mpeg1 ? 1152 : 576;+ final mono = (b3 >> 6) == 3;+ final d = ByteData.sublistView(window);++ int? frames;+ final xingAt = frame + 4 + (mpeg1 ? (mono ? 17 : 32) : (mono ? 9 : 17));+ if (xingAt + 12 <= window.length) {+ final tag = String.fromCharCodes(window.sublist(xingAt, xingAt + 4));+ if ((tag == 'Xing' || tag == 'Info') && (d.getUint32(xingAt + 4) & 1) != 0) {+ frames = d.getUint32(xingAt + 8);+ }+ }+ final vbriAt = frame + 4 + 32;+ if (frames == null && vbriAt + 18 <= window.length &&+ String.fromCharCodes(window.sublist(vbriAt, vbriAt + 4)) == 'VBRI') {+ frames = d.getUint32(vbriAt + 14);+ }+ if (frames != null && frames > 0) return frames * samplesPerFrame / sampleRate;++ final kbps = (mpeg1 ? _bitratesV1L3 : _bitratesV2L3)[(b2 >> 4) & 0xF];+ if (kbps <= 0) return null;+ return (length - start - frame) * 8 / (kbps * 1000);+}diff --git a/lib/services/audio_locator.dart b/lib/services/audio_locator.dartnew file mode 100644index 00000000..3c6cc200--- /dev/null+++ b/lib/services/audio_locator.dart@@ -0,0 +1,620 @@+import 'package:flutter/foundation.dart';++import 'api_service.dart';+import 'audio_player_service.dart';+import 'find_in_ebook.dart';+import 'sync_point_store.dart';+import 'transcription_service.dart';+import '../utils/chapter_title_match.dart';++/// What Find in audiobook needs from a book's text: the reader's open pages,+/// or the EPUB file read with no reader open.+abstract class BookTextSource {+ Future<List<String>> spineHrefs();+ String? chapterForHref(String href);+ Future<List<double>> sectionCharCounts(int from, int to);++ /// {s, e, fine} for where [transcript] sits in section [si]'s text.+ Future<Map<String, dynamic>?> locateTranscriptInSection(int si, String transcript);+}++/// Find in audiobook: where a spot in the ebook is in the audio. Anchors on+/// sync points or the matching audio chapter, then transcribes short probes+/// and matches them back into the section's text until one covers the spot.+class AudioLocator {+ AudioLocator(this.itemId, this.text);++ final String itemId;+ final BookTextSource text;++ // Find in audiobook: how much audio each probe transcribes, how many+ // estimate-correct-retry rounds the main anchor gets, and the ceiling once+ // the fallback candidates (player position, book percentage, neighbouring+ // chapters) have taken two rounds each. A probe is roughly ten seconds.+ static const double _probeWindowSeconds = 30.0;+ static const int _maxProbes = 5;+ static const int _maxTotalProbes = 12;+ // Narration pace measured on real books: ~0.07-0.08 s per character. Used+ // when no audio chapter anchors the estimate, and to reject absurd+ // chapter-derived rates (3-second "chapters" exist in the wild).+ static const double _fallbackSecPerChar = 0.075;+ // How far a failed probe shifts the search around the original estimate,+ // at minimum; a long section widens it so the probes spread across it.+ static const double _scanStepSeconds = 90.0;++ /// Where the audiobook should be for the spot in [info] (si, offset,+ /// total, href) and the range it could sit in, from sync points or a+ /// uniquely named audio chapter. Nothing is transcribed.+ Future<({double est, double lo, double hi})?> estimate(Map<String, dynamic> info, ApiService? api) async {+ final si = (info['si'] as num).toInt();+ final offset = (info['offset'] as num).toDouble();+ final total = (info['total'] as num).toDouble();+ if (total <= 0 || offset < 0) return null;+ final audio = await resolveAudioChapters(itemId, api);+ if (audio.duration <= 0) return null;+ final spine = await text.spineHrefs();+ await SyncPointStore.instance.load(+ itemId,+ audioDuration: audio.duration,+ spineLength: spine.isEmpty ? null : spine.length,+ );+ final sync = await _syncPointCandidate(+ si: si,+ offset: offset,+ total: total,+ fallbackRate: _fallbackSecPerChar,+ top: audio.duration);+ if (sync != null) return (est: sync.est, lo: sync.lo, hi: sync.hi);+ // A title that several audio chapters share can't place the page.+ final tocTitle = text.chapterForHref(info['href'] as String? ?? '');+ final named = [+ for (final ch in audio.chapters)+ if (ch is Map<String, dynamic> &&+ chapterTitlesAgree(ch['title'] as String?, tocTitle))+ ch,+ ];+ if (named.length != 1) return null;+ final a =+ _chapterAnchorEstimate(named.first, offset, total, audio.duration);+ return (est: a.est, lo: a.lo, hi: a.hi);+ }++ /// The time in the audiobook for the spot in [info] (si, offset, total,+ /// href, and pct when known), or null when no probe matched it.+ Future<double?> locate(Map<String, dynamic> info, ApiService? api) async {+ final si = (info['si'] as num).toInt();+ final offset = (info['offset'] as num).toDouble();+ final total = (info['total'] as num).toDouble();+ final href = info['href'] as String? ?? '';+ if (total <= 0 || offset < 0) return null;++ final audio = await resolveAudioChapters(itemId, api);+ if (audio.chapters.isEmpty) {+ debugPrint('[FindAudio] no audio chapters');+ return null;+ }+ final spineAll = await text.spineHrefs();+ await SyncPointStore.instance.load(+ itemId,+ audioDuration: audio.duration > 0 ? audio.duration : null,+ spineLength: spineAll.isEmpty ? null : spineAll.length,+ );+ Future<double> remember(double t) async {+ await SyncPointStore.instance.add(+ itemId,+ SyncPoint(t: t, si: si, off: offset, src: 'a'),+ );+ return t;+ }++ // Which audio chapter is this section? That anchors both the initial+ // estimate and the seconds-per-character correction rate. Books whose+ // chapters are plain names (alternating POV) repeat titles, so collect+ // every agreeing audio chapter and pick by occurrence - the 3rd "Sydney"+ // section anchors on the 3rd "Sydney" audio chapter. When the counts+ // don't line up, take the one nearest the selection's position in the+ // book, and keep a runner-up to probe if the first anchor turns out wrong.+ final tocTitle = text.chapterForHref(href);+ final bookEnd = audio.duration > 0 ? audio.duration : double.infinity;+ final pct = (info['pct'] as num?)?.toDouble();+ final agreeing = <Map<String, dynamic>>[];+ for (final ch in audio.chapters) {+ final m = ch as Map<String, dynamic>;+ if (chapterTitlesAgree(m['title'] as String?, tocTitle)) agreeing.add(m);+ }+ Map<String, dynamic>? audioCh;+ Map<String, dynamic>? audioChAlt;+ if (agreeing.length == 1) {+ audioCh = agreeing.first;+ } else if (agreeing.length > 1) {+ // Occurrence counting walks the spine and counts transitions into the+ // title, so a chapter split across several files still counts once and+ // two same-named chapters separated by an unnamed split file count+ // twice.+ final hrefs = await text.spineHrefs();+ var occurrence = 0;+ String? prev;+ for (var i = 0; i <= si && i < hrefs.length; i++) {+ final t = text.chapterForHref(hrefs[i]);+ if (t == tocTitle && prev != tocTitle) occurrence++;+ prev = t;+ }+ final targetFrac = (pct != null && pct > 0)+ ? pct+ : (hrefs.isNotEmpty ? si / hrefs.length : 0.5);+ double fracOf(Map<String, dynamic> m) {+ final s = (m['start'] as num?)?.toDouble() ?? 0;+ final e = (m['end'] as num?)?.toDouble() ?? s;+ return audio.duration > 0 ? ((s + e) / 2) / audio.duration : 0;+ }+ final byFrac = List<Map<String, dynamic>>.from(agreeing)+ ..sort((x, y) => (fracOf(x) - targetFrac)+ .abs()+ .compareTo((fracOf(y) - targetFrac).abs()));+ final picked = (occurrence >= 1 && occurrence <= agreeing.length)+ ? agreeing[occurrence - 1]+ : byFrac.first;+ audioCh = picked;+ for (final m in byFrac) {+ if (!identical(m, picked)) {+ audioChAlt = m;+ break;+ }+ }+ debugPrint('[FindAudio] "$tocTitle" matches ${agreeing.length} audio '+ 'chapters, occurrence #$occurrence -> '+ '"${picked['title']}"@${((picked['start'] as num?)?.toDouble() ?? 0).toStringAsFixed(0)}s'+ '${audioChAlt != null ? ', runner-up @${((audioChAlt['start'] as num?)?.toDouble() ?? 0).toStringAsFixed(0)}s' : ''}');+ }++ double lo, hi, rate;+ double est;+ var anchorRate = double.nan;+ if (audioCh != null) {+ final a = _chapterAnchorEstimate(audioCh, offset, total, bookEnd);+ lo = a.lo;+ hi = a.hi;+ rate = a.rate;+ est = a.est;+ final chStart = (audioCh['start'] as num?)?.toDouble() ?? 0;+ final chEnd = (audioCh['end'] as num?)?.toDouble() ?? bookEnd;+ anchorRate = (chEnd - chStart) / total;+ if (anchorRate > 0.2 && chEnd.isFinite) {+ // One audio chapter covering several ebook sections (a whole part+ // with no chapter markers): pace through the text of the sections+ // before this one under the same TOC entry, and take the rate from+ // the run as a whole rather than this section alone.+ final hrefs = await text.spineHrefs();+ var first = si;+ while (first > 0 &&+ first > si - 12 &&+ first - 1 < hrefs.length &&+ text.chapterForHref(hrefs[first - 1]) == tocTitle) {+ first--;+ }+ var last = si;+ while (last + 1 < hrefs.length &&+ last < si + 12 &&+ (text.chapterForHref(hrefs[last + 1]) ?? tocTitle) == tocTitle) {+ last++;+ }+ final counts = await text.sectionCharCounts(first, last);+ if (counts.length == last - first + 1) {+ double before = 0, run = 0;+ for (var i = 0; i < counts.length; i++) {+ final n = first + i == si ? total : counts[i];+ run += n;+ if (first + i < si) before += n;+ }+ final runRate = run > 0 ? (chEnd - chStart) / run : double.nan;+ rate = (runRate >= 0.03 && runRate <= 0.2)+ ? runRate+ : _fallbackSecPerChar;+ est = (chStart + (before + offset) * rate).clamp(chStart, chEnd);+ lo = chStart;+ hi = chEnd;+ debugPrint('[FindAudio] anchor spans sections $first-$last '+ '(${run.toInt()} chars, ${before.toInt()} before this one) '+ 'rate=${rate.toStringAsFixed(4)} est=${est.toStringAsFixed(1)}');+ }+ }+ // A marker that sits a little late (the part's interlude narrated under+ // the previous chapter) puts the passage just before the anchor, where+ // a scan clamped at the chapter start can never look.+ lo = (lo - 900).clamp(0.0, lo);+ debugPrint('[FindAudio] si=$si target@${offset.toInt()}/${total.toInt()} '+ 'toc="$tocTitle" audioCh="${audioCh['title']}" '+ '${lo.toStringAsFixed(0)}-${hi.isFinite ? hi.toStringAsFixed(0) : '?'}s '+ 'rate=${rate.toStringAsFixed(4)} est=${est.toStringAsFixed(1)}');+ } else {+ // Calibre-split books often have spine sections the TOC never names+ // (toc=null), or titles no audio chapter agrees with. Best fallback:+ // anchor on the nearest PRECEDING section that does map to an audio+ // chapter and pace forward through the intervening text. The whole-book+ // percentage is the last resort - on books with songs or front matter+ // it was measured ~800s off, far outside the probes' scan range.+ double? anchoredEst;+ var anchorStart = 0.0;+ final hrefs = await text.spineHrefs();+ for (var a = si - 1; a >= 0 && a >= si - 8; a--) {+ if (a >= hrefs.length) continue;+ final aTitle = text.chapterForHref(hrefs[a]);+ if (aTitle == null) continue;+ Map<String, dynamic>? aCh;+ for (final ch in audio.chapters) {+ final m = ch as Map<String, dynamic>;+ if (chapterTitlesAgree(m['title'] as String?, aTitle)) {+ aCh = m;+ break;+ }+ }+ if (aCh == null) continue;+ final aStart = (aCh['start'] as num?)?.toDouble() ?? 0;+ final counts = await text.sectionCharCounts(a, si - 1);+ if (counts.length == si - a) {+ final between = counts.fold<double>(0, (x, y) => x + y);+ anchorStart = aStart;+ anchoredEst = aStart + (between + offset) * _fallbackSecPerChar;+ debugPrint('[FindAudio] anchored on si=$a "${aCh['title']}" '+ 'start=${aStart.toStringAsFixed(0)} '+ 'charsBetween=${between.toInt()} est=${anchoredEst.toStringAsFixed(1)}');+ }+ break;+ }++ if (anchoredEst != null) {+ lo = anchorStart;+ hi = bookEnd;+ rate = _fallbackSecPerChar;+ est = anchoredEst;+ } else if (pct != null && pct > 0 && audio.duration > 0) {+ lo = 0;+ hi = audio.duration;+ rate = _fallbackSecPerChar;+ est = (pct * audio.duration).clamp(0.0, audio.duration);+ debugPrint('[FindAudio] fallback estimate (toc="$tocTitle") '+ 'pct=${(pct * 100).toStringAsFixed(2)}% est=${est.toStringAsFixed(1)}');+ } else {+ debugPrint('[FindAudio] no audio chapter matches toc="$tocTitle", '+ 'no anchor, no location percentage - giving up');+ return null;+ }+ }+ if (hi.isInfinite) hi = est + 3600;++ // The section's narration length sets how far apart the probes spread:+ // 90s steps suit a short section, a 40-minute chapter wants them wider so+ // five probes cover it instead of one corner.+ final scanStep = (total * rate / 4).clamp(_scanStepSeconds, 300.0);+ final dur = audio.duration;+ final probed = <double>[est];+ var probesLeft = _maxTotalProbes;++ Future<double?> run(String label, double e, double from, double to,+ double pace, int rounds, {double? step}) async {+ if (probesLeft <= 0) return null;+ final n = rounds < probesLeft ? rounds : probesLeft;+ probesLeft -= n;+ debugPrint('[FindAudio] $label est=${e.toStringAsFixed(1)} '+ 'window ${from.toStringAsFixed(0)}-${to.toStringAsFixed(0)}s '+ 'rounds=$n');+ return _probeForTarget(+ si: si,+ offset: offset,+ estimate: e,+ lo: from,+ hi: to,+ rate: pace,+ duration: dur,+ maxProbes: n,+ scanStepSeconds: step ?? scanStep,+ );+ }++ // A spot this book has already been matched at, in this section or the+ // one either side, beats any chapter-title guess: it is known, and two+ // of them give the real pace between. Probed first, in a window sized to+ // how far the pacing had to reach.+ final sync = await _syncPointCandidate(+ si: si,+ offset: offset,+ total: total,+ fallbackRate: rate,+ top: dur > 0 ? dur : est + 3600);+ if (sync != null) {+ probed.add(sync.est);+ final window = sync.hi - sync.lo;+ final r = await run(sync.label, sync.est, sync.lo, sync.hi, sync.rate, 3,+ step: (window / 3).clamp(45.0, _scanStepSeconds));+ if (r != null) return remember(r);+ }++ final t = await run('anchor', est, lo, hi, rate, _maxProbes);+ if (t != null) return remember(t);++ // The anchor never matched. Fallback candidates, most likely first, two+ // rounds each.+ final extras =+ <({String label, double est, double lo, double hi, double rate})>[];+ final top = dur > 0 ? dur : double.infinity;+ final pctEst = (pct != null && pct > 0 && dur > 0)+ ? (pct * dur).clamp(0.0, dur)+ : null;++ // Where the audio is parked right now. People mostly look up the passage+ // they just heard, so a player position near the estimate or the book+ // percentage is the best lead there is.+ final player = AudioPlayerService();+ if (player.currentItemId == itemId) {+ final now = player.position.inMilliseconds / 1000.0;+ final near = (now - est).abs() <= 1800 ||+ (pctEst != null && (now - pctEst).abs() <= 1800);+ if (near) {+ extras.add((+ label: 'player position',+ est: now,+ lo: (now - 900).clamp(0.0, now),+ hi: (now + 900).clamp(now, top),+ rate: _fallbackSecPerChar,+ ));+ }+ }+ // The whole-book percentage disagreeing with the anchor by more than a+ // few minutes usually means the anchor is the wrong chapter.+ if (pctEst != null && (pctEst - est).abs() > 300) {+ extras.add((+ label: 'book percentage',+ est: pctEst,+ lo: (pctEst - 1200).clamp(0.0, pctEst),+ hi: (pctEst + 1200).clamp(pctEst, dur),+ rate: _fallbackSecPerChar,+ ));+ }+ // The same title elsewhere in the book.+ if (audioChAlt != null) {+ final alt = _chapterAnchorEstimate(audioChAlt, offset, total, bookEnd);+ extras.add((+ label: 'runner-up "${audioChAlt['title']}"',+ est: alt.est,+ lo: alt.lo,+ hi: alt.hi.isFinite ? alt.hi : alt.est + 3600,+ rate: alt.rate,+ ));+ }+ // A chapter-derived pace far from real narration says the audio and+ // ebook chapters are numbered differently (twice too fast means the ebook+ // chapter holds twice the text the audio chapter narrates): try the+ // neighbours, nearest to the book percentage first.+ if (audioCh != null &&+ (anchorRate.isNaN || anchorRate < 0.05 || anchorRate > 0.12)) {+ final idx = audio.chapters.indexOf(audioCh);+ final neighbours = <Map<String, dynamic>>[];+ if (idx > 0) neighbours.add(audio.chapters[idx - 1] as Map<String, dynamic>);+ if (idx >= 0 && idx + 1 < audio.chapters.length) {+ neighbours.add(audio.chapters[idx + 1] as Map<String, dynamic>);+ }+ final withEst = neighbours+ .map((n) => (ch: n, a: _chapterAnchorEstimate(n, offset, total, bookEnd)))+ .toList();+ if (pctEst != null) {+ withEst.sort((x, y) =>+ (x.a.est - pctEst).abs().compareTo((y.a.est - pctEst).abs()));+ }+ for (final n in withEst) {+ extras.add((+ label: 'neighbour "${n.ch['title']}"',+ est: n.a.est,+ lo: n.a.lo,+ hi: n.a.hi.isFinite ? n.a.hi : n.a.est + 3600,+ rate: n.a.rate,+ ));+ }+ }++ for (final c in extras) {+ if (probed.any((p) => (p - c.est).abs() <= 120)) {+ debugPrint('[FindAudio] skip ${c.label}: '+ 'est=${c.est.toStringAsFixed(1)} already probed');+ continue;+ }+ probed.add(c.est);+ final r = await run(c.label, c.est, c.lo, c.hi, c.rate, 2);+ if (r != null) return remember(r);+ }+ debugPrint('[FindAudio] no candidate matched');+ return null;+ }++ /// Where the sync points say [offset] in section [si] should be in the+ /// audio. Same-section points first; failing that the last point of the+ /// previous section or the first of the next, paced through the text in+ /// between. Null when nothing recorded is close enough to help.+ Future<({String label, double est, double lo, double hi, double rate})?>+ _syncPointCandidate({+ required int si,+ required double offset,+ required double total,+ required double fallbackRate,+ required double top,+ }) async {+ final pts = SyncPointStore.instance.cached(itemId);+ if (pts.isEmpty) return null;+ final same = pts.where((p) => p.si == si).toList();+ var e = SyncPointEstimator.inSection(same, offset, fallbackRate);+ var label = 'sync points';+ if (e == null) {+ SyncPoint? prev, next;+ for (final p in pts) {+ if (p.si == si - 1 && (prev == null || p.off > prev.off)) prev = p;+ if (p.si == si + 1 && (next == null || p.off < next.off)) next = p;+ }+ if (prev != null) {+ final counts = await text.sectionCharCounts(si - 1, si - 1);+ if (counts.length == 1 && counts.first > 0) {+ final chars = (counts.first - prev.off) + offset;+ if (chars * fallbackRate <= 1800) {+ e = SyncPointEstimator.fromPoint(prev, chars, fallbackRate);+ label = 'sync point in the previous section';+ }+ }+ }+ if (e == null && next != null) {+ final chars = (total - offset) + next.off;+ if (chars * fallbackRate <= 1800) {+ e = SyncPointEstimator.fromPoint(next, -chars, fallbackRate);+ label = 'sync point in the next section';+ }+ }+ }+ if (e == null) return null;+ debugPrint('[FindAudio] $label (${e.how}) from ${pts.length} points: '+ 'est=${e.est.toStringAsFixed(1)} rate=${e.rate.toStringAsFixed(4)}');+ return (+ label: '$label (${e.how})',+ est: e.est.clamp(0.0, top),+ lo: e.lo.clamp(0.0, top),+ hi: e.hi.clamp(0.0, top),+ rate: e.rate,+ );+ }++ /// Initial search window and seconds-per-character pacing from an audio+ /// chapter anchor.+ ({double lo, double hi, double rate, double est}) _chapterAnchorEstimate(+ Map<String, dynamic> ch, double offset, double total, double bookEnd) {+ final chStart = (ch['start'] as num?)?.toDouble() ?? 0;+ final chEnd = (ch['end'] as num?)?.toDouble() ?? bookEnd;+ final chRate = (chEnd - chStart) / total;+ if (chRate >= 0.03 && chRate <= 0.2) {+ return (+ lo: chStart,+ hi: chEnd,+ rate: chRate,+ est: chStart + offset * chRate,+ );+ }+ // Mis-tagged audio chapters (a 3-second "chapter" was seen in the wild)+ // give an absurd rate. Trust the chapter START as an anchor, pace the+ // estimate at normal narration speed, leave the end open.+ return (+ lo: chStart,+ hi: bookEnd,+ rate: _fallbackSecPerChar,+ est: chStart + offset * _fallbackSecPerChar,+ );+ }++ /// Probe-transcribes around [estimate], correcting toward the selection at+ /// [offset] each round. Returns the resolved global time, or null when+ /// [maxProbes] rounds never matched the section text.+ Future<double?> _probeForTarget({+ required int si,+ required double offset,+ required double estimate,+ required double lo,+ required double hi,+ required double rate,+ required double duration,+ required int maxProbes,+ required double scanStepSeconds,+ }) async {+ var est = estimate;+ final baseEst = est;+ var scanStep = 0;+ for (var attempt = 0; attempt < maxProbes; attempt++) {+ final maxStart =+ (hi - _probeWindowSeconds) > lo ? hi - _probeWindowSeconds : lo;+ var probeStart = (est - _probeWindowSeconds / 2).clamp(lo, maxStart);+ // A chapter start is usually a file start too. A window centred on it+ // begins in the previous file and gets cut at the boundary, so it only+ // ever hears the end of the last chapter. Start at the boundary instead+ // so the estimate is inside what gets transcribed.+ final boundary = TranscriptionService.instance+ .trackBoundaryBetween(itemId, probeStart, est);+ if (boundary != null) {+ debugPrint('[FindAudio] probe#$attempt window start '+ '${probeStart.toStringAsFixed(1)} -> file boundary '+ '${boundary.toStringAsFixed(1)}');+ probeStart = boundary.clamp(lo, maxStart > boundary ? maxStart : boundary);+ }++ List<({double start, double end, String text})> segs;+ try {+ segs = await TranscriptionService.instance.transcribeWindowSegments(+ itemId: itemId,+ startSeconds: probeStart,+ windowSeconds: _probeWindowSeconds,+ preferAccuracy: false,+ );+ } on TranscriptionException catch (e) {+ // A silent or music-only window transcribes to nothing, and a probe+ // landing at the tail of a track file gets truncated to nearly zero+ // (windows don't span file boundaries) - scan on rather than giving+ // up. Setup problems can't be scanned away.+ if (e.kind != TranscriptionError.empty &&+ e.kind != TranscriptionError.extractFailed) {+ rethrow;+ }+ segs = const [];+ }+ final probeText = segs.map((s) => s.text).join(' ').trim();+ final match =+ probeText.isEmpty ? null : await text.locateTranscriptInSection(si, probeText);+ final fine = match == null ? 0.0 : (match['fine'] as num).toDouble();++ if (match == null || fine < 0.5) {+ // Bad probe (music, silence, or the estimate is off enough that the+ // audio here isn't in this section): scan around the original+ // estimate instead of declining on the first miss.+ scanStep = scanStep >= 0 ? -(scanStep + 1) : -scanStep;+ est = (baseEst + scanStep * scanStepSeconds).clamp(lo, hi);+ debugPrint('[FindAudio] probe#$attempt start=${probeStart.toStringAsFixed(1)} '+ 'no usable match (fine=${fine.toStringAsFixed(3)}) - '+ 'scanning to ${est.toStringAsFixed(1)}');+ continue;+ }++ final mOff = (match['s'] as num).toDouble();+ final mEnd = (match['e'] as num).toDouble();+ debugPrint('[FindAudio] probe#$attempt start=${probeStart.toStringAsFixed(1)} '+ 'match=${mOff.toInt()}-${mEnd.toInt()} '+ 'fine=${fine.toStringAsFixed(3)} target=${offset.toInt()}');++ if (offset >= mOff && offset <= mEnd) {+ // Target is inside the probed audio: walk the segments to the one+ // covering the target's share of the matched text.+ final frac = (mEnd - mOff) > 0 ? (offset - mOff) / (mEnd - mOff) : 0.0;+ final lens = segs.map((s) => s.text.length + 1).toList();+ final totalLen = lens.fold<int>(0, (a, b) => a + b);+ final targetChar = frac * totalLen;+ var t = probeStart + segs.last.start;+ var acc = 0.0;+ for (var i = 0; i < segs.length; i++) {+ if (targetChar <= acc + lens[i] || i == segs.length - 1) {+ final inFrac = lens[i] > 0+ ? ((targetChar - acc) / lens[i]).clamp(0.0, 1.0)+ : 0.0;+ t = probeStart + segs[i].start + inFrac * (segs[i].end - segs[i].start);+ break;+ }+ acc += lens[i];+ }+ debugPrint('[FindAudio] resolved t=${t.toStringAsFixed(1)}s');+ return duration > 0 ? t.clamp(0.0, duration) : t;+ }++ // Probe landed off-target: correct by the miss distance and retry. A+ // correction too small to move the next probe means the rate is off -+ // step most of a window toward the target instead.+ var correction = (offset - (mOff + mEnd) / 2) * rate;+ if (correction.abs() < 2.0) {+ correction = correction.isNegative+ ? -_probeWindowSeconds * 0.75+ : _probeWindowSeconds * 0.75;+ }+ est = (est + correction).clamp(lo, hi);+ }+ debugPrint('[FindAudio] gave up after $maxProbes probes');+ return null;+ }+}diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 3790a935..dd38cbb7 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -10,6 +10,7 @@ import 'package:audio_session/audio_session.dart';import 'package:shared_preferences/shared_preferences.dart';import 'api_service.dart';import 'download_service.dart';+import 'narrated_books.dart';import 'offline_source.dart';import 'playback_history_service.dart' hide PlaybackEvent;import 'progress_sync_service.dart';@@ -1381,6 +1382,9 @@ class AudioPlayerService extends ChangeNotifier {// LibraryProvider calls [drainPendingBookFinished] once its absorbing cache// is loaded so auto-advance has the state it needs.static String? _pendingBookFinishedKey;+ /// A book started or resumed from the app's own controls.+ static void Function(String itemId)? onAppPlay;+static void setOnBookFinishedCallback(void Function(String itemId)? cb) {_onBookFinishedCallback = cb;}@@ -3815,7 +3819,14 @@ class AudioPlayerService extends ChangeNotifier {// Check if downloaded — play locallyString? result;- if (_downloadService.isDownloaded(progressKey)) {+ if (episodeId == null && !api.isBookOrbit && NarratedBooks.contains(itemId) &&+ !_downloadService.isDownloaded(progressKey)) {+ // An Audiobookshelf EPUB that reads itself aloud plays once downloaded.+ debugPrint('[Player] $itemId is narration that is not downloaded - not starting');+ _endAdvanceBuffering();+ _clearState();+ return 'Download this book to play its narration';+ } else if (_downloadService.isDownloaded(progressKey)) {result = await _playFromLocal(progressKey,title,@@ -3954,6 +3965,7 @@ class AudioPlayerService extends ChangeNotifier {_onPlaybackStateChangedCallback?.call(true);// Auto-navigate to Absorbing tab when an episode starts playing.if (episodeId != null) _onEpisodePlayStartedCallback?.call();+ if (fromUi && episodeId == null) onAppPlay?.call(itemId);}return result;}@@ -7505,6 +7517,8 @@ class AudioPlayerService extends ChangeNotifier {_scheduleAudioDiagnostics('resume');_logEvent(PlaybackEventType.play, detail: logDetail);_onPlaybackStateChangedCallback?.call(true);+ final resumed = _currentItemId;+ if (fromUi && resumed != null && _currentEpisodeId == null) onAppPlay?.call(resumed);// Re-create server session and check progress in the background// so resume is instant instead of waiting for network round-trips_resumeServerSync();diff --git a/lib/services/book_search_index.dart b/lib/services/book_search_index.dartindex 07746228..87edddad 100644--- a/lib/services/book_search_index.dart+++ b/lib/services/book_search_index.dart@@ -187,6 +187,10 @@ class BookSearchIndex {);}+ /// Every item indexed so far this session, across libraries.+ Iterable<Map<String, dynamic>> get indexedItems =>+ _cache.values.expand((list) => list.map((e) => e.item));+List<BookSearchHit> search(String libraryId, String query, {int limit = 40}) {final idx = _cache[libraryId];if (idx == null) return const [];diff --git a/lib/services/bookorbit_api_service.dart b/lib/services/bookorbit_api_service.dartindex f54fb964..bc7a8c07 100644--- a/lib/services/bookorbit_api_service.dart+++ b/lib/services/bookorbit_api_service.dart@@ -3453,8 +3453,26 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {String buildEbookUrl(String itemId, String ino) =>BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$ino/serve');+ /// A narrated EPUB's audio is hundreds of MB the reader never touches; the+ /// server can hand over the book without it.+ @override+ String buildReaderEbookUrl(String itemId, String ino) {+ final detail = _details[_key(itemId)];+ if (detail != null) {+ final media = BookOrbitMapper.item(detail: detail)['media'] as Map<String, dynamic>;+ if ('${(media['narration'] as Map?)?['fileId']}' == ino) {+ return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$ino/audioless-epub/download');+ }+ }+ return buildEbookUrl(itemId, ino);+ }+@overrideMap<String, String> downloadHeadersFor(String url) {+ if (url.startsWith('$_v1/watch-downloads/media-overlay/files/')) {+ final ticket = _narrationTickets[_key(Uri.parse(url).queryParameters['book'] ?? '')];+ if (ticket != null) return {...customHeaders, 'Authorization': 'Bearer ${ticket.token}'};+ }if (url.startsWith('$_v1/watch-downloads/files/')) {final fileId = Uri.parse(url).pathSegments.last;for (final t in _tickets.values) {@@ -3469,11 +3487,64 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {/// Background downloads outlive a fifteen-minute access token, so ask the/// server for a download ticket (good for twelve hours) covering the/// book's audio files. Without one the files go through the in-app proxy.+ final Map<String, ({String token, DateTime expiresAt, Map<String, String> paths})> _narrationTickets = {};++ @override+ String? buildNarrationDownloadUrl(String itemId, String contentUrl) {+ final uri = Uri.parse(contentUrl);+ const marker = '/media-overlay/file/';+ final at = uri.path.indexOf(marker);+ if (at < 0) return null;+ final href = uri.path+ .substring(at + marker.length)+ .split('/')+ .map(Uri.decodeComponent)+ .join('/');+ final ticket = _narrationTickets[_key(itemId)];+ final path = ticket?.paths[href];+ if (ticket != null &&+ path != null &&+ ticket.expiresAt.isAfter(DateTime.now().add(const Duration(hours: 1)))) {+ return '$_cleanBaseUrl$path?book=$itemId';+ }+ return buildTrackUrl(contentUrl);+ }++ /// A download ticket for a narrated EPUB's audio files, so a background+ /// download outlives the access token like an audiobook's does.+ Future<void> _prepareNarrationDownload(String itemId) async {+ final n = await _narration(itemId, fresh: true);+ if (n == null) return;+ final hrefs = n.overlay.tracks.map((t) => t.href).take(2048).toList();+ try {+ final res = await _boPost('/watch-downloads/media-overlay', {+ 'bookId': int.parse(itemId),+ 'fileId': n.fileId,+ 'hrefs': hrefs,+ }) as Map<String, dynamic>;+ final token = res['token'] as String?;+ final expires = DateTime.tryParse(res['expiresAt'] as String? ?? '');+ final paths = <String, String>{+ for (final f in (res['files'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>())+ if (f['href'] is String && f['downloadPath'] is String) f['href'] as String: f['downloadPath'] as String,+ };+ if (token != null && expires != null && paths.isNotEmpty) {+ _narrationTickets[_key(itemId)] = (token: token, expiresAt: expires, paths: paths);+ }+ } catch (e) {+ debugPrint('[BookOrbit] No narration download ticket for $itemId ($e) - using the proxy');+ }+ }+@overrideFuture<void> prepareDownload(String itemId) async {await ensureMediaReady();final manifest = await _manifest(itemId, fresh: true);- final fileIds = (manifest?['assets'] as List<dynamic>? ?? const [])+ if (manifest == null) {+ await _prepareNarrationDownload(itemId);+ return;+ }+ final fileIds = (manifest['assets'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().map((a) => a['fileId']).whereType<int>()@@ -3538,12 +3609,27 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {final state = manifest != null ? await _playbackState(bookId) : null;({String? cfi, double? percent, int? updated, int? fileId}) ebook =(cfi: null, percent: null, updated: null, fileId: null);- if ((BookOrbitMapper.item(detail: detail)['media'] as Map)['ebookFile'] != null) {+ final itemMedia = BookOrbitMapper.item(detail: detail)['media'] as Map;+ var fp = const <dynamic>[];+ if (itemMedia['ebookFile'] != null) {try {- final fp = await _boGet('/books/$bookId/progress') as List<dynamic>;+ fp = await _boGet('/books/$bookId/progress') as List<dynamic>;ebook = _ebookFrom(detail, fp);} catch (_) {}}+ // A narrated EPUB with no audiobook: listening progress is the narration+ // position kept on the EPUB.+ final narration = itemMedia['narration'] as Map?;+ double? narrationAt;+ final narrationTotal = (narration?['duration'] as num?)?.toDouble() ?? 0;+ if (narration != null) {+ final fileId = int.tryParse('${narration['fileId']}');+ for (final r in fp.whereType<Map<String, dynamic>>()) {+ if ((r['fileId'] as num?)?.toInt() == fileId) {+ narrationAt = (r['positionSeconds'] as num?)?.toDouble();+ }+ }+ }final readStatus = detail['readStatus'] as Map<String, dynamic>?;if (state == null && ebook.percent == null && readStatus == null) return null;final p = BookOrbitMapper.progress(@@ -3556,6 +3642,15 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {ebookUpdatedAt: ebook.updated,);if (!hasAudio && ebook.percent != null) p['progress'] = (ebook.percent! / 100).clamp(0.0, 1.0);+ if (narrationAt != null && narrationTotal > 0) {+ p['duration'] = narrationTotal;+ p['currentTime'] = narrationAt;+ if (p['isFinished'] != true) p['progress'] = (narrationAt / narrationTotal).clamp(0.0, 1.0);+ } else if (narration != null) {+ // No listening spot on the EPUB (a page save from an older Absorb+ // cleared it): nothing to move a paused player to, least of all 0.+ p.remove('currentTime');+ }return p;}@@ -3618,7 +3713,7 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {/// describes the outcome for Audiobookshelf callers.Future<int> _putPosition(String bookId, double absoluteSeconds, {DateTime? capturedAt}) async {var manifest = await _manifest(bookId);- if (manifest == null) return 404;+ if (manifest == null) return _putNarrationPosition(bookId, absoluteSeconds);final when = (capturedAt ?? DateTime.now()).toUtc();final operationId = _uuid();for (var attempt = 0; attempt < 3; attempt++) {@@ -3714,7 +3809,8 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {Future<void> _saveEbookProgress(String bookId, String? location, double? progress) async {final detail = await _detail(bookId);- final ebook = (BookOrbitMapper.item(detail: detail)['media'] as Map)['ebookFile'] as Map?;+ final media = BookOrbitMapper.item(detail: detail)['media'] as Map;+ final ebook = media['ebookFile'] as Map?;final fileId = ebook?['ino'];if (fileId == null) return;final pct = ((progress ?? 0) * 100).clamp(0.0, 100.0);@@ -3723,6 +3819,7 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {'percentage': pct,if (location != null && page == null) 'cfi': location,if (page != null) 'pageNumber': page,+ ...await _narrationSpotToKeep(bookId, media, '$fileId'),});if (progress != null && progress >= 1.0) {await _setStatus(bookId, {'status': 'read'});@@ -3754,6 +3851,22 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {await _unfinish(bookId);}+ /// Only the ebook file's progress: the full item progress also reads the+ /// audio manifest and playback state, which made the reader's open-time+ /// check run out of time and start from the phone's older place.+ @override+ Future<Map<String, dynamic>?> getEbookPosition(String itemId) async {+ final detail = await _detail(itemId);+ final fp = await _boGet('/books/$itemId/progress') as List<dynamic>;+ final ebook = _ebookFrom(detail, fp);+ if (ebook.cfi == null && ebook.percent == null) return null;+ return {+ 'ebookLocation': ebook.cfi,+ 'ebookProgress': ebook.percent == null ? null : (ebook.percent! / 100).clamp(0.0, 1.0),+ 'ebookUpdatedAt': ebook.updated,+ };+ }+@overrideFuture<bool> updateEbookProgress(String itemId, {required String ebookLocation, required double ebookProgress}) async {lastEbookProgressStatus = null;@@ -3831,10 +3944,207 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {}}+ final Map<String, ({MediaOverlay overlay, int fileId})> _narrations = {};++ /// The narration of a book whose only audio is its EPUB reading itself+ /// aloud (EPUB 3 media overlays), or null for any other book.+ Future<({MediaOverlay overlay, int fileId})?> _narration(+ String bookId, {+ Map<String, dynamic>? detail,+ bool fresh = false,+ }) async {+ final k = _key(bookId);+ final cached = _narrations[k];+ if (!fresh && cached != null) return cached;+ detail ??= await _detail(bookId);+ final media = BookOrbitMapper.item(detail: detail)['media'] as Map<String, dynamic>;+ final fileId = int.tryParse('${(media['narration'] as Map?)?['fileId']}');+ if (fileId == null) return null;+ final playlist = await _boGet('/epub/$bookId/media-overlay', {'fileId': '$fileId'}) as Map<String, dynamic>;+ final parsed = MediaOverlay.fromBookOrbit(playlist);+ if (parsed == null || parsed.isEmpty) return null;+ var overlay = parsed;+ // The playlist names each narrated file only when the contents point+ // straight at it; the whole contents name the rest.+ try {+ final info = await _boGet('/epub/$bookId/info', {'fileId': '$fileId'}) as Map<String, dynamic>;+ overlay = overlay.withBookOrbitContents(info);+ } catch (e) {+ debugPrint('[BookOrbit] contents for $bookId not read: $e');+ }+ return _narrations[k] = (overlay: overlay, fileId: fileId);+ }++ /// Public for the reader's read along: the same narration the player is+ /// streaming, so its timings line up exactly.+ Future<MediaOverlay?> narrationFor(String bookId) async {+ try {+ return (await _narration(bookId))?.overlay;+ } catch (e) {+ debugPrint('[BookOrbit] narration for $bookId failed: $e');+ return null;+ }+ }++ /// BookOrbit keeps reading sessions of its own: the time goes on the ebook+ /// file as reading, not listening.+ @override+ Future<bool> logReadingTime(+ String itemId, {+ required String sessionId,+ required DateTime startedAt,+ required int seconds,+ required double audioAt,+ required double audioDuration,+ String? title,+ double? ebookStart,+ double? ebookEnd,+ }) async {+ try {+ final detail = await _detail(itemId);+ final ebook = (BookOrbitMapper.item(detail: detail)['media'] as Map)['ebookFile'] as Map?;+ final fileId = ebook?['ino'];+ if (fileId == null) return false;+ final end = DateTime.now();+ final span = math.max(0, end.difference(startedAt).inSeconds);+ final source = _platformSource();+ await _boPost('/books/files/$fileId/sessions', {+ 'sessionId': sessionId.length > 64 ? sessionId.substring(0, 64) : sessionId,+ 'startedAt': _iso(startedAt),+ 'endedAt': _iso(end),+ 'durationSeconds': math.min(seconds, span),+ if (ebookStart != null && ebookEnd != null)+ 'progressDelta': double.parse(((ebookEnd - ebookStart) * 100).toStringAsFixed(4)),+ if (ebookEnd != null) 'endProgress': (ebookEnd * 100).clamp(0.0, 100.0),+ 'sessionType': 'read',+ if (source != null) 'source': source,+ });+ return true;+ } catch (e) {+ debugPrint('[BookOrbit] reading time for $itemId not logged: $e');+ return false;+ }+ }++ /// BookOrbit keeps a narrated EPUB's listening spot on the same row as its+ /// page, and a page save without it clears it, so the spot rides along.+ Future<Map<String, Object?>> _narrationSpotToKeep(String bookId, Map media, String fileId) async {+ if ('${(media['narration'] as Map?)?['fileId']}' != fileId) return const {};+ try {+ final at = await _narrationPosition(bookId, int.parse(fileId));+ if (at == null) return const {};+ final clip = (await _narration(bookId))?.overlay.clipAt(at.seconds);+ return {+ 'positionSeconds': at.seconds,+ 'mediaOverlayFragment': clip?.fragment,+ 'mediaOverlaySectionIndex': clip?.section,+ };+ } catch (e) {+ debugPrint('[BookOrbit] narration spot for $bookId not kept: $e');+ return const {};+ }+ }++ /// Where the narration was left, in seconds, from the EPUB's progress.+ Future<({double seconds, int? updatedAt})?> _narrationPosition(String bookId, int fileId) async {+ try {+ final rows = await _boGet('/books/$bookId/progress') as List<dynamic>;+ for (final r in rows.whereType<Map<String, dynamic>>()) {+ if ((r['fileId'] as num?)?.toInt() != fileId) continue;+ final s = (r['positionSeconds'] as num?)?.toDouble();+ if (s == null) return null;+ return (seconds: s, updatedAt: BookOrbitMapper.ms(r['updatedAt']));+ }+ } on _BoHttpError catch (e) {+ if (e.status != 404) rethrow;+ }+ return null;+ }++ /// Saved where BookOrbit's own read along keeps its place: the narration+ /// position on the EPUB, with the sentence it reached.+ Future<int> _putNarrationPosition(String bookId, double seconds) async {+ final ({MediaOverlay overlay, int fileId})? n;+ try {+ n = await _narration(bookId);+ } on _BoHttpError catch (e) {+ return e.status;+ }+ if (n == null) return 404;+ final total = n.overlay.duration;+ final clip = n.overlay.clipAt(seconds);+ try {+ await _boPost('/books/files/${n.fileId}/progress', {+ 'percentage': total > 0 ? (seconds / total * 100).clamp(0.0, 100.0) : 0,+ 'positionSeconds': math.max(0.0, seconds),+ 'mediaOverlayFragment': clip?.fragment,+ 'mediaOverlaySectionIndex': clip?.section,+ 'source': 'narration',+ });+ return 200;+ } on _BoHttpError catch (e) {+ debugPrint('[BookOrbit] Narration position for $bookId not saved: ${e.status} ${e.message}');+ return e.status;+ }+ }++ static String _narrationTrackPath(String bookId, int fileId, OverlayTrack track) {+ final path = track.href.split('/').map(Uri.encodeComponent).join('/');+ return '/api/v1/epub/$bookId/media-overlay/file/$path?fileId=$fileId';+ }++ Future<Map<String, dynamic>> _startNarrationSession(String bookId, Map<String, dynamic> detail) async {+ final n = await _narration(bookId, detail: detail, fresh: true);+ if (n == null) throw _BoHttpError(404, 'Book has no audiobook assets');+ final overlay = n.overlay;+ final item = BookOrbitMapper.item(detail: detail);+ final media = item['media'] as Map<String, dynamic>;+ final metadata = media['metadata'] as Map<String, dynamic>;+ final chapters = overlay.chapters();+ final tracks = overlay.audioTracks((t) => _narrationTrackPath(bookId, n.fileId, t));+ media['chapters'] = chapters;+ media['tracks'] = tracks;+ media['duration'] = overlay.duration;+ final saved = await _narrationPosition(bookId, n.fileId);+ final current = (saved?.seconds ?? 0).clamp(0.0, overlay.duration).toDouble();+ final now = DateTime.now();+ final sessionId = 'bo-$bookId-${now.millisecondsSinceEpoch}';+ _sessions[sessionId] = _BoListenSession(bookId, _uuid(), now)+ ..fileId = n.fileId+ ..startPercent = overlay.duration > 0 ? (current / overlay.duration * 100).clamp(0.0, 100.0) : null;+ debugPrint('[BookOrbit] narration session for $bookId: ${tracks.length} tracks, '+ '${overlay.clips.length} sentences, ${overlay.duration.toStringAsFixed(0)}s, from ${current.toStringAsFixed(0)}s');+ return {+ 'id': sessionId,+ 'userId': '',+ 'libraryId': item['libraryId'],+ 'libraryItemId': bookId,+ 'episodeId': null,+ 'mediaType': 'book',+ 'mediaMetadata': metadata,+ 'chapters': chapters,+ 'displayTitle': metadata['title'],+ 'displayAuthor': metadata['authorName'],+ 'coverPath': media['coverPath'],+ 'duration': overlay.duration,+ 'playMethod': 0,+ 'mediaPlayer': 'exo-player',+ 'deviceInfo': _deviceInfo,+ 'date': '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}',+ 'timeListening': 0,+ 'startTime': current,+ 'currentTime': current,+ 'startedAt': now.millisecondsSinceEpoch,+ 'updatedAt': saved?.updatedAt ?? now.millisecondsSinceEpoch,+ 'audioTracks': tracks,+ 'libraryItem': item,+ };+ }+Future<Map<String, dynamic>> _startSession(String bookId, Map<String, dynamic> body) async {final detail = await _detail(bookId, fresh: true);final manifest = await _manifest(bookId, fresh: true);- if (manifest == null) throw _BoHttpError(404, 'Book has no audiobook assets');+ if (manifest == null) return _startNarrationSession(bookId, detail);final state = await _playbackState(bookId);final item = BookOrbitMapper.item(detail: detail, manifest: manifest);final media = item['media'] as Map<String, dynamic>;@@ -3892,6 +4202,11 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {final manifest = await _manifest(s.bookId);final assets = (manifest?['assets'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>();fileId = assets.isEmpty ? null : (assets.first['fileId'] as num?)?.toInt();+ if (manifest == null) {+ try {+ fileId = (await _narration(s.bookId))?.fileId;+ } catch (_) {}+ }s.fileId = fileId;}if (fileId == null) return;@@ -3964,7 +4279,9 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {if (currentTime != null) {status = await _putPosition(s.bookId, currentTime);final manifest = _manifests[_key(s.bookId)];- final total = manifest == null ? 0.0 : BookOrbitMapper.totalSeconds(manifest);+ final total = manifest == null+ ? (_narrations[_key(s.bookId)]?.overlay.duration ?? 0.0)+ : BookOrbitMapper.totalSeconds(manifest);if (total > 0) {s.lastPercent = (currentTime / total * 100).clamp(0.0, 100.0);s.startPercent ??= s.lastPercent;diff --git a/lib/services/bookorbit_mapper.dart b/lib/services/bookorbit_mapper.dartindex 6af92096..d5f6c505 100644--- a/lib/services/bookorbit_mapper.dart+++ b/lib/services/bookorbit_mapper.dart@@ -304,9 +304,17 @@ class BookOrbitMapper {}}- final ebook = _primaryEbook(contentFiles);+ // An EPUB 3 that reads itself aloud, with no audiobook beside it: its+ // narration is the book's audio, and the narrated copy is the one to read+ // so read along can follow it.+ final narrated = audioFiles.isEmpty ? narratedEpub(contentFiles) : null;+ final narrationSeconds =+ ((narrated?['mediaOverlay'] as Map?)?['durationSeconds'] as num?)?.toDouble() ?? 0;+ final ebook = narrated ?? _primaryEbook(contentFiles);final ebookFormat = ebook == null ? null : _format(ebook);- final duration = _bookDurationSeconds(manifest, audioMeta, offset);+ final duration = narrated != null+ ? narrationSeconds+ : _bookDurationSeconds(manifest, audioMeta, offset);final size = files.fold<num>(0, (sum, f) => sum + ((f['sizeBytes'] as num?) ?? 0));final hasCover = detail != null? detail['coverSource'] != null@@ -335,6 +343,7 @@ class BookOrbitMapper {},},'ebookFormat': ebookFormat,+ if (narrated != null) 'narration': {'fileId': _str(narrated['id']), 'duration': narrationSeconds},'numTracks': audioFiles.length,'numAudioFiles': audioFiles.length,'numChapters': chapters.length,@@ -629,6 +638,17 @@ class BookOrbitMapper {static bool _hasAudio(List<Map<String, dynamic>> files) =>files.where(_isContent).any((f) => isAudioFormat(_format(f)));+ /// An EPUB carrying its own narration (EPUB 3 media overlays) of a known+ /// length, or null.+ static Map<String, dynamic>? narratedEpub(List<Map<String, dynamic>> contentFiles) {+ for (final f in contentFiles) {+ if (_format(f) != 'epub') continue;+ final overlay = f['mediaOverlay'] as Map?;+ if (overlay?['available'] == true && ((overlay?['durationSeconds'] as num?) ?? 0) > 0) return f;+ }+ return null;+ }+static Map<String, dynamic>? _primaryEbook(List<Map<String, dynamic>> contentFiles) {final ebooks = contentFiles.where((f) {final fmt = _format(f);diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex 651a5fb8..ec7db85d 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -16,6 +16,8 @@ import '../widgets/overlay_toast.dart';import 'api_service.dart';import 'audio_player_service.dart';import 'ebook_cache.dart';+import 'narrated_books.dart';+import 'narration_service.dart';import 'offline_source.dart';import 'user_account_service.dart';@@ -677,8 +679,14 @@ class DownloadService extends ChangeNotifier {notifyListeners();}- bool isDownloaded(String itemId) =>- _downloads[itemId]?.status == DownloadStatus.downloaded;+ /// A narrated EPUB on Audiobookshelf counts as downloaded only once its+ /// audio is: its ebook alone (kept by the reader in earlier builds) would+ /// otherwise block the narration's download and play from nothing.+ bool isDownloaded(String itemId) {+ final d = _downloads[itemId];+ if (d?.status != DownloadStatus.downloaded) return false;+ return d!.localPaths.isNotEmpty || !NarratedBooks.contains(itemId);+ }/// Registers an ebook-only book as a completed download so it shows in the/// offline library and its detail sheet loads offline. There's no audio, so@@ -696,6 +704,9 @@ class DownloadService extends ChangeNotifier {String? libraryId,bool onlyIfNoAudio = false,}) async {+ // A narrated EPUB's download is its audio; the reader keeps the ebook+ // apart (keepEbook) so the two don't get mixed up.+ if (onlyIfNoAudio && NarratedBooks.contains(itemId)) return false;Map<String, dynamic>? fullItem;try {fullItem = await api.getLibraryItem(itemId);@@ -739,6 +750,99 @@ class DownloadService extends ChangeNotifier {return true;}+ /// A narrated EPUB's audio, taken out of the book file, kept as the book's+ /// download so it plays like any downloaded audiobook. Replaces an+ /// ebook-only record for the same book.+ Future<void> registerNarration({+ required ApiService api,+ required String itemId,+ required Map<String, dynamic> item,+ required String dirPath,+ required List<String> paths,+ required double duration,+ required List<Map<String, dynamic>> chapters,+ required List<Map<String, dynamic>> audioTracks,+ }) async {+ final media = Map<String, dynamic>.from(item['media'] as Map? ?? const {});+ final metadata = media['metadata'] as Map<String, dynamic>?;+ media['duration'] = duration;+ media['chapters'] = chapters;+ media['tracks'] = audioTracks;+ media['narration'] = {'duration': duration, 'local': true};+ final stored = {...item, 'media': media};+ final localCoverPath = await _cacheCover(api, itemId, api.getCoverUrl(itemId, width: 800));+ for (final p in paths) {+ await _excludeFromBackup(p);+ }+ _noteOrigin(itemId);+ _downloads[itemId] = DownloadInfo(+ itemId: itemId,+ status: DownloadStatus.downloaded,+ localPaths: paths,+ sessionData: jsonEncode({+ 'libraryItem': stored,+ 'mediaMetadata': metadata,+ 'displayTitle': metadata?['title'],+ 'displayAuthor': metadata?['authorName'],+ 'duration': duration,+ 'chapters': chapters,+ 'audioTracks': audioTracks,+ }),+ title: metadata?['title'] as String?,+ author: metadata?['authorName'] as String?,+ localCoverPath: localCoverPath,+ localDirPath: dirPath,+ libraryId: item['libraryId'] as String?,+ );+ await _save();+ notifyListeners();+ debugPrint('[Download] narration kept as audio for $itemId: ${paths.length} files, ${duration.toStringAsFixed(0)}s');+ }++ /// A kept narration's chapters and track lengths, read again.+ Future<void> updateNarrationTimeline(+ String itemId, {+ required double duration,+ required List<Map<String, dynamic>> chapters,+ required List<Map<String, dynamic>> audioTracks,+ }) async {+ final info = _downloads[itemId];+ final raw = info?.sessionData;+ if (info == null || raw == null) return;+ try {+ final data = jsonDecode(raw) as Map<String, dynamic>;+ data['duration'] = duration;+ data['chapters'] = chapters;+ data['audioTracks'] = audioTracks;+ final item = data['libraryItem'];+ if (item is Map<String, dynamic> && item['media'] is Map<String, dynamic>) {+ final media = item['media'] as Map<String, dynamic>;+ media['duration'] = duration;+ media['chapters'] = chapters;+ media['tracks'] = audioTracks;+ media['narration'] = {'duration': duration, 'local': true};+ }+ _downloads[itemId] = DownloadInfo(+ itemId: itemId,+ status: info.status,+ progress: info.progress,+ localPaths: info.localPaths,+ sessionData: jsonEncode(data),+ title: info.title,+ author: info.author,+ coverUrl: info.coverUrl,+ localCoverPath: info.localCoverPath,+ localDirPath: info.localDirPath,+ libraryId: info.libraryId,+ );+ await _save();+ notifyListeners();+ debugPrint('[Download] narration timeline for $itemId: ${chapters.length} chapters, ${duration.toStringAsFixed(0)}s');+ } catch (e) {+ debugPrint('[Download] narration timeline for $itemId not updated: $e');+ }+ }+bool isDownloading(String itemId) =>_downloads[itemId]?.status == DownloadStatus.downloading;@@ -1553,6 +1657,15 @@ class DownloadService extends ChangeNotifier {return null;}+ // An Audiobookshelf narrated EPUB: its audio comes out of the EPUB here in+ // the app, a file at a time, rather than through the background downloader.+ if (episodeId == null && !api.isBookOrbit && NarratedBooks.contains(itemId)) {+ if (shouldStart?.call() == false) return null;+ unawaited(_downloadNarration(api, itemId,+ title: title, author: author, coverUrl: coverUrl, libraryId: libraryId));+ return null;+ }+// If at capacity, queue this oneif (_activeDownloadIds.length >= maxConcurrent) {if (shouldStart?.call() == false) return null;@@ -1593,6 +1706,58 @@ class DownloadService extends ChangeNotifier {return null;}+ Future<void> _downloadNarration(+ ApiService api,+ String itemId, {+ required String title,+ String? author,+ String? coverUrl,+ String? libraryId,+ }) async {+ _activeDownloadIds.add(itemId);+ _cancelledIds.remove(itemId);+ DownloadInfo running(double progress) => DownloadInfo(+ itemId: itemId,+ status: DownloadStatus.downloading,+ progress: progress,+ title: title,+ author: author,+ coverUrl: coverUrl,+ libraryId: libraryId,+ );+ _downloads[itemId] = running(0);+ notifyListeners();+ debugPrint('[Download] Starting "$title" ($itemId): the narration out of its EPUB');+ var shown = DateTime(0);+ var ok = false;+ try {+ final item = await api.getLibraryItem(itemId);+ if (item != null) {+ ok = await NarrationService.instance.prepareLocal(api, item, onProgress: (p) {+ if (_cancelledIds.contains(itemId)) throw const NarrationCancelled();+ final now = DateTime.now();+ if (now.difference(shown) < const Duration(milliseconds: 500)) return;+ shown = now;+ _downloads[itemId] = running(p.clamp(0.0, 1.0));+ notifyListeners();+ });+ }+ } on NarrationCancelled {+ debugPrint('[Download] "$title" ($itemId) cancelled');+ } catch (e) {+ debugPrint('[Download] "$title" ($itemId) failed: $e');+ } finally {+ _activeDownloadIds.remove(itemId);+ }+ if (ok || _downloads[itemId]?.status == DownloadStatus.downloaded) return;+ if (_downloads[itemId]?.status == DownloadStatus.downloading) _downloads.remove(itemId);+ try {+ final dir = Directory('${await downloadBasePath}/$itemId');+ if (dir.existsSync()) await dir.delete(recursive: true);+ } catch (_) {}+ notifyListeners();+ }+/// Download entry point for short-lived background isolates (the episode/// notification job). Same guards as [downloadItem], but awaits the enqueue/// (the isolate dies as soon as the task returns, which would cut off a@@ -1662,7 +1827,7 @@ class DownloadService extends ChangeNotifier {Future<void> _cacheEbookForOffline(ApiService api, String itemId, Map<String, dynamic> ebookFile, String title) async {try {- final f = await fetchEbookToCache(api, itemId, ebookFile, title);+ final f = await NarrationService.instance.readerFile(api, itemId, ebookFile, title);await _excludeFromBackup(f.path);debugPrint('[Download] cached ebook for offline: $itemId');} catch (e) {@@ -2111,6 +2276,12 @@ class DownloadService extends ChangeNotifier {throw Exception('Track ${i + 1} points to a different server');}}+ // A narrated EPUB's audio, on servers that serve it file by file.+ final narration = api.buildNarrationDownloadUrl(apiItemId, contentUrl);+ if (narration != null) {+ out.add((url: narration, filename: _trackFileName(track, i)));+ continue;+ }final segments = uri.pathSegments;String? ino;for (int segment = 0; segment + 4 < segments.length; segment++) {@@ -2375,6 +2546,9 @@ class DownloadService extends ChangeNotifier {}) =>_resolveDurableFiles(api, itemId, audioTracks, sessionId: sessionId);+ @visibleForTesting+ void debugPutDownload(DownloadInfo info) => _downloads[info.itemId] = info;+@visibleForTestingFuture<void> debugReset() async {_reconcileTimer?.cancel();diff --git a/lib/services/ebook_cache.dart b/lib/services/ebook_cache.dartindex e0747ad8..bad72da2 100644--- a/lib/services/ebook_cache.dart+++ b/lib/services/ebook_cache.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:convert';import 'dart:io';import 'package:flutter/foundation.dart';@@ -225,7 +226,7 @@ Future<File> fetchEbookToCache(// reverse proxies strip the header - the same reason audio file downloads// use the token form (see ApiService.buildFileUrl).final url = api.isBookOrbit- ? api.buildEbookUrl(itemId, ino)+ ? api.buildReaderEbookUrl(itemId, ino): '$cleanBase/api/items/$itemId/file/$ino?token=${api.token}';debugPrint('[EbookCache] downloading item=$itemId path=/api/items/$itemId/file/$ino');@@ -253,9 +254,24 @@ Future<File> fetchEbookToCache(}final ct = response.headers['content-type'] ?? '';if (ct.contains('text/html')) throw Exception('Server returned an error page');+ final total = response.contentLength ?? -1;+ debugPrint('[EbookCache] receiving item=$itemId bytes=${total < 0 ? 'unknown' : total}');final sink = partFile.openWrite();+ var received = 0;+ var logged = 0;try {- await response.stream.pipe(sink);+ // A stalled transfer used to sit forever with the reader spinning.+ await sink.addStream(response.stream.timeout(const Duration(seconds: 60)).map((chunk) {+ received += chunk.length;+ if (received - logged >= 50 * 1024 * 1024) {+ logged = received;+ debugPrint('[EbookCache] item=$itemId received $received of ${total < 0 ? '?' : total} bytes');+ }+ return chunk;+ }));+ } on TimeoutException {+ debugPrint('[EbookCache] item=$itemId stalled after $received bytes');+ throw Exception('The ebook download stopped responding');} finally {await sink.close();}diff --git a/lib/services/ebook_history.dart b/lib/services/ebook_history.dartnew file mode 100644index 00000000..4c3968c6--- /dev/null+++ b/lib/services/ebook_history.dart@@ -0,0 +1,100 @@+import 'dart:convert';++import 'package:flutter/foundation.dart';++import 'scoped_prefs.dart';++/// Why a spot was kept.+enum EbookSpotReason { closed, beforeJump, beforeSync }++/// A page the reader was on.+class EbookSpot {+ const EbookSpot({+ required this.cfi,+ required this.reason,+ required this.at,+ this.progress,+ this.chapter,+ });++ final String cfi;+ final EbookSpotReason reason;+ final DateTime at;+ final double? progress;+ final String? chapter;++ Map<String, dynamic> toJson() => {+ 'cfi': cfi,+ 'r': reason.name,+ 'at': at.millisecondsSinceEpoch,+ if (progress != null) 'p': progress,+ if (chapter != null) 'c': chapter,+ };++ static EbookSpot? fromJson(Map<String, dynamic> j) {+ final cfi = j['cfi'], at = j['at'];+ if (cfi is! String || at is! num) return null;+ return EbookSpot(+ cfi: cfi,+ reason: EbookSpotReason.values.firstWhere((r) => r.name == j['r'], orElse: () => EbookSpotReason.closed),+ at: DateTime.fromMillisecondsSinceEpoch(at.toInt()),+ progress: (j['p'] as num?)?.toDouble(),+ chapter: j['c'] as String?,+ );+ }+}++/// Pages the reader was on, kept on this phone for each book: where it was+/// closed, and where it was before every jump (a chapter, a search hit, a+/// sync to the audio). A way back when the place gets lost.+class EbookHistory {+ EbookHistory._();+ static final EbookHistory instance = EbookHistory._();++ static const _max = 100;++ static String _key(String itemId) => 'ebook_history_$itemId';++ Future<void> record(+ String itemId, {+ required String cfi,+ required EbookSpotReason reason,+ double? progress,+ String? chapter,+ }) async {+ if (!cfi.startsWith('epubcfi(')) return;+ try {+ final list = await ScopedPrefs.getStringList(_key(itemId));+ if (list.isNotEmpty) {+ final last = EbookSpot.fromJson(jsonDecode(list.last) as Map<String, dynamic>);+ if (last?.cfi == cfi) return;+ }+ final title = chapter?.trim();+ list.add(jsonEncode(EbookSpot(+ cfi: cfi,+ reason: reason,+ at: DateTime.now(),+ progress: progress,+ chapter: title == null || title.isEmpty ? null : title,+ ).toJson()));+ if (list.length > _max) list.removeRange(0, list.length - _max);+ await ScopedPrefs.setStringList(_key(itemId), list);+ debugPrint('[EbookHistory] $itemId: kept ${reason.name} at '+ '${progress == null ? '?' : '${(progress * 100).toStringAsFixed(1)}%'}${title == null ? '' : ' ($title)'}');+ } catch (e) {+ debugPrint('[EbookHistory] keeping a spot for $itemId failed: $e');+ }+ }++ /// The kept spots, newest first.+ Future<List<EbookSpot>> spots(String itemId) async {+ final out = <EbookSpot>[];+ for (final raw in (await ScopedPrefs.getStringList(_key(itemId))).reversed) {+ try {+ final s = EbookSpot.fromJson(jsonDecode(raw) as Map<String, dynamic>);+ if (s != null) out.add(s);+ } catch (_) {}+ }+ return out;+ }+}diff --git a/lib/services/epub_book_text.dart b/lib/services/epub_book_text.dartnew file mode 100644index 00000000..3c360010--- /dev/null+++ b/lib/services/epub_book_text.dart@@ -0,0 +1,421 @@+import 'dart:convert';++import 'package:archive/archive_io.dart';+import 'package:html/dom.dart' as html;+import 'package:html/parser.dart' as html_parser;+import 'package:xml/xml.dart';++/// A spot found in a book's text: the spine section, where the words start+/// and end in its text, and how well they matched (0 to 1).+typedef TextMatch = ({int si, int s, int e, double fine});++final RegExp _token = RegExp(r"[\p{L}\p{N}']+", unicode: true);++/// Where [transcript] sits in [text], fuzzily: windows of the text holding+/// most of the transcript's words, scored by edit distance over the words.+/// The same scoring the reader runs on a page it has open.+({int s, int e, double fine})? matchTranscript(String text, String transcript) {+ final t = [for (final m in _token.allMatches(transcript)) m.group(0)!.toLowerCase()];+ if (t.length < 3) return null;+ final need = <String, int>{};+ for (final w in t) {+ need[w] = (need[w] ?? 0) + 1;+ }+ final tNorm = t.join(' ');+ final width = t.length;+ final st = [+ for (final m in _token.allMatches(text)) (t: m.group(0)!.toLowerCase(), s: m.start, e: m.end),+ ];+ if (st.length < 3) return null;+ final have = <String, int>{};+ var matched = 0;+ final cands = <({int i, int m})>[];+ final floor = (width * 0.4).floor() > 2 ? (width * 0.4).floor() : 2;+ for (var p = 0; p < st.length; p++) {+ final tk = st[p].t;+ have[tk] = (have[tk] ?? 0) + 1;+ if (have[tk]! <= (need[tk] ?? 0)) matched++;+ if (p >= width) {+ final old = st[p - width].t;+ if (have[old]! <= (need[old] ?? 0)) matched--;+ have[old] = have[old]! - 1;+ }+ if (matched >= floor) cands.add((i: p - width + 1 < 0 ? 0 : p - width + 1, m: matched));+ }+ cands.sort((a, b) => b.m.compareTo(a.m));+ final picked = <({int i, int m})>[];+ for (final c in cands) {+ if (picked.length >= 4) break;+ if (picked.any((p) => (p.i - c.i).abs() < width)) continue;+ picked.add(c);+ }+ ({int s, int e, double fine})? out;+ for (final c in picked) {+ final e1 = c.i + width - 1 < st.length - 1 ? c.i + width - 1 : st.length - 1;+ final win = [for (var k = c.i; k <= e1; k++) st[k].t].join(' ');+ final longest = tNorm.length > win.length ? tNorm.length : win.length;+ final fine = 1 - _levenshtein(tNorm, win) / longest;+ if (out == null || fine > out.fine) out = (s: st[c.i].s, e: st[e1].e, fine: fine);+ }+ return out;+}++int _levenshtein(String a, String b) {+ final m = a.length, n = b.length;+ if (m == 0) return n;+ if (n == 0) return m;+ var prev = List<int>.generate(n + 1, (j) => j);+ var cur = List<int>.filled(n + 1, 0);+ for (var x = 1; x <= m; x++) {+ cur[0] = x;+ final ca = a.codeUnitAt(x - 1);+ for (var j = 1; j <= n; j++) {+ final cost = ca == b.codeUnitAt(j - 1) ? 0 : 1;+ final del = prev[j] + 1, ins = cur[j - 1] + 1, sub = prev[j - 1] + cost;+ cur[j] = del < ins ? (del < sub ? del : sub) : (ins < sub ? ins : sub);+ }+ final tmp = prev;+ prev = cur;+ cur = tmp;+ }+ return prev[n];+}++class _Section {+ _Section(this.root, this.nodes, this.starts, this.text);++ /// The html element.+ final html.Element root;+ final List<html.Text> nodes;+ final List<int> starts;+ final String text;+}++/// Text nodes directly under [parent], in order.+List<html.Text> _textKids(html.Node parent) => parent.nodes.whereType<html.Text>().toList();++/// An EPUB's text as the reader's pages hold it, read straight from the+/// file: each spine section's body text, the table of contents, and CFIs to+/// and from a spot in that text in the form the reader writes them. Lets a+/// place be found and saved with no reader open.+///+/// Sections are parsed as HTML, as the reader's epub.js does (it loads each+/// one through an iframe's srcdoc), so the text nodes, offsets and element+/// counts are the browser's: a self-closing `<span/>` swallows what follows+/// it, a table gains its tbody. Parsing as XML would place CFIs elsewhere.+class EpubBookText {+ EpubBookText._(this._input, this._archive, this.spine, this._paths, this.toc, this._spineStep,+ this.hasMediaOverlays);++ final InputFileStream _input;+ final Archive _archive;++ /// Spine hrefs in reading order, as the package lists them.+ final List<String> spine;+ final List<String> _paths;++ /// The table of contents, flattened in reading order.+ final List<({String href, String title})> toc;+ final int _spineStep;++ /// The EPUB carries its own narration (EPUB 3 media overlays).+ final bool hasMediaOverlays;++ final Map<int, _Section?> _sections = {};++ /// Opens the EPUB at [path]. Null when it isn't one.+ static EpubBookText? open(String path) {+ final input = InputFileStream(path);+ try {+ final archive = ZipDecoder().decodeStream(input);+ final book = _read(input, archive);+ if (book == null) input.closeSync();+ return book;+ } catch (_) {+ input.closeSync();+ return null;+ }+ }++ void close() => _input.closeSync();++ static String? _file(Archive archive, String name) {+ final f = archive.findFile(name);+ return f == null ? null : utf8.decode(f.content as List<int>, allowMalformed: true);+ }++ static XmlDocument? _xml(String? source) {+ if (source == null) return null;+ try {+ return XmlDocument.parse(source, entityMapping: XmlDefaultEntityMapping.html5());+ } catch (_) {+ return null;+ }+ }++ static String _dir(String path) {+ final i = path.lastIndexOf('/');+ return i < 0 ? '' : path.substring(0, i + 1);+ }++ static String _resolve(String base, String href) {+ var clean = href.split('#').first.split('?').first;+ try {+ clean = Uri.decodeFull(clean);+ } catch (_) {}+ final parts = <String>[];+ for (final p in '${_dir(base)}$clean'.split('/')) {+ if (p.isEmpty || p == '.') continue;+ if (p == '..') {+ if (parts.isNotEmpty) parts.removeLast();+ } else {+ parts.add(p);+ }+ }+ return parts.join('/');+ }++ static String _flat(String s) => s.replaceAll(RegExp(r'\s+'), ' ').trim();++ static EpubBookText? _read(InputFileStream input, Archive archive) {+ final container = _xml(_file(archive, 'META-INF/container.xml'));+ final opfPath = container?.descendantElements+ .where((e) => e.localName == 'rootfile')+ .map((e) => e.getAttribute('full-path'))+ .firstWhere((p) => p != null, orElse: () => null);+ if (opfPath == null) return null;+ final opf = _xml(_file(archive, opfPath));+ final package = opf?.rootElement;+ if (package == null) return null;+ final children = package.childElements.toList();+ final spineEl = children.where((e) => e.localName == 'spine').firstOrNull;+ final manifestEl = children.where((e) => e.localName == 'manifest').firstOrNull;+ if (spineEl == null || manifestEl == null) return null;+ final manifest = <String, ({String href, String path, String type, String props})>{};+ var overlays = false;+ for (final item in manifestEl.childElements.where((e) => e.localName == 'item')) {+ final id = item.getAttribute('id'), href = item.getAttribute('href');+ if (id == null || href == null) continue;+ if (item.getAttribute('media-overlay') != null) overlays = true;+ manifest[id] = (+ href: href,+ path: _resolve(opfPath, href),+ type: item.getAttribute('media-type') ?? '',+ props: item.getAttribute('properties') ?? '',+ );+ }+ final spine = <String>[];+ final paths = <String>[];+ for (final ref in spineEl.childElements.where((e) => e.localName == 'itemref')) {+ final item = manifest[ref.getAttribute('idref')];+ spine.add(item?.href ?? '');+ paths.add(item?.path ?? '');+ }+ final toc = <({String href, String title})>[];+ final nav = manifest.values.where((v) => v.props.split(' ').contains('nav')).firstOrNull;+ if (nav != null) {+ final doc = _xml(_file(archive, nav.path));+ final navs = doc?.descendantElements.where((e) => e.localName == 'nav').toList() ?? const [];+ final tocNav = navs+ .where((e) => e.attributes.any((a) => a.localName == 'type' && a.value.split(' ').contains('toc')))+ .firstOrNull ??+ navs.firstOrNull;+ for (final a in tocNav?.descendantElements.where((e) => e.localName == 'a') ?? const <XmlElement>[]) {+ final href = a.getAttribute('href');+ if (href == null) continue;+ toc.add((href: _resolve(nav.path, href) + (href.contains('#') ? '#${href.split('#').last}' : ''),+ title: _flat(a.innerText)));+ }+ }+ if (toc.isEmpty) {+ final ncxId = spineEl.getAttribute('toc');+ final ncx = manifest[ncxId] ??+ manifest.values.where((v) => v.type == 'application/x-dtbncx+xml').firstOrNull;+ if (ncx != null) {+ final doc = _xml(_file(archive, ncx.path));+ for (final point in doc?.descendantElements.where((e) => e.localName == 'navPoint') ?? const <XmlElement>[]) {+ final src = point.childElements.where((e) => e.localName == 'content').firstOrNull?.getAttribute('src');+ final label = point.childElements.where((e) => e.localName == 'navLabel').firstOrNull;+ if (src == null || label == null) continue;+ toc.add((href: _resolve(ncx.path, src) + (src.contains('#') ? '#${src.split('#').last}' : ''),+ title: _flat(label.innerText)));+ }+ }+ }+ return EpubBookText._(input, archive, spine, paths, toc, (children.indexOf(spineEl) + 1) * 2, overlays);+ }++ _Section? _section(int si) {+ if (si < 0 || si >= _paths.length) return null;+ return _sections.putIfAbsent(si, () {+ final source = _file(_archive, _paths[si]);+ if (source == null) return null;+ final doc = html_parser.parse(source);+ final root = doc.documentElement;+ final body = doc.body;+ if (root == null || body == null) return null;+ final nodes = <html.Text>[];+ void walk(html.Node n) {+ for (final c in n.nodes) {+ if (c is html.Text) {+ nodes.add(c);+ } else if (c is html.Element) {+ walk(c);+ }+ }+ }++ walk(body);+ final starts = <int>[];+ final buf = StringBuffer();+ for (final n in nodes) {+ starts.add(buf.length);+ buf.write(n.data);+ }+ return _Section(root, nodes, starts, buf.toString());+ });+ }++ String sectionText(int si) => _section(si)?.text ?? '';++ int sectionLength(int si) => sectionText(si).length;++ /// The TOC title for a spine href, matched the way the reader matches it:+ /// by file name first, then by the end of the path.+ String? chapterForHref(String href) {+ if (href.isEmpty || toc.isEmpty) return null;+ String base(String s) {+ var p = s.split('#').first;+ try {+ p = Uri.decodeFull(p);+ } catch (_) {}+ return p.split('/').last.toLowerCase();+ }++ String? label(String t) => t.trim().isEmpty ? null : t.trim();+ final b = base(href);+ if (b.isNotEmpty) {+ for (final c in toc) {+ if (base(c.href) == b) return label(c.title);+ }+ }+ final path = href.split('#').first;+ for (final c in toc) {+ final p = c.href.split('#').first;+ if (p.isEmpty) continue;+ if (path.endsWith(p) || p.endsWith(path)) return label(c.title);+ }+ return null;+ }++ /// How far through the whole book's text [offset] in section [si] is.+ double fraction(int si, int offset) {+ var before = 0, total = 0;+ for (var i = 0; i < spine.length; i++) {+ final n = sectionLength(i);+ if (i < si) before += n;+ total += n;+ }+ return total <= 0 ? 0 : ((before + offset) / total).clamp(0.0, 1.0);+ }++ /// Where [transcript] is in the book: the best-matching passage of any+ /// section, the one nearest [near] (a fraction of the book) when two+ /// match about as well. Null under [minFine].+ TextMatch? findPassage(String transcript, {double? near, double minFine = 0.6}) {+ final hits = <TextMatch>[];+ for (var si = 0; si < spine.length; si++) {+ final m = matchTranscript(sectionText(si), transcript);+ if (m != null && m.fine >= minFine) hits.add((si: si, s: m.s, e: m.e, fine: m.fine));+ }+ if (hits.isEmpty) return null;+ hits.sort((a, b) => b.fine.compareTo(a.fine));+ final top = hits.where((h) => hits.first.fine - h.fine <= 0.05).toList();+ if (near == null || top.length == 1) return top.first;+ top.sort((a, b) => (fraction(a.si, a.s) - near).abs().compareTo((fraction(b.si, b.s) - near).abs()));+ return top.first;+ }++ /// The CFI for [offset] in section [si], in the form the reader writes:+ /// `epubcfi(/6/34!/4[body-id]/2/10/1:33)`. Null when the section has no+ /// parsed text.+ String? cfiAt(int si, int offset) {+ final s = _section(si);+ if (s == null || s.nodes.isEmpty) return null;+ final root = s.root;+ var k = s.nodes.length - 1;+ for (var i = 0; i < s.nodes.length; i++) {+ if (offset < s.starts[i] + s.nodes[i].data.length) {+ k = i;+ break;+ }+ }+ final node = s.nodes[k];+ final local = (offset - s.starts[k]).clamp(0, node.data.length);+ final parent = node.parent;+ if (parent == null) return null;+ final steps = <String>['${1 + 2 * _textKids(parent).indexOf(node)}'];+ for (html.Element? el = parent; el != null && !identical(el, root); el = el.parent) {+ final up = el.parent;+ if (up == null) break;+ final id = el.attributes['id'];+ steps.add('${(up.children.indexOf(el) + 1) * 2}${id == null || id.isEmpty ? '' : '[$id]'}');+ }+ return 'epubcfi(/$_spineStep/${(si + 1) * 2}!/${steps.reversed.join('/')}:$local)';+ }++ /// The section and text offset a CFI points at (a range's start). Null+ /// when it doesn't resolve in this book.+ ({int si, int offset})? locate(String cfi) {+ final m = RegExp(r'^epubcfi\((.*)\)$').firstMatch(cfi.trim());+ if (m == null) return null;+ final inner = m.group(1)!;+ final bang = inner.indexOf('!');+ if (bang < 0) return null;+ final pkg = inner.substring(0, bang).split('/').where((p) => p.isNotEmpty).toList();+ if (pkg.isEmpty) return null;+ final spineStep = int.tryParse(pkg.last.split('[').first);+ if (spineStep == null || spineStep < 2) return null;+ final si = spineStep ~/ 2 - 1;+ final parts = inner.substring(bang + 1).split(',');+ final path = parts.length > 1 ? parts[0] + parts[1] : parts[0];+ final s = _section(si);+ if (s == null) return null;+ var term = 0;+ var steps = path;+ final colon = path.lastIndexOf(':');+ if (colon >= 0) {+ term = int.tryParse(path.substring(colon + 1).split('[').first) ?? 0;+ steps = path.substring(0, colon);+ }+ html.Element el = s.root;+ html.Text? text;+ for (final raw in steps.split('/').where((p) => p.isNotEmpty)) {+ final n = int.tryParse(raw.split('[').first);+ if (n == null || text != null) return null;+ if (n.isEven) {+ final kids = el.children;+ final i = n ~/ 2 - 1;+ if (i < 0 || i >= kids.length) return null;+ el = kids[i];+ } else {+ final kids = _textKids(el);+ final i = (n - 1) ~/ 2;+ if (i < 0 || i >= kids.length) return null;+ text = kids[i];+ }+ }+ if (text != null) {+ final k = s.nodes.indexOf(text);+ if (k < 0) return null;+ return (si: si, offset: s.starts[k] + term.clamp(0, text.data.length));+ }+ // An element: where its first text starts.+ for (var k = 0; k < s.nodes.length; k++) {+ for (html.Node? up = s.nodes[k].parent; up != null; up = up.parent) {+ if (identical(up, el)) return (si: si, offset: s.starts[k]);+ }+ }+ return null;+ }+}diff --git a/lib/services/local_session_service.dart b/lib/services/local_session_service.dartindex 80672a5a..d914c5f4 100644--- a/lib/services/local_session_service.dart+++ b/lib/services/local_session_service.dart@@ -106,6 +106,7 @@ class LocalSessionService {'updatedAt': s['updatedAt'],'date': s['date'],'dayOfWeek': s['dayOfWeek'],+ if (s['keepProgress'] == true) 'keepProgress': true,};/// Swap the payload's duration for the item's server-side duration when it@@ -300,6 +301,12 @@ class LocalSessionService {DateTime? _lastPushLogAt;+ String newSessionId() => _uuid();++ /// A finished session that couldn't be sent (reading time logged while+ /// offline), queued to go with the next replay.+ Future<void> queue(Map<String, dynamic> session) => _enqueue(session);+/// Clear the active session (stop / finish / item change). When [pushed] is/// false (offline, or the push failed) it's queued for replay; when true it's/// already on the server so we just drop it.diff --git a/lib/services/media_overlay.dart b/lib/services/media_overlay.dartnew file mode 100644index 00000000..d2631b71--- /dev/null+++ b/lib/services/media_overlay.dart@@ -0,0 +1,577 @@+import 'dart:convert';+import 'dart:math';++import 'package:archive/archive_io.dart';++/// One narrated sentence: where its text is and which stretch of which audio+/// file reads it.+class OverlayClip {+ final int section;+ final String textHref;+ final String? fragment;+ final int track;+ final double begin;+ final double end;++ const OverlayClip({+ required this.section,+ required this.textHref,+ required this.fragment,+ required this.track,+ required this.begin,+ required this.end,+ });+}++/// An audio file inside the EPUB, placed on the book's timeline.+class OverlayTrack {+ final String href;+ final String mediaType;+ final double duration;+ final double start;++ const OverlayTrack(this.href, this.mediaType, this.duration, this.start);+}++/// A narrated chapter (spine item) and where its narration starts.+class OverlaySection {+ final int index;+ final String href;+ final String? label;+ final double start;++ const OverlaySection(this.index, this.href, this.label, this.start);+}++class _RawClip {+ final int section;+ final String textHref;+ final String? fragment;+ final String audioHref;+ final double begin;+ double? end;+ _RawClip(this.section, this.textHref, this.fragment, this.audioHref, this.begin, this.end);+}++/// An EPUB 3 media overlay (a narrated or "read along" EPUB) laid out the way+/// the player sees it: the audio files end to end, each sentence a stretch of+/// one file. Built from BookOrbit's playlist or straight from the EPUB.+class MediaOverlay {+ final List<OverlayTrack> tracks;+ final List<OverlayClip> clips;+ final List<OverlaySection> sections;+ final List<List<int>> _byTrack;++ MediaOverlay._(this.tracks, this.clips, this.sections)+ : _byTrack = List.generate(tracks.length, (_) => <int>[]) {+ for (var i = 0; i < clips.length; i++) {+ _byTrack[clips[i].track].add(i);+ }+ for (final list in _byTrack) {+ list.sort((a, b) => clips[a].begin.compareTo(clips[b].begin));+ }+ }++ double get duration => tracks.isEmpty ? 0 : tracks.last.start + tracks.last.duration;++ bool get isEmpty => clips.isEmpty;++ static MediaOverlay? _build(+ List<_RawClip> raw, {+ required Map<String, String> mediaTypes,+ required Map<int, ({String href, String? label})> sectionInfo,+ }) {+ if (raw.isEmpty) return null;+ final order = <String, int>{};+ for (final c in raw) {+ order.putIfAbsent(c.audioHref, () => order.length);+ }+ // A clip with no end runs to the next clip in the same file.+ final byFile = <String, List<_RawClip>>{};+ for (final c in raw) {+ (byFile[c.audioHref] ??= []).add(c);+ }+ for (final list in byFile.values) {+ list.sort((a, b) => a.begin.compareTo(b.begin));+ for (var i = 0; i < list.length; i++) {+ if (list[i].end != null) continue;+ list[i].end = i + 1 < list.length ? list[i + 1].begin : list[i].begin;+ }+ }+ final tracks = <OverlayTrack>[];+ var start = 0.0;+ for (final href in order.keys) {+ final d = byFile[href]!.fold<double>(0, (m, c) => max(m, c.end ?? c.begin));+ tracks.add(OverlayTrack(href, mediaTypes[href] ?? _guessType(href), d, start));+ start += d;+ }+ final clips = [+ for (final c in raw)+ OverlayClip(+ section: c.section,+ textHref: c.textHref,+ fragment: c.fragment,+ track: order[c.audioHref]!,+ begin: c.begin,+ end: c.end ?? c.begin,+ ),+ ];+ final sections = <OverlaySection>[];+ final seen = <int>{};+ for (final c in clips) {+ if (!seen.add(c.section)) continue;+ final info = sectionInfo[c.section];+ sections.add(OverlaySection(+ c.section,+ info?.href ?? c.textHref,+ info?.label,+ tracks[c.track].start + c.begin,+ ));+ }+ sections.sort((a, b) => a.start.compareTo(b.start));+ return MediaOverlay._(tracks, clips, sections);+ }++ static String _guessType(String href) {+ final ext = href.split('.').last.toLowerCase();+ return switch (ext) {+ 'mp3' => 'audio/mpeg',+ 'm4a' || 'm4b' || 'mp4' || 'aac' => 'audio/mp4',+ 'ogg' || 'oga' || 'opus' => 'audio/ogg',+ 'wav' => 'audio/wav',+ _ => 'application/octet-stream',+ };+ }++ /// The track playing at book time [t].+ int trackAt(double t) {+ var lo = 0, hi = tracks.length - 1, ans = 0;+ while (lo <= hi) {+ final mid = (lo + hi) >> 1;+ if (tracks[mid].start <= t) {+ ans = mid;+ lo = mid + 1;+ } else {+ hi = mid - 1;+ }+ }+ return ans;+ }++ /// The sentence being read at book time [t]: the last one to have started+ /// in the file playing then, so the gap after a sentence keeps it lit.+ OverlayClip? clipAt(double t) {+ if (tracks.isEmpty) return null;+ final track = trackAt(t);+ final local = t - tracks[track].start;+ final list = _byTrack[track];+ var lo = 0, hi = list.length - 1, ans = -1;+ while (lo <= hi) {+ final mid = (lo + hi) >> 1;+ if (clips[list[mid]].begin <= local + 0.001) {+ ans = mid;+ lo = mid + 1;+ } else {+ hi = mid - 1;+ }+ }+ if (ans < 0) return list.isEmpty ? null : clips[list.first];+ return clips[list[ans]];+ }++ /// Book time where [clip] starts.+ double startOf(OverlayClip clip) => tracks[clip.track].start + clip.begin;++ static bool sameDoc(String a, String b) {+ if (a == b) return true;+ final x = a.split('#').first, y = b.split('#').first;+ return x == y || x.endsWith('/$y') || y.endsWith('/$x');+ }++ /// The first sentence whose element is [fragment] in [href], or the first+ /// one in [href] when the fragment isn't narrated.+ OverlayClip? clipFor(String href, String? fragment) {+ OverlayClip? first;+ for (final c in clips) {+ if (!sameDoc(c.textHref, href)) continue;+ first ??= c;+ if (fragment != null && c.fragment == fragment) return c;+ }+ return first;+ }++ /// The chapters Absorb shows. With the book's contents to go by, each+ /// named section starts a chapter and the sections after it that the+ /// contents leave out carry it on (one chapter split over several files),+ /// and an unnamed opening, such as the title read aloud, joins the first+ /// chapter. A book with no usable contents gets one chapter per section.+ List<Map<String, dynamic>> chapters() {+ final named = sections.any((s) => s.label?.trim().isNotEmpty == true);+ final out = <Map<String, dynamic>>[];+ var openingUnnamed = false;+ for (var i = 0; i < sections.length; i++) {+ final s = sections[i];+ final end = i + 1 < sections.length ? sections[i + 1].start : duration;+ if (end <= s.start) continue;+ final label = s.label?.trim() ?? '';+ if (named && label.isEmpty && out.isNotEmpty) {+ out.last['end'] = end;+ continue;+ }+ if (out.isEmpty) openingUnnamed = named && label.isEmpty;+ out.add({+ 'id': out.length,+ 'start': s.start,+ 'end': end,+ 'title': label.isNotEmpty ? label : 'Chapter ${out.length + 1}',+ });+ }+ if (openingUnnamed && out.length > 1) {+ out[1]['start'] = out[0]['start'];+ out.removeAt(0);+ for (var i = 0; i < out.length; i++) {+ out[i]['id'] = i;+ }+ }+ return out;+ }++ /// The sections named from the book's contents: [spine] is every file in+ /// reading order, [labels] the first contents entry pointing into each.+ /// An entry on a file with no narration (a chapter's title page) names+ /// the next narrated file the contents leave out.+ MediaOverlay withContents(List<String> spine, Map<String, String> labels) {+ final names = <int, String?>{};+ String? pending;+ for (final href in spine) {+ final own = labels[href];+ OverlaySection? section;+ for (final s in sections) {+ if (sameDoc(s.href, href)) {+ section = s;+ break;+ }+ }+ if (section == null) {+ if (own != null) pending = own;+ continue;+ }+ names[section.index] = own ?? pending ?? section.label;+ pending = null;+ }+ return MediaOverlay._(tracks, clips, [+ for (final s in sections)+ OverlaySection(s.index, s.href, names.containsKey(s.index) ? names[s.index] : s.label, s.start),+ ]);+ }++ /// Audiobookshelf-shaped audio tracks, with [url] giving each file's address.+ List<Map<String, dynamic>> audioTracks(String Function(OverlayTrack track) url) => [+ for (var i = 0; i < tracks.length; i++)+ {+ 'index': i + 1,+ 'startOffset': tracks[i].start,+ 'duration': tracks[i].duration,+ 'title': tracks[i].href.split('/').last,+ 'contentUrl': url(tracks[i]),+ 'mimeType': tracks[i].mediaType,+ // Numbered, so same-named files in different folders can't collide.+ 'metadata': {'filename': '${(i + 1).toString().padLeft(3, '0')} ${tracks[i].href.split('/').last}'},+ },+ ];++ /// The same narration laid out on each audio file's measured length. A+ /// missing measurement, or one shorter than the file's last sentence, keeps+ /// the length the timings imply.+ MediaOverlay withTrackDurations(List<double?> measured) {+ final laid = <OverlayTrack>[];+ var start = 0.0;+ for (var i = 0; i < tracks.length; i++) {+ final m = i < measured.length ? measured[i] : null;+ final d = m != null && m >= tracks[i].duration - 0.5 ? m : tracks[i].duration;+ laid.add(OverlayTrack(tracks[i].href, tracks[i].mediaType, d, start));+ start += d;+ }+ final first = <int, OverlayClip>{};+ for (final c in clips) {+ first.putIfAbsent(c.section, () => c);+ }+ final secs = [+ for (final s in sections)+ OverlaySection(s.index, s.href, s.label,+ first[s.index] == null ? s.start : laid[first[s.index]!.track].start + first[s.index]!.begin),+ ];+ return MediaOverlay._(laid, clips, secs);+ }++ /// The clip in this narration reading the same sentence as [other], which+ /// may come from an earlier layout of it.+ OverlayClip? sameClip(OverlayClip other) {+ for (final c in clips) {+ if (c.fragment == other.fragment && c.textHref == other.textHref && c.begin == other.begin) return c;+ }+ return null;+ }++ Map<String, dynamic> toJson() => {+ 'tracks': [+ for (final t in tracks)+ {'href': t.href, 'type': t.mediaType, 'duration': t.duration, 'start': t.start},+ ],+ 'clips': [+ for (final c in clips)+ [c.section, c.textHref, c.fragment, c.track, c.begin, c.end],+ ],+ 'sections': [+ for (final s in sections) {'index': s.index, 'href': s.href, 'label': s.label, 'start': s.start},+ ],+ };++ static MediaOverlay? fromJson(Map<String, dynamic> j) {+ try {+ final tracks = [+ for (final t in (j['tracks'] as List<dynamic>).cast<Map<String, dynamic>>())+ OverlayTrack(t['href'] as String, t['type'] as String, (t['duration'] as num).toDouble(),+ (t['start'] as num).toDouble()),+ ];+ final clips = [+ for (final c in (j['clips'] as List<dynamic>).cast<List<dynamic>>())+ OverlayClip(+ section: (c[0] as num).toInt(),+ textHref: c[1] as String,+ fragment: c[2] as String?,+ track: (c[3] as num).toInt(),+ begin: (c[4] as num).toDouble(),+ end: (c[5] as num).toDouble(),+ ),+ ];+ final sections = [+ for (final s in (j['sections'] as List<dynamic>).cast<Map<String, dynamic>>())+ OverlaySection((s['index'] as num).toInt(), s['href'] as String, s['label'] as String?,+ (s['start'] as num).toDouble()),+ ];+ if (tracks.isEmpty || clips.isEmpty) return null;+ return MediaOverlay._(tracks, clips, sections);+ } catch (_) {+ return null;+ }+ }++ /// From BookOrbit's `/epub/:bookId/media-overlay` playlist.+ static MediaOverlay? fromBookOrbit(Map<String, dynamic> playlist) {+ final types = <String, String>{+ for (final r in (playlist['resources'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>())+ if (r['href'] is String) r['href'] as String: r['mediaType'] as String? ?? '',+ };+ final sectionInfo = <int, ({String href, String? label})>{+ for (final s in (playlist['sections'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>())+ if (s['index'] is num && s['href'] is String)+ (s['index'] as num).toInt(): (href: s['href'] as String, label: s['label'] as String?),+ };+ final raw = <_RawClip>[];+ for (final i in (playlist['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {+ final audio = i['audioHref'] as String?;+ final text = i['textHref'] as String?;+ final begin = (i['clipBeginSeconds'] as num?)?.toDouble();+ if (audio == null || text == null || begin == null) continue;+ final section = (i['sectionIndex'] as num?)?.toInt() ?? 0;+ raw.add(_RawClip(section, text, i['textFragment'] as String?, audio, begin,+ (i['clipEndSeconds'] as num?)?.toDouble()));+ if (!sectionInfo.containsKey(section) && i['label'] is String) {+ sectionInfo[section] = (href: text, label: i['label'] as String);+ }+ }+ types.removeWhere((_, v) => v.isEmpty);+ return _build(raw, mediaTypes: types, sectionInfo: sectionInfo);+ }++ /// Straight from an EPUB's package and SMIL files. Null when the book has+ /// no narration.+ static Future<MediaOverlay?> fromEpub(Archive archive) =>+ fromFiles((name) async => _text(archive, name));++ /// The same, with the EPUB's files read through [load] (a local zip, or+ /// range requests to one on the server).+ static Future<MediaOverlay?> fromFiles(Future<String?> Function(String name) load) async {+ final container = await load('META-INF/container.xml');+ if (container == null) return null;+ final rootfile = _rootfileTag.firstMatch(container);+ final opfPath = rootfile == null ? null : _attrs(rootfile.group(0)!)['full-path'];+ if (opfPath == null) return null;+ final opf = await load(opfPath);+ if (opf == null) return null;++ final byId = <String, ({String href, String type, String? overlay, String props})>{};+ for (final m in _itemTag.allMatches(opf)) {+ final a = _attrs(m.group(0)!);+ final id = a['id'], href = a['href'];+ if (id == null || href == null) continue;+ byId[id] = (+ href: _resolve(opfPath, href),+ type: a['media-type'] ?? '',+ overlay: a['media-overlay'],+ props: a['properties'] ?? '',+ );+ }+ final types = {for (final v in byId.values) v.href: v.type};+ final overlayIds = {for (final v in byId.values) if (v.overlay != null) v.overlay!};+ if (overlayIds.isEmpty) return null;+ final labels = await _navLabels(load, byId.values.where((v) => v.props.split(' ').contains('nav')).map((v) => v.href));++ final raw = <_RawClip>[];+ final sectionInfo = <int, ({String href, String? label})>{};+ final spine = <String>[];+ var index = 0;+ for (final m in _itemrefTag.allMatches(opf)) {+ final spineIndex = index++;+ final ref = _attrs(m.group(0)!)['idref'];+ final item = ref == null ? null : byId[ref];+ if (item != null) spine.add(item.href);+ final overlayId = item?.overlay;+ if (item == null || overlayId == null) continue;+ final smilPath = byId[overlayId]?.href;+ final smil = smilPath == null ? null : await load(smilPath);+ if (smil == null) continue;+ sectionInfo[spineIndex] = (href: item.href, label: labels[item.href]);+ for (final par in _parBlock.allMatches(smil)) {+ final body = par.group(1)!;+ final text = _textTag.firstMatch(body);+ final audio = _audioTag.firstMatch(body);+ if (text == null || audio == null) continue;+ final t = _attrs(text.group(0)!), au = _attrs(audio.group(0)!);+ final src = t['src'], audioSrc = au['src'];+ if (src == null || audioSrc == null) continue;+ final begin = parseClock(au['clipbegin']) ?? 0;+ final hash = src.indexOf('#');+ raw.add(_RawClip(+ spineIndex,+ _resolve(smilPath!, src),+ hash < 0 ? null : Uri.decodeComponent(src.substring(hash + 1)),+ _resolve(smilPath, audioSrc),+ begin,+ parseClock(au['clipend']),+ ));+ }+ }+ return _build(raw, mediaTypes: types, sectionInfo: sectionInfo)?.withContents(spine, labels);+ }++ /// [withContents] from BookOrbit's book info: its spine and table of+ /// contents, the first entry in each file.+ MediaOverlay withBookOrbitContents(Map<String, dynamic> info) {+ final spine = [+ for (final s in (info['spine'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>())+ if (s['href'] is String) s['href'] as String,+ ];+ final labels = <String, String>{};+ void visit(Object? node) {+ if (node is! Map) return;+ final href = node['href'], label = node['label'];+ if (href is String && label is String && label.trim().isNotEmpty) {+ labels.putIfAbsent(href.split('#').first, () => label.trim());+ }+ for (final child in (node['children'] as List<dynamic>? ?? const [])) {+ visit(child);+ }+ }++ visit(info['toc']);+ if (spine.isEmpty || labels.isEmpty) return this;+ return withContents(spine, labels);+ }++ /// SMIL clock values: "1:02:03.5", "02:03.5", "12.5s", "250ms", "1.5min",+ /// "2h", or plain seconds.+ static double? parseClock(String? v) {+ if (v == null) return null;+ final s = v.trim();+ if (s.isEmpty) return null;+ if (s.contains(':')) {+ final parts = s.split(':').map((p) => double.tryParse(p.trim())).toList();+ if (parts.any((p) => p == null)) return null;+ return parts.fold<double>(0, (acc, p) => acc * 60 + p!);+ }+ final m = RegExp(r'^([\d.]+)\s*(h|min|s|ms)?$').firstMatch(s);+ if (m == null) return null;+ final n = double.tryParse(m.group(1)!);+ if (n == null) return null;+ return switch (m.group(2)) {+ 'h' => n * 3600,+ 'min' => n * 60,+ 'ms' => n / 1000,+ _ => n,+ };+ }+}++final _attr = RegExp(r'''([\w:.-]+)\s*=\s*("([^"]*)"|'([^']*)')''');+final _itemTag = RegExp(r'<(?:\w+:)?item\b[^>]*>', caseSensitive: false);+final _itemrefTag = RegExp(r'<(?:\w+:)?itemref\b[^>]*>', caseSensitive: false);+final _rootfileTag = RegExp(r'<(?:\w+:)?rootfile\b[^>]*>', caseSensitive: false);+final _parBlock = RegExp(r'<(?:\w+:)?par\b[^>]*>(.*?)</(?:\w+:)?par\s*>', caseSensitive: false, dotAll: true);+final _textTag = RegExp(r'<(?:\w+:)?text\b[^>]*>', caseSensitive: false);+final _audioTag = RegExp(r'<(?:\w+:)?audio\b[^>]*>', caseSensitive: false);+final _navLink = RegExp(r'''<a\b[^>]*href\s*=\s*("([^"]*)"|'([^']*)')[^>]*>(.*?)</a\s*>''', caseSensitive: false, dotAll: true);+final _tags = RegExp(r'<[^>]*>');+final _space = RegExp(r'\s+');++Map<String, String> _attrs(String tag) {+ final out = <String, String>{};+ for (final m in _attr.allMatches(tag)) {+ var name = m.group(1)!.toLowerCase();+ final colon = name.lastIndexOf(':');+ if (colon >= 0 && !name.startsWith('xml')) name = name.substring(colon + 1);+ out.putIfAbsent(name, () => _unescape(m.group(3) ?? m.group(4) ?? ''));+ }+ return out;+}++String _unescape(String s) => s+ .replaceAll('&', '&')+ .replaceAll('"', '"')+ .replaceAll(''', "'")+ .replaceAll('<', '<')+ .replaceAll('>', '>');++String _dir(String path) {+ final i = path.lastIndexOf('/');+ return i < 0 ? '' : path.substring(0, i + 1);+}++/// [href] relative to [base]'s folder, as a path inside the zip.+String _resolve(String base, String href) {+ final clean = Uri.decodeFull(href.split('#').first.split('?').first);+ final parts = <String>[];+ for (final p in '${_dir(base)}$clean'.split('/')) {+ if (p.isEmpty || p == '.') continue;+ if (p == '..') {+ if (parts.isNotEmpty) parts.removeLast();+ } else {+ parts.add(p);+ }+ }+ return parts.join('/');+}++String? _text(Archive archive, String name) {+ final f = archive.findFile(name);+ if (f == null) return null;+ return utf8.decode(f.content as List<int>, allowMalformed: true);+}++/// Chapter names from the navigation document, by the file they point at.+Future<Map<String, String>> _navLabels(+ Future<String?> Function(String name) load, Iterable<String> navPaths) async {+ final out = <String, String>{};+ for (final path in navPaths) {+ final doc = await load(path);+ if (doc == null) continue;+ for (final m in _navLink.allMatches(doc)) {+ final href = m.group(2) ?? m.group(3) ?? '';+ final label = _unescape(m.group(4)!.replaceAll(_tags, ' ')).replaceAll(_space, ' ').trim();+ if (href.isEmpty || label.isEmpty) continue;+ out.putIfAbsent(_resolve(path, href), () => label);+ }+ }+ return out;+}diff --git a/lib/services/narrated_books.dart b/lib/services/narrated_books.dartnew file mode 100644index 00000000..6ee7d603--- /dev/null+++ b/lib/services/narrated_books.dart@@ -0,0 +1,58 @@+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:shared_preferences/shared_preferences.dart';++/// Audiobookshelf books whose EPUB reads itself aloud, as found on this+/// phone (the server only sees an ebook). Held in memory so the quick "is+/// this ebook only" checks can count them as audiobooks. Item ids are unique+/// across servers, so one list serves every account.+class NarratedBooks {+ NarratedBooks._();++ static const _key = 'narrated_books';+ static final Map<String, double> _durations = {};+ static Future<void>? _loading;++ static Future<void> load() => _loading ??= _load();++ static Future<void> _load() async {+ try {+ final raw = (await SharedPreferences.getInstance()).getString(_key);+ if (raw == null) return;+ (jsonDecode(raw) as Map<String, dynamic>).forEach((id, d) {+ if (d is num && d > 0) _durations[id] = d.toDouble();+ });+ } catch (e) {+ debugPrint('[Narration] reading the narrated books failed: $e');+ }+ }++ static bool contains(Object? itemId) => itemId is String && _durations.containsKey(itemId);++ static double? duration(String itemId) => _durations[itemId];++ /// Notes [itemId] as narrated with [duration] seconds, or as not narrated.+ static Future<void> set(String itemId, double? duration) async {+ await load();+ if (duration != null && duration > 0) {+ if (_durations[itemId] == duration) return;+ _durations[itemId] = duration;+ } else if (_durations.remove(itemId) == null) {+ return;+ }+ try {+ await (await SharedPreferences.getInstance()).setString(_key, jsonEncode(_durations));+ } catch (e) {+ debugPrint('[Narration] saving the narrated books failed: $e');+ }+ }++ @visibleForTesting+ static void debugSet(Map<String, double> durations) {+ _loading = Future.value();+ _durations+ ..clear()+ ..addAll(durations);+ }+}diff --git a/lib/services/narration_script.dart b/lib/services/narration_script.dartnew file mode 100644index 00000000..4e1fb6f8--- /dev/null+++ b/lib/services/narration_script.dart@@ -0,0 +1,202 @@+import 'read_along_script.dart';++/// JavaScript for read along on a narrated EPUB: the sentence the narration+/// is on gets lit by its element id, and the reader is told whether it is on+/// the page in view so it can turn. Installed as `window.__absorbMO`.+String narrationBootstrap(int argb, {bool eink = false}) {+ return '(function() {'+ 'var MO = window.__absorbMO = window.__absorbMO || {};'+ "MO.color = '${cssHex(argb)}';"+ "MO.eink = ${eink ? 'true' : 'false'};"+ '$_body'+ '})();';+}++const String _body = r'''+ MO.cur = MO.cur || null;++ MO.css = function() {+ if (MO.eink) {+ return '.absorb-mo-on { text-decoration: underline;' ++ ' text-decoration-thickness: 2px; text-underline-offset: 3px; }';+ }+ return '.absorb-mo-on, .absorb-mo-on * { color: ' + MO.color + ' !important;' ++ ' transition: color 180ms ease; }';+ };++ MO.style = function(doc) {+ try {+ var st = doc.getElementById('absorbNarrationStyle');+ if (!st) {+ st = doc.createElement('style');+ st.id = 'absorbNarrationStyle';+ (doc.head || doc.documentElement).appendChild(st);+ }+ st.textContent = MO.css();+ } catch (e) {}+ };++ MO.views = function() {+ try { return rendition.manager.views.all() || []; } catch (e) { return []; }+ };++ MO.same = function(a, b) {+ a = (a || '').split('#')[0];+ b = (b || '').split('#')[0];+ if (!a || !b) return false;+ if (a === b) return true;+ if (a.length > b.length) return a.slice(-b.length - 1) === '/' + b;+ return b.slice(-a.length - 1) === '/' + a;+ };++ MO.setColor = function(hex) {+ MO.color = hex;+ var vs = MO.views();+ for (var i = 0; i < vs.length; i++) {+ var doc = vs[i].contents && vs[i].contents.document;+ if (doc && doc.getElementById('absorbNarrationStyle')) MO.style(doc);+ }+ };++ // Judged against what is on screen, not the section's iframe, which holds+ // every page of the section side by side (or the whole scroll).+ MO.visible = function(el) {+ var out = { v: true, dir: 0 };+ try {+ var rects = el.getClientRects();+ var rect = rects.length ? rects[0] : el.getBoundingClientRect();+ if (!rect || (rect.width === 0 && rect.height === 0)) return out;+ var fe = el.ownerDocument.defaultView.frameElement;+ var fr = fe ? fe.getBoundingClientRect() : { left: 0, top: 0 };+ var flow = '';+ try { flow = (rendition.settings && rendition.settings.flow) || ''; } catch (e0) {}+ if (flow.indexOf('scrolled') === -1) {+ var x = fr.left + (rect.left + rect.right) / 2;+ out.v = x >= 0 && x < window.innerWidth;+ out.dir = x < 0 ? -1 : (x >= window.innerWidth ? 1 : 0);+ } else {+ var y = fr.top + (rect.top + rect.bottom) / 2;+ out.v = y >= 0 && y < window.innerHeight;+ out.dir = y < 0 ? -1 : (y >= window.innerHeight ? 1 : 0);+ out.low = out.v && y > window.innerHeight * 0.7;+ }+ } catch (e) {}+ return out;+ };++ MO.find = function(href, id) {+ var vs = MO.views();+ for (var i = 0; i < vs.length; i++) {+ var v = vs[i];+ if (!v.section || !MO.same(v.section.href, href)) continue;+ var doc = v.contents && v.contents.document;+ var el = doc ? doc.getElementById(id) : null;+ if (el) return el;+ }+ return null;+ };++ MO.clear = function() {+ if (MO.cur) {+ try { MO.cur.classList.remove('absorb-mo-on'); } catch (e) {}+ MO.cur = null;+ }+ };++ // 'on' when the sentence is on the page in view ('low' when that is near+ // the bottom of a scroll), 'before' or 'after' when it is on another page+ // of the loaded section, 'missing' when its section isn't loaded.+ MO.show = function(href, id) {+ var el = MO.find(href, id);+ if (!el) { MO.clear(); return 'missing'; }+ if (MO.cur !== el) {+ MO.clear();+ MO.style(el.ownerDocument);+ el.classList.add('absorb-mo-on');+ MO.cur = el;+ }+ var vis = MO.visible(el);+ if (vis.low) return 'low';+ return vis.v ? 'on' : (vis.dir < 0 ? 'before' : 'after');+ };++ // Scroll mode: glide the lit sentence up to a quarter of the way down+ // the screen, rather than jumping a whole screen at a time.+ MO.reveal = function(href, id) {+ var el = MO.find(href, id);+ var c = null;+ try { c = rendition.manager && rendition.manager.container; } catch (e0) {}+ if (!el || !c) return false;+ try {+ var fe = el.ownerDocument.defaultView.frameElement;+ var fr = fe ? fe.getBoundingClientRect() : { top: 0 };+ var r = el.getBoundingClientRect();+ var y = fr.top + r.top;+ c.scrollTo({ top: c.scrollTop + y - window.innerHeight * 0.25, behavior: 'smooth' });+ return true;+ } catch (e) {+ return false;+ }+ };++ MO.go = function(href, id) {+ var items = [];+ try { items = book.spine.spineItems || []; } catch (e) {}+ for (var i = 0; i < items.length; i++) {+ if (MO.same(items[i].href, href)) {+ rendition.display(items[i].href + (id ? '#' + id : ''));+ return true;+ }+ }+ return false;+ };++ // The ids around a selection (its own element and those it sits in), then+ // the ones after it, with their section: where "play from here" starts.+ MO.idsAt = function(cfi) {+ var out = { href: '', ids: [] };+ var vs = MO.views();+ for (var i = 0; i < vs.length; i++) {+ var v = vs[i];+ var r = null;+ try { r = v.contents.range(cfi); } catch (e) {}+ if (!r || !v.section) continue;+ out.href = v.section.href;+ var n = r.startContainer;+ while (n && n.nodeType !== 1) n = n.parentNode;+ for (var el = n; el && el.tagName && el.tagName.toLowerCase() !== 'body'; el = el.parentElement) {+ if (el.id) out.ids.push(el.id);+ }+ var doc = v.contents.document;+ var all = doc.body ? doc.body.querySelectorAll('[id]') : [];+ for (var j = 0; j < all.length && out.ids.length < 60; j++) {+ if (n && (n.compareDocumentPosition(all[j]) & 4)) out.ids.push(all[j].id);+ }+ break;+ }+ return JSON.stringify(out);+ };++ // The ids on the page in view, in reading order, with their section: where+ // read along starts the narration when the book isn't playing yet.+ MO.onPage = function() {+ var out = { href: '', ids: [] };+ var vs = MO.views();+ for (var i = 0; i < vs.length && out.ids.length < 300; i++) {+ var v = vs[i];+ var doc = v.contents && v.contents.document;+ if (!doc || !v.section) continue;+ var els = doc.body ? doc.body.querySelectorAll('[id]') : [];+ for (var j = 0; j < els.length && out.ids.length < 300; j++) {+ var vis = MO.visible(els[j]);+ if (vis.v) {+ if (!out.href) out.href = v.section.href;+ if (v.section.href === out.href) out.ids.push(els[j].id);+ } else if (vis.dir > 0 && out.ids.length) {+ break;+ }+ }+ }+ return JSON.stringify(out);+ };+''';diff --git a/lib/services/narration_service.dart b/lib/services/narration_service.dartnew file mode 100644index 00000000..82ae7f1b--- /dev/null+++ b/lib/services/narration_service.dart@@ -0,0 +1,555 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:archive/archive_io.dart';+import 'package:flutter/foundation.dart';+import 'package:path_provider/path_provider.dart';++import 'api_service.dart';+import 'audio_file_duration.dart';+import 'audio_player_service.dart';+import 'download_service.dart';+import 'ebook_cache.dart';+import 'media_overlay.dart';+import 'narrated_books.dart';+import 'remote_zip.dart';+import 'scoped_prefs.dart';++Future<MediaOverlay?> _parseEpub(String path) async {+ final input = InputFileStream(path);+ try {+ return await MediaOverlay.fromEpub(ZipDecoder().decodeStream(input));+ } catch (e) {+ debugPrint('[Narration] reading $path failed: $e');+ return null;+ } finally {+ input.closeSync();+ }+}++List<String> _extract(({String epub, String dir, List<String> hrefs, List<String> names}) job) {+ final input = InputFileStream(job.epub);+ try {+ final archive = ZipDecoder().decodeStream(input);+ Directory(job.dir).createSync(recursive: true);+ final out = <String>[];+ for (var i = 0; i < job.hrefs.length; i++) {+ final entry = archive.findFile(job.hrefs[i]);+ if (entry == null) throw StateError('${job.hrefs[i]} is not in the EPUB');+ final path = '${job.dir}/${job.names[i]}';+ final file = File(path);+ if (!(file.existsSync() && file.lengthSync() == entry.size)) {+ final output = OutputFileStream(path);+ try {+ entry.writeContent(output);+ } finally {+ output.closeSync();+ }+ }+ out.add(path);+ }+ return out;+ } finally {+ input.closeSync();+ }+}++/// Downloading the narration was called off.+class NarrationCancelled implements Exception {+ const NarrationCancelled();+}++/// Narrated EPUBs (EPUB 3 media overlays): the narration as the book's+/// audio, and the sentence timings read along follows.+///+/// BookOrbit knows which books these are and streams their narration. An+/// Audiobookshelf server treats them as plain ebooks, so there it all+/// happens on the phone: the EPUB is looked into with range requests (its+/// index and timings), the reader gets a copy without the audio, and the+/// narration plays once downloaded, fetched as just the audio files out of+/// the EPUB.+class NarrationService {+ NarrationService._();+ static final NarrationService instance = NarrationService._();++ final Map<String, MediaOverlay> _overlays = {};+ final Map<String, double> _known = {};+ static String _key(String itemId) => 'narration_$itemId';+ static String _timedKey(String itemId) => 'narration_timed2_$itemId';++ /// What this phone has found out about the book's EPUB: true when it reads+ /// itself aloud, false when it was checked and doesn't, null when unknown.+ Future<bool?> knownNarrated(String itemId) async {+ final v = _known[itemId] ?? await ScopedPrefs.getDouble(_key(itemId));+ if (v == null) return null;+ _known[itemId] = v;+ return v > 0;+ }++ /// Counts [itemId] as an audiobook from now on. Only for a book with no+ /// audio of its own: one with an audiobook beside its narrated EPUB keeps+ /// that audiobook.+ Future<void> markAudiobook(String itemId, MediaOverlay o) => NarratedBooks.set(itemId, o.duration);++ Future<void> _remember(String itemId, MediaOverlay? o) async {+ if (o != null && hasLocalAudio(itemId) && await ScopedPrefs.getBool(_timedKey(itemId)) != true) {+ o = await _timedFromDownload(itemId, o);+ }+ final v = o == null ? -1.0 : o.duration;+ _known[itemId] = v;+ await ScopedPrefs.setDouble(_key(itemId), v);+ if (o == null || NarratedBooks.contains(itemId)) await NarratedBooks.set(itemId, o?.duration);+ if (o == null) return;+ _overlays[itemId] = o;+ await _save(itemId, o);+ }++ /// Timings read again over a narration already downloaded: laid on its+ /// files' real lengths, with the download's chapters brought up to date.+ Future<MediaOverlay> _timedFromDownload(String itemId, MediaOverlay o) async {+ final paths = DownloadService().getLocalPaths(itemId);+ if (paths == null || paths.length != o.tracks.length) return o;+ final measured = [for (final p in paths) await audioFileDuration(p)];+ final timed = o.withTrackDurations(measured);+ if (measured.every((m) => m != null)) await ScopedPrefs.setBool(_timedKey(itemId), true);+ await DownloadService().updateNarrationTimeline(+ itemId,+ duration: timed.duration,+ chapters: timed.chapters(),+ audioTracks: timed.audioTracks((t) => t.href),+ );+ return timed;+ }++ Future<File> _file(String itemId) async {+ final base = await getApplicationSupportDirectory();+ final dir = Directory('${base.path}/narration');+ if (!dir.existsSync()) dir.createSync(recursive: true);+ return File('${dir.path}/$itemId.v2.json');+ }++ Future<void> _save(String itemId, MediaOverlay o) async {+ try {+ await (await _file(itemId)).writeAsString(jsonEncode(o.toJson()));+ } catch (e) {+ debugPrint('[Narration] saving the timings for $itemId failed: $e');+ }+ }++ /// The narration this phone knows for [itemId], from memory or disk.+ Future<MediaOverlay?> localOverlay(String itemId) async {+ final mem = _overlays[itemId];+ if (mem != null) return mem;+ try {+ final f = await _file(itemId);+ if (!f.existsSync()) return null;+ final o = MediaOverlay.fromJson(jsonDecode(await f.readAsString()) as Map<String, dynamic>);+ if (o != null) _overlays[itemId] = o;+ return o;+ } catch (_) {+ return null;+ }+ }++ /// The narration of [itemId], for read along. [fromServer] when BookOrbit+ /// plays it as the book's audio; otherwise the timings found on this phone.+ Future<({MediaOverlay overlay, bool fromServer})?> overlayFor(+ ApiService api,+ String itemId, {+ File? epub,+ }) async {+ if (api is BookOrbitApiService) {+ final o = await api.narrationFor(itemId);+ if (o != null) {+ _overlays[itemId] = o;+ unawaited(_save(itemId, o));+ return (overlay: o, fromServer: true);+ }+ final saved = await localOverlay(itemId);+ return saved == null ? null : (overlay: saved, fromServer: true);+ }+ final known = await localOverlay(itemId);+ if (known != null) return (overlay: known, fromServer: false);+ if (await knownNarrated(itemId) == false) return null;+ if (epub == null || !epub.existsSync()) return null;+ final o = await compute(_parseEpub, epub.path);+ await _remember(itemId, o == null || o.isEmpty ? null : o);+ final found = _overlays[itemId];+ if (found == null) return null;+ debugPrint('[Narration] $itemId reads itself aloud: ${found.tracks.length} files, '+ '${found.clips.length} sentences, ${found.duration.toStringAsFixed(0)}s');+ return (overlay: found, fromServer: false);+ }++ /// [item] with its narration as audio, the way BookOrbit's books arrive:+ /// a duration (so it isn't ebook-only), chapters, and the narration marker.+ Map<String, dynamic> withNarration(Map<String, dynamic> item, MediaOverlay o) {+ final media = Map<String, dynamic>.from(item['media'] as Map? ?? const {});+ if (((media['duration'] as num?) ?? 0) > 0) return item;+ media['duration'] = o.duration;+ media['chapters'] = o.chapters();+ media['narration'] = {'duration': o.duration, 'local': true};+ return {...item, 'media': media};+ }++ RemoteZip? _openZip;+ String? _openZipItem;+ DateTime _openZipAt = DateTime(0);++ /// The EPUB on the server, its index read once. Opened again after a while+ /// so the token in its URL stays current.+ Future<RemoteZip> _remote(ApiService api, String itemId, Map<String, dynamic> ebookFile) async {+ final open = _openZip;+ if (_openZipItem == itemId &&+ open != null &&+ DateTime.now().difference(_openZipAt) < const Duration(minutes: 10)) {+ return open;+ }+ final ino = ebookFile['ino'] as String?;+ if (ino == null) throw RemoteZipException('no ebook file');+ final zip = await RemoteZip.open(Uri.parse(api.buildFileUrl(itemId, ino)), headers: api.mediaHeaders);+ _openZip?.close();+ _openZip = zip;+ _openZipItem = itemId;+ _openZipAt = DateTime.now();+ return zip;+ }++ static String _ext(String href) {+ final name = href.split('/').last;+ final dot = name.lastIndexOf('.');+ return dot < 0 ? '' : name.substring(dot).toLowerCase();+ }++ /// Looks into an Audiobookshelf book's EPUB on the server (its index and+ /// timings only) to see whether it reads itself aloud. Remembered, so it is+ /// asked once per book.+ Future<MediaOverlay?> probe(ApiService api, Map<String, dynamic> item) async {+ final itemId = item['id'] as String?;+ final ebookFile = resolveEbookFile(item);+ if (itemId == null || ebookFile == null || api.isBookOrbit) return null;+ if (ebookExtFromFile(ebookFile) != '.epub') return null;+ if (await knownNarrated(itemId) == false) return null;+ final local = await localOverlay(itemId);+ if (local != null) return local;+ final started = DateTime.now();+ try {+ final zip = await _remote(api, itemId, ebookFile);+ final o = await MediaOverlay.fromFiles((name) async {+ final e = zip.entry(name);+ return e == null ? null : utf8.decode(await zip.read(e), allowMalformed: true);+ });+ debugPrint('[Narration] looked into $itemId on the server in '+ '${DateTime.now().difference(started).inMilliseconds}ms: '+ '${o == null ? 'no narration' : '${o.clips.length} sentences, ${o.duration.toStringAsFixed(0)}s'} '+ '(${zip.length} bytes, ${zip.entries.length} files)');+ final found = o == null || o.isEmpty ? null : o;+ await _remember(itemId, found);+ return found == null ? null : _overlays[itemId];+ } catch (e) {+ debugPrint('[Narration] could not look into $itemId on the server: $e');+ return null;+ }+ }++ /// The EPUB the reader opens. A narrated book on Audiobookshelf gets a copy+ /// without its audio, pulled from the server a piece at a time, so a+ /// several hundred MB file opens in seconds. Anything else is the usual+ /// cached download.+ Future<File> readerFile(+ ApiService api,+ String itemId,+ Map<String, dynamic> ebookFile,+ String title,+ ) async {+ final cached = await ebookCacheFileFor(itemId, ebookFile);+ if (cached.existsSync() && cached.lengthSync() > 0) {+ if (_slimFailed.contains(itemId) || !await _cachedWithAudio(api, itemId, ebookFile, cached)) {+ debugPrint('[EbookCache] cache hit item=$itemId bytes=${cached.lengthSync()}');+ return cached;+ }+ // An earlier copy kept the narration inside: hundreds of MB the reader+ // can't open. Swap in one without it, keeping the old one if that fails.+ final aside = File('${cached.path}.withaudio');+ debugPrint('[EbookCache] $itemId is cached with its narration audio '+ '(${cached.lengthSync()} bytes) - getting a copy without it');+ await cached.rename(aside.path);+ try {+ final slim = await _freshReaderFile(api, itemId, ebookFile, title, cached, wholeFallback: false);+ if (aside.existsSync()) await aside.delete();+ return slim;+ } catch (e) {+ debugPrint('[EbookCache] copy without audio failed for $itemId ($e) - keeping the full one');+ _slimFailed.add(itemId);+ if (cached.existsSync()) await cached.delete();+ await aside.rename(cached.path);+ return cached;+ }+ }+ return _freshReaderFile(api, itemId, ebookFile, title, cached);+ }++ /// A cached EPUB that still holds the narration: big, the book reads+ /// itself aloud, and the copy is about the size of the server's file.+ Future<bool> _cachedWithAudio(+ ApiService api,+ String itemId,+ Map<String, dynamic> ebookFile,+ File cached,+ ) async {+ if (ebookExtFromFile(ebookFile) != '.epub') return false;+ final length = cached.lengthSync();+ if (length < 50 * 1024 * 1024) return false;+ final narrated =+ api.isBookOrbit ? _bookOrbitNarrated(api, itemId, ebookFile) : await knownNarrated(itemId) == true;+ if (!narrated) return false;+ final size = ((ebookFile['metadata'] as Map?)?['size'] as num?)?.toInt() ?? 0;+ return size <= 0 || length >= size * 0.9;+ }++ Future<File> _freshReaderFile(+ ApiService api,+ String itemId,+ Map<String, dynamic> ebookFile,+ String title,+ File cached, {+ bool wholeFallback = true,+ }) async {+ if (ebookExtFromFile(ebookFile) == '.epub') {+ final slim = api.isBookOrbit+ ? await _slimBookOrbit(api, itemId, ebookFile, cached)+ : await _slimAbs(api, itemId, ebookFile, cached);+ if (slim != null) return slim;+ }+ // BookOrbit's own download leaves the audio out, when it can build it.+ if (!wholeFallback && !api.isBookOrbit) throw StateError('no copy without the audio');+ return fetchEbookToCache(api, itemId, ebookFile, title);+ }++ final Set<String> _slimFailed = {};++ static const _audioExts = {'.mp3', '.m4a', '.m4b', '.mp4', '.aac', '.ogg', '.oga', '.opus', '.wav', '.flac'};++ bool _bookOrbitNarrated(ApiService api, String itemId, Map<String, dynamic> ebookFile) {+ final ino = ebookFile['ino'] as String?;+ return api.isBookOrbit && ino != null && api.buildReaderEbookUrl(itemId, ino) != api.buildEbookUrl(itemId, ino);+ }++ Future<File?> _slimAbs(ApiService api, String itemId, Map<String, dynamic> ebookFile, File cached) async {+ final o = await probe(api, {+ 'id': itemId,+ 'media': {'ebookFile': ebookFile},+ });+ if (o == null) return null;+ final started = DateTime.now();+ try {+ final zip = await _remote(api, itemId, ebookFile);+ final audio = o.tracks.map((t) => t.href).toSet();+ await zip.writeCopy(cached, (e) => !audio.contains(e.name));+ debugPrint('[EbookCache] narrated EPUB $itemId opened without its audio: '+ '${cached.lengthSync()} of ${zip.length} bytes in '+ '${DateTime.now().difference(started).inMilliseconds}ms');+ return cached;+ } catch (e) {+ debugPrint('[EbookCache] copy without audio failed for $itemId ($e) - downloading it whole');+ return null;+ }+ }++ /// BookOrbit builds a copy without the audio itself, but turns big books+ /// away, so the copy is made here from its file with ranges, as on+ /// Audiobookshelf.+ Future<File?> _slimBookOrbit(ApiService api, String itemId, Map<String, dynamic> ebookFile, File cached) async {+ if (!_bookOrbitNarrated(api, itemId, ebookFile)) return null;+ final started = DateTime.now();+ RemoteZip? zip;+ try {+ zip = await RemoteZip.open(Uri.parse(api.buildEbookUrl(itemId, ebookFile['ino'] as String)));+ await zip.writeCopy(cached, (e) => !_audioExts.contains(_ext(e.name)));+ debugPrint('[EbookCache] narrated EPUB $itemId opened without its audio: '+ '${cached.lengthSync()} of ${zip.length} bytes in '+ '${DateTime.now().difference(started).inMilliseconds}ms');+ return cached;+ } catch (e) {+ debugPrint('[EbookCache] copy without audio failed for $itemId ($e) - asking BookOrbit for one');+ return null;+ } finally {+ zip?.close();+ }+ }++ /// Narration already on the phone as the book's audio.+ bool hasLocalAudio(String itemId) =>+ (DownloadService().getLocalPaths(itemId)?.isNotEmpty ?? false);++ /// Puts an Audiobookshelf book's narration on the phone as its audio:+ /// just the audio files, fetched out of the EPUB on the server. Servers+ /// without range requests fall back to the whole EPUB. False when the EPUB+ /// has no narration.+ Future<bool> prepareLocal(+ ApiService api,+ Map<String, dynamic> item, {+ void Function(double progress)? onProgress,+ }) async {+ final itemId = item['id'] as String?;+ final ebookFile = resolveEbookFile(item);+ if (itemId == null || ebookFile == null) return false;+ final o = await probe(api, item);+ if (o != null) {+ try {+ await _fetchAudio(api, item, itemId, ebookFile, o, onProgress);+ return true;+ } on NarrationCancelled {+ rethrow;+ } catch (e) {+ debugPrint('[Narration] fetching the audio out of the EPUB failed ($e) - using the whole file');+ }+ }+ if (await knownNarrated(itemId) == false) return false;+ return _extractFromWholeEpub(api, item, itemId, ebookFile);+ }++ List<String> _trackNames(List<Map<String, dynamic>> tracks) => [+ for (final t in tracks)+ ((t['metadata'] as Map)['filename'] as String).replaceAll(RegExp(r'[\\/:*?"<>|]'), '_'),+ ];++ /// The narration laid on the audio files' real lengths, saved, and kept as+ /// the book's download.+ Future<void> _keep(+ ApiService api,+ Map<String, dynamic> item,+ String itemId,+ MediaOverlay o,+ String dir,+ List<String> paths,+ ) async {+ final measured = <double?>[];+ for (final p in paths) {+ measured.add(await audioFileDuration(p));+ }+ final timed = o.withTrackDurations(measured);+ debugPrint('[Narration] $itemId measured ${measured.where((m) => m != null).length} of '+ '${paths.length} files: ${o.duration.toStringAsFixed(0)}s from the timings, '+ '${timed.duration.toStringAsFixed(0)}s from the audio');+ await _remember(itemId, timed);+ await markAudiobook(itemId, timed);+ if (measured.every((m) => m != null)) await ScopedPrefs.setBool(_timedKey(itemId), true);+ await DownloadService().registerNarration(+ api: api,+ itemId: itemId,+ item: item,+ dirPath: dir,+ paths: paths,+ duration: timed.duration,+ chapters: timed.chapters(),+ audioTracks: timed.audioTracks((t) => t.href),+ );+ }++ Future<void> _fetchAudio(+ ApiService api,+ Map<String, dynamic> item,+ String itemId,+ Map<String, dynamic> ebookFile,+ MediaOverlay o,+ void Function(double progress)? onProgress,+ ) async {+ final zip = await _remote(api, itemId, ebookFile);+ final names = _trackNames(o.audioTracks((t) => t.href));+ final dir = '${await DownloadService().downloadBasePath}/$itemId';+ Directory(dir).createSync(recursive: true);+ final entries = <RemoteZipEntry>[];+ for (final t in o.tracks) {+ final e = zip.entry(t.href);+ if (e == null) throw RemoteZipException('${t.href} is not in the EPUB');+ entries.add(e);+ }+ final total = entries.fold<int>(0, (s, e) => s + e.compressedSize);+ var before = 0;+ final paths = <String>[];+ final started = DateTime.now();+ for (var i = 0; i < entries.length; i++) {+ final out = File('$dir/${names[i]}');+ if (!(out.existsSync() && out.lengthSync() == entries[i].size)) {+ final base = before;+ await zip.download(entries[i], out,+ onBytes: (done) => onProgress?.call(total == 0 ? 0 : (base + done) / total));+ }+ before += entries[i].compressedSize;+ onProgress?.call(total == 0 ? 0 : before / total);+ paths.add(out.path);+ }+ debugPrint('[Narration] fetched ${paths.length} audio files ($total bytes) out of the EPUB for '+ '$itemId in ${DateTime.now().difference(started).inSeconds}s');+ await _keep(api, item, itemId, o, dir, paths);+ }++ Future<bool> _extractFromWholeEpub(+ ApiService api,+ Map<String, dynamic> item,+ String itemId,+ Map<String, dynamic> ebookFile,+ ) async {+ final metadata = (item['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?;+ final title = metadata?['title'] as String? ?? '';+ final epub = await fetchEbookToCache(api, itemId, ebookFile, title);+ final o = await compute(_parseEpub, epub.path);+ if (o == null || o.isEmpty) {+ await _remember(itemId, null);+ return false;+ }+ final names = _trackNames(o.audioTracks((t) => t.href));+ final dir = '${await DownloadService().downloadBasePath}/$itemId';+ final started = DateTime.now();+ final paths = await compute(_extract, (+ epub: epub.path,+ dir: dir,+ hrefs: o.tracks.map((t) => t.href).toList(),+ names: names,+ ));+ debugPrint('[Narration] took ${paths.length} audio files out of the whole EPUB for $itemId '+ 'in ${DateTime.now().difference(started).inSeconds}s');+ await _keep(api, item, itemId, o, dir, paths);+ return true;+ }++ /// Plays the narration, from the sentence [from] when given (read along+ /// starting at the page in view, "play from here"). An Audiobookshelf book+ /// plays it once downloaded: false until then.+ Future<bool> play(+ ApiService api,+ Map<String, dynamic> item, {+ OverlayClip? from,+ String? coverUrl,+ }) async {+ final itemId = item['id'] as String?;+ if (itemId == null) return false;+ if (!api.isBookOrbit && !hasLocalAudio(itemId)) return false;+ final o = await localOverlay(itemId);+ double? startTime;+ if (from != null && o != null) {+ final c = o.sameClip(from);+ if (c != null) startTime = o.startOf(c);+ }+ final shaped = o == null || api.isBookOrbit ? item : withNarration(item, o);+ final media = shaped['media'] as Map<String, dynamic>? ?? const {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};+ final error = await AudioPlayerService().playItem(+ api: api,+ itemId: itemId,+ title: metadata['title'] as String? ?? '',+ author: metadata['authorName'] as String? ?? '',+ coverUrl: coverUrl ?? api.getCoverUrl(itemId),+ totalDuration: (media['duration'] as num?)?.toDouble() ?? 0,+ chapters: media['chapters'] as List<dynamic>? ?? const [],+ startTime: startTime ?? 0,+ forceStartTime: startTime != null,+ libraryId: item['libraryId'] as String?,+ fromUi: true,+ );+ if (error != null) debugPrint('[Narration] play $itemId failed: $error');+ return error == null;+ }+}diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 4fbac1d6..9389994b 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -3,6 +3,7 @@ import 'dart:ui' as ui;import 'package:flutter/material.dart';import 'package:just_audio/just_audio.dart';import 'package:shared_preferences/shared_preferences.dart';+import 'narrated_books.dart';import 'scoped_prefs.dart';import '../widgets/card_button_config.dart';@@ -210,6 +211,17 @@ class PlayerSettings {// (raw SharedPreferences, not per-account) because the downloaded Whisper// model is shared across every profile on the device.+ /// Moves the ebook to where listening stopped, and the audiobook to where+ /// reading stopped, for books with both (transcription does the finding).+ static Future<bool> getSyncReadingListening() async {+ final prefs = await SharedPreferences.getInstance();+ return prefs.getBool('syncReadingListening') ?? false;+ }+ static Future<void> setSyncReadingListening(bool value) async {+ final prefs = await SharedPreferences.getInstance();+ await prefs.setBool('syncReadingListening', value);+ }+static Future<bool> getTranscriptionEnabled() async {final prefs = await SharedPreferences.getInstance();return prefs.getBool('transcriptionEnabled') ?? false;@@ -1359,11 +1371,14 @@ class PlayerSettings {/// Check if an item has no audio content./// For minified responses (library list), duration == 0 means no audio files./// For full responses (detail sheet), we also check ebookFile + audioFiles.- static bool isEbookOnly(Map<String, dynamic> item) {+ /// [countNarration] off asks about the server's own audio only, leaving+ /// out an EPUB found to read itself aloud.+ static bool isEbookOnly(Map<String, dynamic> item, {bool countNarration = true}) {// Podcasts are never eBook-only (minified podcasts lack duration/audioFiles)if ((item['mediaType'] as String?) == 'podcast') return false;// BookOrbit Book Dock files have no tracks until they are filed.if (item['bookDock'] != null) return false;+ if (countNarration && NarratedBooks.contains(item['id'])) return false;final media = item['media'] as Map<String, dynamic>? ?? {};final duration = (media['duration'] as num?)?.toDouble() ?? 0;if (duration > 0) return false; // Has audio contentdiff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dartindex 461c3455..b6f41b35 100644--- a/lib/services/progress_sync_service.dart+++ b/lib/services/progress_sync_service.dart@@ -507,6 +507,10 @@ class ProgressSyncService {}}+ /// Forget a queued position the server has since moved past, so the retry+ /// can't put the older place back.+ Future<void> dropPendingEbookProgress(String itemId) => _removePendingEbook(itemId);+Future<void> _removePendingEbook(String itemId) async {final pending = await getPendingEbookProgress();if (pending.remove(itemId) == null) return;diff --git a/lib/services/read_listen_sync.dart b/lib/services/read_listen_sync.dartnew file mode 100644index 00000000..611b9ea6--- /dev/null+++ b/lib/services/read_listen_sync.dart@@ -0,0 +1,461 @@+import 'dart:async';+import 'dart:isolate';+import 'dart:math';++import 'package:flutter/material.dart';+import 'package:provider/provider.dart';++import '../l10n/app_localizations.dart';+import '../main.dart' show rootNavigatorKey;+import '../providers/auth_provider.dart';+import '../providers/library_provider.dart';+import '../widgets/overlay_toast.dart';+import 'api_service.dart';+import 'audio_locator.dart';+import 'audio_player_service.dart';+import 'ebook_cache.dart';+import 'ebook_history.dart';+import 'epub_book_text.dart';+import 'narration_service.dart';+import 'progress_sync_service.dart';+import 'scoped_prefs.dart';+import 'sync_point_store.dart';+import 'transcription_service.dart';++/// An EPUB file read with no reader open, as Find in audiobook's view of+/// the book.+class _FileBookText implements BookTextSource {+ _FileBookText(this.book);++ final EpubBookText book;++ @override+ Future<List<String>> spineHrefs() async => book.spine;++ @override+ String? chapterForHref(String href) => book.chapterForHref(href);++ @override+ Future<List<double>> sectionCharCounts(int from, int to) async => [+ for (var i = from; i <= to && i < book.spine.length; i++) book.sectionLength(i).toDouble(),+ ];++ @override+ Future<Map<String, dynamic>?> locateTranscriptInSection(int si, String transcript) async {+ final m = matchTranscript(book.sectionText(si), transcript);+ return m == null ? null : {'s': m.s, 'e': m.e, 'fine': m.fine};+ }+}++/// Where the words just heard are in the book, worked out in the background+/// isolate: the spot's CFI and place in the book, and where the saved ebook+/// spot [current] is, to compare.+typedef _Placed = ({+ String cfi,+ double fraction,+ int si,+ int offset,+ int? currentSi,+ int? currentOffset,+ double? currentFraction,+ String? currentChapter,+ bool narrated,+});++_Placed? _placeInBook(String path, String transcript, double near, String? current) {+ final book = EpubBookText.open(path);+ if (book == null) return null;+ try {+ final hit = book.findPassage(transcript, near: near);+ if (hit == null) return null;+ final cfi = book.cfiAt(hit.si, hit.e);+ if (cfi == null) return null;+ final now = current == null ? null : book.locate(current);+ return (+ cfi: cfi,+ fraction: book.fraction(hit.si, hit.e),+ si: hit.si,+ offset: hit.e,+ currentSi: now?.si,+ currentOffset: now?.offset,+ currentFraction: now == null ? null : book.fraction(now.si, now.offset),+ currentChapter: now == null || now.si >= book.spine.length ? null : book.chapterForHref(book.spine[now.si]),+ narrated: book.hasMediaOverlays,+ );+ } finally {+ book.close();+ }+}++/// Which side a sync is moving: the ebook to the audio, or the audio to the+/// page.+enum SyncTarget { ebook, audio }++/// Where the CFI [cfi] is in the book, worked out in the background isolate+/// (placing it in the whole book reads every section).+typedef _Spot = ({int si, int offset, int total, String href, double pct, bool narrated});++_Spot? _spotInBook(String path, String cfi) {+ final book = EpubBookText.open(path);+ if (book == null) return null;+ try {+ final at = book.locate(cfi);+ if (at == null) return null;+ return (+ si: at.si,+ offset: at.offset,+ total: book.sectionLength(at.si),+ href: at.si < book.spine.length ? book.spine[at.si] : '',+ pct: book.fraction(at.si, at.offset),+ narrated: book.hasMediaOverlays,+ );+ } finally {+ book.close();+ }+}++Future<_Placed?> _placeAsync(String path, String transcript, double near, String? current) =>+ Isolate.run(() => _placeInBook(path, transcript, near, current));++Future<_Spot?> _spotAsync(String path, String cfi) => Isolate.run(() => _spotInBook(path, cfi));++/// Keeps an audiobook and its separate ebook at the same spot, when the+/// setting is on. When listening stops (paused for a couple of minutes,+/// stopped, or another book started), the ebook moves to the words last+/// heard. When the reader closes after reading, the audiobook moves to the+/// page. Only ever forward, found by transcribing the audio the way Find in+/// ebook and Find in audiobook do, one book at a time, with a toast when the+/// app is on screen. An EPUB that narrates itself keeps the two together+/// already, so it is left alone.+class ReadListenSync {+ ReadListenSync._();+ static final ReadListenSync instance = ReadListenSync._();++ static const _stopWait = Duration(minutes: 2);++ Timer? _stopTimer;+ String? _item;+ bool _wasPlaying = false;+ bool _started = false;+ Future<void> _queue = Future.value();+ final Set<String> _readerOpen = {};+ final Map<String, Completer<double?>> _finding = {};+ final Map<String, DateTime> _playedAt = {};++ /// Books being synced right now, and which side is moving, for the details+ /// sheet to show.+ final ValueNotifier<Map<String, SyncTarget>> syncing = ValueNotifier(const {});++ void _setSyncing(String itemId, SyncTarget? to) {+ final now = Map<String, SyncTarget>.from(syncing.value);+ if (to == null) {+ if (now.remove(itemId) == null) return;+ } else {+ if (now[itemId] == to) return;+ now[itemId] = to;+ }+ syncing.value = now;+ }++ static String _heardKey(String itemId) => 'rls_heard_$itemId';+ static String _readKey(String itemId) => 'rls_read_$itemId';++ void start() {+ if (_started) return;+ _started = true;+ AudioPlayerService().addListener(_onPlayer);+ }++ void _onPlayer() {+ final p = AudioPlayerService();+ final id = p.hasBook && p.currentEpisodeId == null ? p.currentItemId : null;+ if (id != _item) {+ final left = _item;+ _item = id;+ _wasPlaying = false;+ _stopTimer?.cancel();+ _stopTimer = null;+ if (left != null) {+ debugPrint('[SyncSpot] $left: ${id == null ? 'playback stopped' : 'another book started'} - checking the ebook');+ _run(() => _audioToEbook(left));+ }+ }+ if (id == null) return;+ final playing = p.isPlaying;+ if (playing == _wasPlaying) return;+ _wasPlaying = playing;+ if (playing) _playedAt[id] = DateTime.now();+ _stopTimer?.cancel();+ _stopTimer = null;+ if (!playing) {+ _stopTimer = Timer(_stopWait, () {+ _stopTimer = null;+ final now = AudioPlayerService();+ if (_item == id && !now.isPlaying) {+ debugPrint('[SyncSpot] $id: paused for ${_stopWait.inMinutes} minutes - checking the ebook');+ _run(() => _audioToEbook(id));+ }+ });+ }+ }++ void _run(Future<void> Function() job) {+ _queue = _queue.then((_) => job()).catchError((Object e) {+ debugPrint('[SyncSpot] failed: $e');+ });+ }++ /// The reader shows this book now and keeps its own spot meanwhile.+ void readerOpened(String itemId) => _readerOpen.add(itemId);++ /// The reader closed on [cfi]; [moved] when pages were turned since it+ /// opened. Reading ahead of the audio moves the audio there.+ void readerClosed(String itemId, String? cfi, {required bool moved}) {+ _readerOpen.remove(itemId);+ if (cfi == null || cfi.isEmpty || !moved) return;+ debugPrint('[SyncSpot] $itemId: reader closed after reading - checking the audio');+ final done = _finding[itemId] = Completer<double?>();+ _run(() async {+ double? t;+ try {+ t = await _ebookToAudio(itemId, cfi);+ } finally {+ if (identical(_finding[itemId], done)) _finding.remove(itemId);+ done.complete(t);+ }+ });+ }++ /// The audio spot being found for [itemId] since its reader closed, for a+ /// play that should start there. Null when nothing is being found.+ Future<double?>? audioSpotBeingFound(String itemId) => _finding[itemId]?.future;++ /// For a reader opening while the audio is ahead: the ebook spot moved to+ /// the words last heard, or null when it stays put.+ Future<String?> ebookSpotForReader(String itemId) {+ final done = Completer<String?>();+ _run(() async => done.complete(await _audioToEbook(itemId, fromReader: true)));+ return done.future;+ }++ static ApiService? get _api {+ final ctx = rootNavigatorKey.currentContext;+ return ctx?.read<AuthProvider>().apiService ?? AudioPlayerService().currentApi;+ }++ static bool get _onScreen => WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;++ static void _toast(String Function(AppLocalizations l) text, IconData icon, {VoidCallback? onTap}) {+ final ctx = rootNavigatorKey.currentContext;+ if (ctx == null || !_onScreen) return;+ final l = AppLocalizations.of(ctx);+ if (l != null) showOverlayToast(ctx, text(l), icon: icon, onTap: onTap);+ }++ static Future<bool> _canListen(String itemId) async {+ if (!await PlayerSettings.getSyncReadingListening()) return false;+ if (!await PlayerSettings.getTranscriptionEnabled()) {+ debugPrint('[SyncSpot] $itemId: transcription is off - not syncing');+ return false;+ }+ final t = TranscriptionService.instance;+ if (!t.canTranscribeBook(itemId)) {+ debugPrint('[SyncSpot] $itemId: this book can not be transcribed - not syncing');+ return false;+ }+ for (final size in TranscriptionModelSize.values) {+ if (await t.isModelDownloaded(size)) return true;+ }+ debugPrint('[SyncSpot] $itemId: no transcription model downloaded - not syncing');+ return false;+ }++ /// The audiobook and ebook of [itemId], when it has both and isn't done.+ static Future<({Map<String, dynamic> item, Map<String, dynamic> ebook, double duration})?> _book(+ ApiService api, String itemId) async {+ final item = await api.getLibraryItem(itemId);+ if (item == null) return null;+ final media = item['media'] as Map<String, dynamic>? ?? const {};+ // A book whose audio is its EPUB's own narration keeps them together.+ if (media['narration'] != null) return null;+ final duration = (media['duration'] as num?)?.toDouble() ?? 0;+ final ebook = resolveEbookFile(item);+ if (duration <= 0 || ebook == null || ebookExtFromFile(ebook) != '.epub') return null;+ final progress = item['userMediaProgress'] as Map<String, dynamic>?;+ if (progress?['isFinished'] == true) return null;+ return (item: item, ebook: ebook, duration: duration);+ }++ static Future<double?> _heardAt(String itemId) async {+ final p = AudioPlayerService();+ if (p.currentItemId == itemId && p.currentEpisodeId == null) return p.position.inMilliseconds / 1000.0;+ final local = await ProgressSyncService().getLocal(itemId);+ return (local?['currentTime'] as num?)?.toDouble();+ }++ static Future<String?> _ebookSpot(ApiService api, String itemId) async {+ final pending = (await ProgressSyncService().getPendingEbookProgress())[itemId];+ final queued = pending?['loc'] as String?;+ if (queued != null && queued.startsWith('epubcfi(')) return queued;+ final ctx = rootNavigatorKey.currentContext;+ final local = ctx?.read<LibraryProvider>().getProgressData(itemId)?['ebookLocation'] as String?;+ try {+ final server = (await api.getEbookPosition(itemId))?['ebookLocation'] as String?;+ if (server != null && server.startsWith('epubcfi(')) return server;+ } catch (_) {}+ return local != null && local.startsWith('epubcfi(') ? local : null;+ }++ /// Listening stopped: the ebook spot moves to the words last heard, when+ /// those are past it. Returns the new spot.+ Future<String?> _audioToEbook(String itemId, {bool fromReader = false}) async {+ try {+ if (!fromReader && _readerOpen.contains(itemId)) return null;+ if (!await _canListen(itemId)) return null;+ final api = _api;+ if (api == null) return null;+ final heard = await _heardAt(itemId);+ if (heard == null || heard < 30) return null;+ final last = await ScopedPrefs.getDouble(_heardKey(itemId));+ if (last != null && (heard - last).abs() < 20) return null;+ final book = await _book(api, itemId);+ if (book == null) return null;+ final started = DateTime.now();+ _setSyncing(itemId, SyncTarget.ebook);+ final title = ((book.item['media'] as Map?)?['metadata'] as Map?)?['title'] as String? ?? '';+ final epub = await NarrationService.instance.readerFile(api, itemId, book.ebook, title);+ final from = max(0.0, heard - 15);+ final segs = await TranscriptionService.instance.transcribeWindowSegments(+ itemId: itemId,+ startSeconds: from,+ windowSeconds: heard - from,+ preferAccuracy: false,+ );+ final transcript = segs.map((s) => s.text).join(' ').trim();+ if (transcript.split(RegExp(r'\s+')).length < 5) return null;+ final current = await _ebookSpot(api, itemId);+ final near = (heard / book.duration).clamp(0.0, 1.0);+ final placed = await _placeAsync(epub.path, transcript, near, current);+ await ScopedPrefs.setDouble(_heardKey(itemId), heard);+ if (placed == null) {+ debugPrint('[SyncSpot] $itemId: the words at ${heard.toStringAsFixed(0)}s are not in the ebook');+ return null;+ }+ // BookOrbit moves a narrated EPUB along with the audiobook itself.+ if (placed.narrated && api.isBookOrbit) return null;+ final cs = placed.currentSi, co = placed.currentOffset;+ if (cs != null && co != null && (cs > placed.si || (cs == placed.si && co >= placed.offset))) {+ debugPrint('[SyncSpot] $itemId: the ebook is already at or past ${heard.toStringAsFixed(0)}s');+ return null;+ }+ if (current != null) {+ await EbookHistory.instance.record(itemId,+ cfi: current,+ reason: EbookSpotReason.beforeSync,+ progress: placed.currentFraction,+ chapter: placed.currentChapter);+ }+ await ProgressSyncService().pushEbookProgress(api, itemId, location: placed.cfi, progress: placed.fraction);+ rootNavigatorKey.currentContext+ ?.read<LibraryProvider>()+ .applyLocalEbookProgress(itemId, location: placed.cfi, progress: placed.fraction);+ await ScopedPrefs.setString(_readKey(itemId), placed.cfi);+ await SyncPointStore.instance.add(+ itemId,+ SyncPoint(t: heard, si: placed.si, off: placed.offset.toDouble(), src: 'e', err: 3,+ at: DateTime.now().millisecondsSinceEpoch),+ audioDuration: book.duration,+ );+ debugPrint('[SyncSpot] $itemId: ebook moved to ${heard.toStringAsFixed(0)}s '+ '(section ${placed.si}, ${(placed.fraction * 100).toStringAsFixed(1)}%) '+ 'in ${DateTime.now().difference(started).inMilliseconds}ms');+ if (!fromReader) _toast((l) => l.syncEbookMoved, Icons.menu_book_rounded);+ return placed.cfi;+ } finally {+ _setSyncing(itemId, null);+ }+ }++ /// The reader closed after reading: the audiobook moves to the page, when+ /// the page is past it. Returns the new spot.+ Future<double?> _ebookToAudio(String itemId, String cfi) async {+ try {+ final began = DateTime.now();+ if (!await _canListen(itemId)) return null;+ if (await ScopedPrefs.getString(_readKey(itemId)) == cfi) return null;+ final api = _api;+ if (api == null) return null;+ final player = AudioPlayerService();+ if (player.currentItemId == itemId && player.currentEpisodeId == null && player.isPlaying) return null;+ final heard = await _heardAt(itemId) ?? 0;+ final book = await _book(api, itemId);+ if (book == null) return null;+ final file = await ebookCacheFileFor(itemId, book.ebook);+ if (!file.existsSync()) return null;+ final spot = await _spotAsync(file.path, cfi);+ if (spot == null || (spot.narrated && api.isBookOrbit)) return null;+ final text = EpubBookText.open(file.path);+ if (text == null) return null;+ try {+ final info = <String, dynamic>{+ 'si': spot.si,+ 'offset': spot.offset,+ 'total': spot.total,+ 'href': spot.href,+ 'pct': spot.pct,+ };+ await ScopedPrefs.setString(_readKey(itemId), cfi);+ final locator = AudioLocator(itemId, _FileBookText(text));+ // Nothing is transcribed while the page is plainly behind the audio.+ final rough = await locator.estimate(info, api);+ final guess = rough?.est ?? (info['pct'] as double) * book.duration;+ if (guess <= heard + 60) {+ debugPrint('[SyncSpot] $itemId: the page (about ${guess.toStringAsFixed(0)}s) '+ 'is not ahead of the audio (${heard.toStringAsFixed(0)}s)');+ return null;+ }+ final started = DateTime.now();+ _setSyncing(itemId, SyncTarget.audio);+ final t = await locator.locate(info, api);+ if (t == null || t <= heard + 15) return null;+ final now = AudioPlayerService();+ final inPlayer = now.currentItemId == itemId && now.currentEpisodeId == null;+ // Playback started while this was being found: the audio is never moved+ // under it. The spot is offered instead.+ if ((_playedAt[itemId]?.isAfter(began) ?? false) || (inPlayer && now.isPlaying)) {+ debugPrint('[SyncSpot] $itemId: found ${t.toStringAsFixed(0)}s after playback started - offering it');+ _toast((l) => l.syncAudioOffer, Icons.headphones_rounded, onTap: () {+ final p = AudioPlayerService();+ if (p.currentItemId == itemId) unawaited(p.seekTo(Duration(milliseconds: (t * 1000).round())));+ });+ return null;+ }+ if (inPlayer) {+ await now.seekTo(Duration(milliseconds: (t * 1000).round()));+ } else {+ final local = await ProgressSyncService().getLocal(itemId);+ await ProgressSyncService().saveLocal(+ itemId: itemId,+ currentTime: t,+ duration: book.duration,+ speed: (local?['speed'] as num?)?.toDouble() ?? 1.0,+ );+ try {+ await api.updateProgress(itemId, currentTime: t, duration: book.duration);+ } catch (e) {+ debugPrint('[SyncSpot] $itemId: audio spot not sent: $e');+ }+ }+ await ScopedPrefs.setDouble(_heardKey(itemId), t);+ debugPrint('[SyncSpot] $itemId: audio moved ${heard.toStringAsFixed(0)}s -> '+ '${t.toStringAsFixed(0)}s in ${DateTime.now().difference(started).inMilliseconds}ms');+ _toast((l) => l.syncAudioMoved, Icons.headphones_rounded);+ return t;+ } finally {+ text.close();+ }+ } finally {+ _setSyncing(itemId, null);+ }+ }+}diff --git a/lib/services/remote_zip.dart b/lib/services/remote_zip.dartnew file mode 100644index 00000000..6b20433a--- /dev/null+++ b/lib/services/remote_zip.dart@@ -0,0 +1,288 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:math';+import 'dart:typed_data';++import 'package:http/http.dart' as http;++/// One file inside a [RemoteZip].+class RemoteZipEntry {+ final String name;+ final int method;+ final int compressedSize;+ final int size;+ final int headerOffset;+ final Uint8List centralRecord;+ final int offsetFieldAt;+ final bool offsetInZip64;+ int? _dataOffset;++ RemoteZipEntry._(this.name, this.method, this.compressedSize, this.size, this.headerOffset,+ this.centralRecord, this.offsetFieldAt, this.offsetInZip64);++ bool get stored => method == 0;+}++class RemoteZipException implements Exception {+ final String message;+ RemoteZipException(this.message);+ @override+ String toString() => 'RemoteZipException: $message';+}++/// A zip (an EPUB) on a server, read with HTTP range requests: its index and+/// any one file, without downloading the rest.+class RemoteZip {+ final Uri url;+ final Map<String, String> headers;+ final http.Client _client;+ final int length;+ final List<RemoteZipEntry> entries;+ final int centralOffset;++ RemoteZip._(this.url, this.headers, this._client, this.length, this.entries, this.centralOffset);++ RemoteZipEntry? entry(String name) {+ for (final e in entries) {+ if (e.name == name) return e;+ }+ return null;+ }++ static Future<(Uint8List, int)> _range(+ http.Client client,+ Uri url,+ Map<String, String> headers,+ String range,+ ) async {+ final req = http.Request('GET', url)+ ..headers.addAll(headers)+ ..headers['Range'] = 'bytes=$range';+ final res = await client.send(req).timeout(const Duration(seconds: 30));+ if (res.statusCode != 206) {+ // Not a range: it may be the whole file coming, so hang up on it.+ await res.stream.listen(null).cancel().catchError((_) {});+ throw RemoteZipException('server answered ${res.statusCode} to a range request');+ }+ final total = int.tryParse((res.headers['content-range'] ?? '').split('/').last) ?? -1;+ final body = await res.stream.toBytes().timeout(const Duration(minutes: 5));+ return (body, total);+ }++ Future<Uint8List> bytes(int start, int count) async {+ if (count <= 0) return Uint8List(0);+ final (body, _) = await _range(_client, url, headers, '$start-${start + count - 1}');+ if (body.length != count) throw RemoteZipException('short read: ${body.length} of $count bytes');+ return body;+ }++ /// Reads the zip's index from the end of the file. The length comes first:+ /// not every server takes a range counted from the end (BookOrbit sends+ /// the whole file for `bytes=-N`).+ static Future<RemoteZip> open(Uri url, {Map<String, String> headers = const {}, http.Client? client}) async {+ final c = client ?? http.Client();+ final (_, total) = await _range(c, url, headers, '0-0');+ if (total <= 0) throw RemoteZipException('server sent no file length');+ final (tail, _) = await _range(c, url, headers, '${max(0, total - (22 + 65535))}-${total - 1}');+ final tailStart = total - tail.length;+ final eocd = _lastIndexOf(tail, 0x06054b50);+ if (eocd < 0) throw RemoteZipException('no zip end record');+ final t = ByteData.sublistView(tail);+ final count = t.getUint16(eocd + 10, Endian.little);+ var cdSize = t.getUint32(eocd + 12, Endian.little);+ var cdOffset = t.getUint32(eocd + 16, Endian.little);+ if (count == 0xFFFF || cdSize == 0xFFFFFFFF || cdOffset == 0xFFFFFFFF) {+ final locAt = eocd - 20;+ if (locAt < 0 || t.getUint32(locAt, Endian.little) != 0x07064b50) {+ throw RemoteZipException('zip64 locator missing');+ }+ final z64Offset = t.getUint64(locAt + 8, Endian.little);+ final z64 = z64Offset >= tailStart+ ? ByteData.sublistView(tail, z64Offset - tailStart)+ : ByteData.sublistView(await _rangeBytes(c, url, headers, z64Offset, 56));+ cdSize = z64.getUint64(40, Endian.little);+ cdOffset = z64.getUint64(48, Endian.little);+ }+ final cd = cdOffset >= tailStart+ ? Uint8List.sublistView(tail, cdOffset - tailStart, cdOffset - tailStart + cdSize)+ : await _rangeBytes(c, url, headers, cdOffset, cdSize);+ return RemoteZip._(url, headers, c, total, _parseCentral(cd), cdOffset);+ }++ static Future<Uint8List> _rangeBytes(+ http.Client c, Uri url, Map<String, String> headers, int start, int count) async {+ final (body, _) = await _range(c, url, headers, '$start-${start + count - 1}');+ return body;+ }++ static int _lastIndexOf(Uint8List b, int signature) {+ final d = ByteData.sublistView(b);+ for (var i = b.length - 22; i >= 0; i--) {+ if (d.getUint32(i, Endian.little) == signature) return i;+ }+ return -1;+ }++ static List<RemoteZipEntry> _parseCentral(Uint8List cd) {+ final d = ByteData.sublistView(cd);+ final out = <RemoteZipEntry>[];+ var p = 0;+ while (p + 46 <= cd.length && d.getUint32(p, Endian.little) == 0x02014b50) {+ final method = d.getUint16(p + 10, Endian.little);+ var csize = d.getUint32(p + 20, Endian.little);+ var usize = d.getUint32(p + 24, Endian.little);+ final nameLen = d.getUint16(p + 28, Endian.little);+ final extraLen = d.getUint16(p + 30, Endian.little);+ final commentLen = d.getUint16(p + 32, Endian.little);+ var offset = d.getUint32(p + 42, Endian.little);+ final name = String.fromCharCodes(cd.sublist(p + 46, p + 46 + nameLen));+ var offsetFieldAt = 42;+ var inZip64 = false;+ // Zip64 extra field: the 64-bit values replace whichever 32-bit ones are+ // maxed out, in this order.+ var x = p + 46 + nameLen;+ final xEnd = x + extraLen;+ while (x + 4 <= xEnd) {+ final id = d.getUint16(x, Endian.little);+ final len = d.getUint16(x + 2, Endian.little);+ if (id == 0x0001) {+ var q = x + 4;+ if (usize == 0xFFFFFFFF) {+ usize = d.getUint64(q, Endian.little);+ q += 8;+ }+ if (csize == 0xFFFFFFFF) {+ csize = d.getUint64(q, Endian.little);+ q += 8;+ }+ if (offset == 0xFFFFFFFF) {+ offset = d.getUint64(q, Endian.little);+ offsetFieldAt = q - p;+ inZip64 = true;+ }+ }+ x += 4 + len;+ }+ final end = p + 46 + nameLen + extraLen + commentLen;+ out.add(RemoteZipEntry._(_utf8Name(cd.sublist(p + 46, p + 46 + nameLen), name), method, csize,+ usize, offset, Uint8List.fromList(cd.sublist(p, end)), offsetFieldAt, inZip64));+ p = end;+ }+ return out;+ }++ static String _utf8Name(List<int> bytes, String fallback) {+ try {+ return utf8.decode(bytes);+ } catch (_) {+ return fallback;+ }+ }++ /// Where [e]'s data starts, read from its local header.+ Future<int> dataOffset(RemoteZipEntry e) async {+ final known = e._dataOffset;+ if (known != null) return known;+ final h = ByteData.sublistView(await bytes(e.headerOffset, 30));+ if (h.getUint32(0, Endian.little) != 0x04034b50) throw RemoteZipException('bad local header for ${e.name}');+ final at = e.headerOffset + 30 + h.getUint16(26, Endian.little) + h.getUint16(28, Endian.little);+ e._dataOffset = at;+ return at;+ }++ /// The whole of one (small) file.+ Future<Uint8List> read(RemoteZipEntry e) async {+ final raw = await bytes(await dataOffset(e), e.compressedSize);+ if (e.method == 0) return raw;+ if (e.method == 8) return Uint8List.fromList(ZLibDecoder(raw: true).convert(raw));+ throw RemoteZipException('${e.name} uses compression method ${e.method}');+ }++ /// Streams one file into [out], inflating it when it is compressed.+ Future<void> download(RemoteZipEntry e, File out, {void Function(int done)? onBytes}) async {+ final start = await dataOffset(e);+ final req = http.Request('GET', url)+ ..headers.addAll(headers)+ ..headers['Range'] = 'bytes=$start-${start + e.compressedSize - 1}';+ final res = await _client.send(req).timeout(const Duration(seconds: 30));+ if (res.statusCode != 206) {+ await res.stream.drain<void>().catchError((_) {});+ throw RemoteZipException('server answered ${res.statusCode} to a range request');+ }+ final part = File('${out.path}.part');+ final sink = part.openWrite();+ var done = 0;+ try {+ Stream<List<int>> body = res.stream.timeout(const Duration(seconds: 60)).map((chunk) {+ done += chunk.length;+ onBytes?.call(done);+ return chunk;+ });+ if (e.method == 8) body = body.transform(ZLibDecoder(raw: true));+ await sink.addStream(body);+ } finally {+ await sink.close();+ }+ if (out.existsSync()) await out.delete();+ await part.rename(out.path);+ }++ /// A copy of the zip holding only the files [keep] accepts, made from the+ /// server's bytes as they are (no recompression). Neighbouring files come+ /// down in one request.+ Future<void> writeCopy(File out, bool Function(RemoteZipEntry e) keep) async {+ final ordered = [...entries]..sort((a, b) => a.headerOffset.compareTo(b.headerOffset));+ final spans = <(RemoteZipEntry, int, int)>[];+ for (var i = 0; i < ordered.length; i++) {+ final e = ordered[i];+ final end = i + 1 < ordered.length ? ordered[i + 1].headerOffset : centralOffset;+ if (keep(e)) spans.add((e, e.headerOffset, end));+ }+ final part = File('${out.path}.part');+ final raf = await part.open(mode: FileMode.write);+ final central = BytesBuilder(copy: false);+ var written = 0;+ try {+ var i = 0;+ while (i < spans.length) {+ // Batch spans that follow one another on the server, up to 8MB.+ var j = i;+ while (j + 1 < spans.length && spans[j + 1].$2 == spans[j].$3 && spans[j + 1].$3 - spans[i].$2 < 8 << 20) {+ j++;+ }+ final data = await bytes(spans[i].$2, spans[j].$3 - spans[i].$2);+ for (var k = i; k <= j; k++) {+ final (e, s, end) = spans[k];+ final rel = s - spans[i].$2;+ await raf.writeFrom(data, rel, rel + (end - s));+ final rec = Uint8List.fromList(e.centralRecord);+ final rd = ByteData.sublistView(rec);+ if (e.offsetInZip64) {+ rd.setUint64(e.offsetFieldAt, written, Endian.little);+ } else {+ rd.setUint32(e.offsetFieldAt, written, Endian.little);+ }+ central.add(rec);+ written += end - s;+ }+ i = j + 1;+ }+ final cd = central.takeBytes();+ await raf.writeFrom(cd);+ final eocd = ByteData(22)+ ..setUint32(0, 0x06054b50, Endian.little)+ ..setUint16(8, min(spans.length, 0xFFFF), Endian.little)+ ..setUint16(10, min(spans.length, 0xFFFF), Endian.little)+ ..setUint32(12, cd.length, Endian.little)+ ..setUint32(16, written, Endian.little);+ await raf.writeFrom(eocd.buffer.asUint8List());+ } finally {+ await raf.close();+ }+ if (out.existsSync()) await out.delete();+ await part.rename(out.path);+ }++ void close() => _client.close();+}diff --git a/lib/services/siri_matcher.dart b/lib/services/siri_matcher.dartnew file mode 100644index 00000000..10624da1--- /dev/null+++ b/lib/services/siri_matcher.dart@@ -0,0 +1,365 @@+import 'dart:math';++/// One thing Siri can be asked to play: a book, a podcast show, an episode or+/// a series (which plays its next unfinished book).+class SiriEntry {+ final String kind;+ final String itemId;+ final String? episodeId;+ final String? libraryId;+ final String title;+ final String author;+ final List<String> series;+ final double progress;+ final bool finished;+ final int lastPlayed;+ final bool downloaded;+ final String? coverPath;++ const SiriEntry({+ required this.kind,+ required this.itemId,+ required this.title,+ this.episodeId,+ this.libraryId,+ this.author = '',+ this.series = const [],+ this.progress = 0,+ this.finished = false,+ this.lastPlayed = 0,+ this.downloaded = false,+ this.coverPath,+ });++ /// The identifier Siri hands back when it asks the app to play this.+ String get id => switch (kind) {+ 'episode' => 'episode|$itemId|${episodeId ?? ''}',+ 'series' => 'series|$itemId|${libraryId ?? ''}',+ _ => '$kind|$itemId',+ };++ bool get inProgress => progress > 0 && !finished;++ SiriEntry copyWith({+ double? progress,+ bool? finished,+ int? lastPlayed,+ bool? downloaded,+ String? coverPath,+ List<String>? series,+ }) =>+ SiriEntry(+ kind: kind,+ itemId: itemId,+ episodeId: episodeId,+ libraryId: libraryId,+ title: title,+ author: author,+ series: series ?? this.series,+ progress: progress ?? this.progress,+ finished: finished ?? this.finished,+ lastPlayed: lastPlayed ?? this.lastPlayed,+ downloaded: downloaded ?? this.downloaded,+ coverPath: coverPath ?? this.coverPath,+ );++ Map<String, dynamic> toJson() => {+ 'id': id,+ 'kind': kind,+ 'itemId': itemId,+ if (episodeId != null) 'episodeId': episodeId,+ if (libraryId != null) 'libraryId': libraryId,+ 'title': title,+ 'author': author,+ if (series.isNotEmpty) 'series': series,+ 'progress': progress,+ 'finished': finished,+ 'lastPlayed': lastPlayed,+ 'downloaded': downloaded,+ if (coverPath != null) 'coverPath': coverPath,+ };++ factory SiriEntry.fromJson(Map<String, dynamic> j) => SiriEntry(+ kind: j['kind'] as String? ?? 'book',+ itemId: j['itemId'] as String? ?? '',+ episodeId: j['episodeId'] as String?,+ libraryId: j['libraryId'] as String?,+ title: j['title'] as String? ?? '',+ author: j['author'] as String? ?? '',+ series: (j['series'] as List<dynamic>? ?? const []).whereType<String>().toList(),+ progress: (j['progress'] as num?)?.toDouble() ?? 0,+ finished: j['finished'] == true,+ lastPlayed: (j['lastPlayed'] as num?)?.toInt() ?? 0,+ downloaded: j['downloaded'] == true,+ coverPath: j['coverPath'] as String?,+ );+}++/// What Siri asked for. [type] is 'book', 'podcast', 'episode' or 'any';+/// [latest] is set when the request asked for the newest episode.+class SiriQuery {+ final String? name;+ final String? artist;+ final String type;+ final bool latest;++ const SiriQuery({this.name, this.artist, this.type = 'any', this.latest = false});++ factory SiriQuery.fromArgs(Map<dynamic, dynamic> args) {+ String? clean(Object? v) {+ final s = (v as String?)?.trim();+ return (s == null || s.isEmpty) ? null : s;+ }++ return SiriQuery(+ name: clean(args['name']),+ artist: clean(args['artist']),+ type: clean(args['type']) ?? 'any',+ latest: args['latest'] == true,+ );+ }++ /// "Resume Absorb", "Play my audiobook in Absorb": nothing to search for.+ bool get isResume => _nameKey.isEmpty && (artist == null || siriNormalize(artist!).isEmpty);++ String get _nameKey {+ final key = siriNormalize(_stripNoise(name ?? ''));+ return _fillerNames.contains(key) ? '' : key;+ }+}++const _fillerNames = {+ 'my', 'my book', 'book', 'books', 'my books', 'my audiobooks', 'my show',+ 'my podcasts', 'something', 'anything', 'last', 'my last book', 'latest',+ 'where i left off', 'what i was listening to', 'my current book',+ 'current book', 'my story', 'music',+};++class SiriMatch {+ /// 'ok', 'ambiguous' or 'none'.+ final String status;+ final List<SiriEntry> items;+ final double score;++ /// The pick came from a series name rather than a title, so the series'+ /// own next book may be a better answer than the books on hand.+ final bool viaSeries;++ const SiriMatch(this.status, this.items, this.score, {this.viaSeries = false});++ static const none = SiriMatch('none', [], 0);+}++const _numberWords = {+ 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5',+ 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'ten': '10',+ 'eleven': '11', 'twelve': '12', 'thirteen': '13', 'fourteen': '14',+ 'fifteen': '15', 'sixteen': '16', 'seventeen': '17', 'eighteen': '18',+ 'nineteen': '19', 'twenty': '20',+};++const _foldFrom = 'àáâãäåāăąçćčďèéêëēėęěìíîïīįłñńňòóôõöøōőřśšşťùúûüūůűųýÿžźżß';+const _foldTo = 'aaaaaaaaaccc' 'deeeeeeee' 'iiiiiilnnn' 'oooooooo' 'rsss' 't' 'uuuuuuuu' 'yy' 'zzz' 's';++String _fold(String s) {+ final out = StringBuffer();+ for (final ch in s.split('')) {+ final i = _foldFrom.indexOf(ch);+ out.write(i >= 0 && i < _foldTo.length ? _foldTo[i] : ch);+ }+ return out.toString();+}++final _nonWord = RegExp(r'[^\p{L}\p{N}]+', unicode: true);+final _leadingArticle = RegExp(r'^(the|a|an) ');+final _noise = RegExp(+ r'\b(the )?(audio ?book|podcast|latest episode of|newest episode of|new episode of|episode of)\b',+ caseSensitive: false);++String _stripNoise(String s) => s.replaceAll(_noise, ' ');++/// Lowercase, accents folded, punctuation dropped, number words as digits and+/// a leading article removed, so "The Wheel of Time: Book One" and "wheel of+/// time book 1" compare equal.+String siriNormalize(String s) {+ var t = _fold(s.toLowerCase()).replaceAll('&', ' and ').replaceAll(RegExp(r"['’]"), '');+ t = t.replaceAll(_nonWord, ' ').trim();+ if (t.isEmpty) return t;+ t = t.split(RegExp(r'\s+')).map((w) => _numberWords[w] ?? w).join(' ');+ return t.replaceFirst(_leadingArticle, '');+}++double _similarity(String a, String b) {+ if (a == b) return 1;+ if (a.isEmpty || b.isEmpty) return 0;+ final m = a.length, n = b.length;+ var prev = List<int>.generate(n + 1, (j) => j);+ for (var i = 1; i <= m; i++) {+ final cur = List<int>.filled(n + 1, 0);+ cur[0] = i;+ for (var j = 1; j <= n; j++) {+ final cost = a.codeUnitAt(i - 1) == b.codeUnitAt(j - 1) ? 0 : 1;+ cur[j] = min(min(cur[j - 1] + 1, prev[j] + 1), prev[j - 1] + cost);+ }+ prev = cur;+ }+ return 1 - prev[n] / max(m, n);+}++bool _hasPhrase(String hay, String needle) => ' $hay '.contains(' $needle ');++/// How well a spoken [query] names [target], 0 to 100. Both normalized.+double siriTextScore(String query, String target) {+ if (query.isEmpty || target.isEmpty) return 0;+ if (query == target) return 100;+ var best = 0.0;+ if (_hasPhrase(target, query)) {+ best = max(best, 78 + 17 * query.length / target.length);+ }+ if (_hasPhrase(query, target)) {+ best = max(best, 74 + 16 * target.length / query.length);+ }+ final qt = query.split(' ').toSet();+ final tt = target.split(' ').toSet();+ final shared = qt.intersection(tt).length;+ if (shared > 0) {+ final overlap = shared / max(qt.length, tt.length);+ final allQuery = shared == qt.length;+ best = max(best, (allQuery ? 72 : 60) * overlap);+ }+ final sim = _similarity(query, target);+ if (sim >= 0.75) best = max(best, 92 * sim);+ return best;+}++class _Scored {+ final SiriEntry entry;+ final double score;+ final bool bySeries;+ const _Scored(this.entry, this.score, this.bySeries);+}++bool _kindFits(String kind, String type) => switch (type) {+ 'book' => kind == 'book' || kind == 'series',+ 'podcast' => kind == 'podcast' || kind == 'episode',+ 'episode' => kind == 'episode' || kind == 'podcast',+ _ => true,+ };++int _rank(SiriEntry e) => e.inProgress ? 2 : (e.finished ? 0 : 1);++/// Picks what a Siri request means from [entries]. A clear winner is 'ok';+/// close calls come back 'ambiguous' for Siri to ask which one.+SiriMatch siriMatch(SiriQuery query, List<SiriEntry> entries) {+ final name = query._nameKey;+ final artist = query.artist == null ? '' : siriNormalize(query.artist!);+ final pool = entries.where((e) => _kindFits(e.kind, query.type)).toList();+ if (pool.isEmpty) return SiriMatch.none;++ if (name.isEmpty) {+ if (artist.isEmpty) return SiriMatch.none;+ return _byAuthor(artist, pool);+ }++ final scored = <_Scored>[];+ for (final e in pool) {+ final titleScore = siriTextScore(name, siriNormalize(e.title));+ var seriesScore = 0.0;+ for (final s in e.series) {+ seriesScore = max(seriesScore, siriTextScore(name, siriNormalize(s)) * 0.96);+ }+ final bySeries = seriesScore > titleScore;+ var score = max(titleScore, seriesScore);+ if (artist.isNotEmpty && score > 0) {+ final a = siriTextScore(artist, siriNormalize(e.author));+ score = a >= 70 ? min(100.0, score + 4) : score * 0.85;+ }+ if (score > 0) scored.add(_Scored(e, score, bySeries));+ }++ // "Play Brandon Sanderson": the name is an author, not a title.+ final bestTitle = scored.fold<double>(0, (m, s) => max(m, s.score));+ if (bestTitle < 80) {+ final asAuthor = _byAuthor(name, pool);+ if (asAuthor.status != 'none' && asAuthor.score > bestTitle) return asAuthor;+ }+ if (scored.isEmpty) return SiriMatch.none;++ scored.sort((a, b) {+ final c = b.score.compareTo(a.score);+ if (c != 0) return c;+ final r = _rank(b.entry).compareTo(_rank(a.entry));+ if (r != 0) return r;+ return b.entry.lastPlayed.compareTo(a.entry.lastPlayed);+ });++ var top = scored.first;+ if (top.score < 60) return SiriMatch.none;+ // A book and its series named the same: the book is the likelier ask.+ if (top.entry.kind == 'series') {+ final book = scored.firstWhere(+ (s) => s.entry.kind == 'book' && !s.bySeries && top.score - s.score < 1,+ orElse: () => top);+ if (book != top) {+ scored.remove(book);+ scored.insert(0, book);+ top = book;+ }+ }++ // A series name: its books tie, so play the one the listener is on, or the+ // first not finished.+ if (top.bySeries) {+ final inSeries = scored.where((s) => s.bySeries && top.score - s.score < 3).map((s) => s.entry).toList();+ return SiriMatch('ok', [_nextInSeries(inSeries)], top.score, viaSeries: true);+ }++ final rivals = scored+ .skip(1)+ .where((s) =>+ s.entry.id != top.entry.id &&+ !(s.entry.kind == 'series' && top.entry.kind == 'book' && top.score - s.score < 1))+ .toList();+ if (rivals.isEmpty ||+ top.score - rivals.first.score > 10 ||+ (top.score >= 97 && rivals.first.score < 97)) {+ return SiriMatch('ok', [top.entry], top.score);+ }+ final close = [top.entry];+ for (final s in rivals) {+ if (top.score - s.score > 10 || close.length == 4) break;+ if (!close.any((e) => e.id == s.entry.id)) close.add(s.entry);+ }+ return SiriMatch('ambiguous', close, top.score);+}++SiriEntry _nextInSeries(List<SiriEntry> books) {+ final playing = books.where((e) => e.inProgress).toList()+ ..sort((a, b) => b.lastPlayed.compareTo(a.lastPlayed));+ if (playing.isNotEmpty) return playing.first;+ return books.firstWhere((e) => !e.finished, orElse: () => books.first);+}++SiriMatch _byAuthor(String author, List<SiriEntry> pool) {+ final hits = <_Scored>[];+ for (final e in pool) {+ if (e.kind == 'series') continue;+ final names = e.author.split(RegExp(r',|&| and ')).map(siriNormalize).where((n) => n.isNotEmpty);+ var s = siriTextScore(author, siriNormalize(e.author));+ for (final n in names) {+ s = max(s, siriTextScore(author, n));+ }+ if (s >= 85) hits.add(_Scored(e, s, false));+ }+ if (hits.isEmpty) return SiriMatch.none;+ hits.sort((a, b) {+ final r = _rank(b.entry).compareTo(_rank(a.entry));+ if (r != 0) return r;+ return b.entry.lastPlayed.compareTo(a.entry.lastPlayed);+ });+ final best = hits.first;+ if (best.entry.inProgress || hits.length == 1) {+ return SiriMatch('ok', [best.entry], best.score);+ }+ return SiriMatch('ambiguous', hits.take(4).map((s) => s.entry).toList(), best.score);+}diff --git a/lib/services/siri_service.dart b/lib/services/siri_service.dartnew file mode 100644index 00000000..327ea455--- /dev/null+++ b/lib/services/siri_service.dart@@ -0,0 +1,748 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';+import 'package:home_widget/home_widget.dart';+import 'package:shared_preferences/shared_preferences.dart';++import 'android_auto_service.dart';+import 'api_service.dart';+import 'audio_player_service.dart';+import 'download_service.dart';+import 'home_widget_service.dart';+import 'progress_sync_service.dart';+import 'siri_matcher.dart';+import 'sleep_timer_service.dart';++/// Siri on iOS. Native code forwards the media intent ("Play Dune on Absorb")+/// and the App Shortcuts here; this side picks the book, plays it, keeps the+/// list of books Siri can name in the app group, and tells Siri what gets+/// played so it learns the listener's books.+class SiriService {+ static final SiriService _instance = SiriService._();+ factory SiriService() => _instance;+ SiriService._();++ static const _channel = MethodChannel('com.absorb.siri');+ static const _widgetChannel = MethodChannel('com.absorb.widget');+ static const catalogFileName = 'siri_catalog.json';++ /// Items the library screens have loaded (Absorbing, home shelves of every+ /// library opened). Set by LibraryProvider.+ static Iterable<Map<String, dynamic>> Function()? libraryItems;++ bool _initialized = false;+ List<SiriEntry> _catalog = const [];+ bool _catalogLoaded = false;+ Timer? _catalogTimer;+ bool _rebuilding = false;+ bool _askedAutoRefresh = false;+ String? _lastPlayKey;+ Map<String, Map<String, dynamic>> _progress = const {};+ DateTime? _progressAt;++ Future<void> init() async {+ if (_initialized || !Platform.isIOS) return;+ _initialized = true;+ _channel.setMethodCallHandler(_onCall);+ try {+ await _channel.invokeMethod('ready');+ } catch (e) {+ debugPrint('[Siri] ready failed: $e');+ }+ AudioPlayerService().addListener(_onPlayerChanged);+ AndroidAutoService.serverDataListeners.add(scheduleCatalogUpdate);+ scheduleCatalogUpdate(delay: const Duration(seconds: 8));+ }++ Future<dynamic> _onCall(MethodCall call) async {+ final args = (call.arguments as Map?) ?? const {};+ try {+ switch (call.method) {+ case 'resolve':+ return await _resolve(SiriQuery.fromArgs(args));+ case 'play':+ return await _play(args);+ case 'control':+ return await _control(args);+ }+ } catch (e) {+ debugPrint('[Siri] ${call.method} failed: $e');+ return {'ok': false, 'status': 'none', 'items': const []};+ }+ return null;+ }++ // Resolving++ Future<Map<String, dynamic>> _resolve(SiriQuery q) async {+ debugPrint('[Siri] resolve name="${q.name}" artist="${q.artist}" type=${q.type} latest=${q.latest}');+ if (q.isResume) return _resumeTarget();+ await _ensureCatalogLoaded();+ var result = siriMatch(q, _catalog);+ if (result.status != 'ok' || result.score < 85 || result.viaSeries) {+ final found = await _searchServer(q)+ .timeout(const Duration(seconds: 5), onTimeout: () => const <SiriEntry>[]);+ if (found.isNotEmpty) {+ final again = siriMatch(q, _merge(_catalog, found));+ if (again.status != 'none' && (result.status == 'none' || again.score >= result.score)) {+ result = again;+ }+ }+ }+ if (result.status == 'none' && await AndroidAutoService().getApi() == null) {+ return {'status': 'signedOut', 'items': const []};+ }+ debugPrint('[Siri] resolve -> ${result.status}: ${result.items.map((e) => e.title).join(' | ')}');+ return {'status': result.status, 'items': result.items.map(_itemJson).toList()};+ }++ Map<String, dynamic> _itemJson(SiriEntry e) => {+ 'id': e.id,+ 'kind': e.kind,+ 'title': e.title,+ 'author': e.author,+ if (e.coverPath != null) 'coverPath': e.coverPath,+ };++ Future<Map<String, dynamic>> _resumeTarget() async {+ final player = AudioPlayerService();+ if (player.hasBook) {+ return {+ 'status': 'ok',+ 'items': [+ {'id': 'resume', 'kind': 'book', 'title': player.currentTitle ?? '', 'author': player.currentAuthor ?? ''},+ ],+ };+ }+ final prefs = await SharedPreferences.getInstance();+ final itemId = prefs.getString('widget_item_id');+ if (itemId == null) return {'status': 'none', 'items': const []};+ final episodeId = prefs.getString('widget_episode_id');+ final key = episodeId != null ? '$itemId-$episodeId' : itemId;+ if (HomeWidgetService.lastPlayedIsFinished(await ProgressSyncService().getLocal(key))) {+ return {'status': 'none', 'items': const []};+ }+ String? title, author;+ try {+ title = await HomeWidget.getWidgetData<String>('np_title');+ author = await HomeWidget.getWidgetData<String>('np_author');+ } catch (_) {}+ return {+ 'status': 'ok',+ 'items': [+ {'id': 'resume', 'kind': episodeId != null ? 'episode' : 'book', 'title': title ?? '', 'author': author ?? ''},+ ],+ };+ }++ List<SiriEntry> _merge(List<SiriEntry> known, List<SiriEntry> found) {+ final byId = {for (final e in known) e.id: e};+ for (final e in found) {+ final had = byId[e.id];+ byId[e.id] = had == null+ ? e+ : had.copyWith(series: had.series.isEmpty ? e.series : had.series);+ }+ return byId.values.toList();+ }++ Future<List<SiriEntry>> _searchServer(SiriQuery q) async {+ final text = (q.name?.trim().isNotEmpty == true ? q.name! : q.artist ?? '').trim();+ if (text.isEmpty) return const [];+ final api = await AndroidAutoService().getApi();+ if (api == null) return const [];+ final libraries = await _libraries(api);+ final wantBooks = q.type == 'book' || q.type == 'any';+ final wantPodcasts = q.type != 'book';+ final out = <SiriEntry>[];+ await Future.wait(libraries.where((l) => l.isPodcast ? wantPodcasts : wantBooks).map((lib) async {+ final res = await api.searchLibrary(lib.id, text, limit: 10);+ if (res == null) return;+ for (final key in ['book', 'podcast']) {+ for (final hit in (res[key] as List<dynamic>? ?? const [])) {+ final item = (hit is Map ? hit['libraryItem'] : null) as Map<String, dynamic>?;+ final e = item == null ? null : entryFromItem(item, libraryId: lib.id);+ if (e != null) out.add(e);+ }+ }+ for (final hit in (res['series'] as List<dynamic>? ?? const [])) {+ if (hit is! Map) continue;+ final series = hit['series'] as Map<String, dynamic>?;+ final id = series?['id'] as String?;+ final name = series?['name'] as String?;+ if (id != null && name != null && name.isNotEmpty) {+ out.add(SiriEntry(kind: 'series', itemId: id, libraryId: lib.id, title: name));+ }+ for (final b in (hit['books'] as List<dynamic>? ?? const [])) {+ final e = b is Map<String, dynamic> ? entryFromItem(b, libraryId: lib.id) : null;+ if (e != null) out.add(e);+ }+ }+ }));+ debugPrint('[Siri] server search "$text" -> ${out.length} results');+ return _withProgress(out, api: api);+ }++ Future<List<AutoLibraryEntry>> _libraries(ApiService api) async {+ final known = AndroidAutoService().libraries;+ if (known.isNotEmpty) return known;+ final libs = await api.getLibraries();+ return [+ for (final l in libs.whereType<Map<String, dynamic>>())+ if (l['id'] is String)+ AutoLibraryEntry(+ id: l['id'] as String,+ name: l['name'] as String? ?? '',+ mediaType: l['mediaType'] as String? ?? 'book',+ ),+ ];+ }++ // Playing++ Future<Map<String, dynamic>> _play(Map<dynamic, dynamic> args) async {+ final id = args['id'] as String? ?? 'resume';+ final speed = (args['speed'] as num?)?.toDouble();+ final latest = args['latest'] == true;+ debugPrint('[Siri] play $id speed=$speed latest=$latest');+ final parts = id.split('|');+ String part(int i) => parts.length > i ? parts[i] : '';+ var ok = false;+ switch (parts.first) {+ case 'book':+ ok = await _playItem(part(1), null);+ case 'episode':+ ok = await _playItem(part(1), part(2).isEmpty ? null : part(2));+ case 'podcast':+ ok = await _playPodcast(part(1), latest: latest);+ case 'series':+ ok = await _playSeries(part(1), part(2));+ default:+ ok = await _resume();+ }+ final player = AudioPlayerService();+ if (ok && speed != null && speed > 0) {+ await player.setSpeed(speed.clamp(0.5, 5.0).toDouble());+ }+ debugPrint('[Siri] play $id -> ok=$ok "${player.currentTitle}"');+ return {'ok': ok, 'title': player.currentTitle ?? '', 'author': player.currentAuthor ?? ''};+ }++ Future<bool> _resume() async {+ final player = AudioPlayerService();+ if (player.hasBook) {+ if (!player.isPlaying) await player.play();+ return true;+ }+ await HomeWidgetService().resumeLastPlayedIfAvailable();+ return player.hasBook;+ }++ Future<bool> _playItem(String itemId, String? episodeId) async {+ if (itemId.isEmpty) return false;+ final player = AudioPlayerService();+ if (player.hasBook && player.currentItemId == itemId && player.currentEpisodeId == episodeId) {+ if (!player.isPlaying) await player.play();+ return true;+ }+ final handler = AudioPlayerService.handler;+ if (handler == null) return false;+ final key = episodeId == null ? itemId : '$itemId-$episodeId';+ await handler.playFromMediaId(AutoMediaIds.itemId(key));+ return player.currentItemId == itemId && player.currentEpisodeId == episodeId;+ }++ /// The episode the listener is partway through, or else the newest one+ /// not finished. "The latest episode of" always takes the newest.+ Future<bool> _playPodcast(String showId, {bool latest = false}) async {+ final api = await AndroidAutoService().getApi();+ if (api == null) return false;+ final item = await api.getLibraryItem(showId);+ final episodes = ((item?['media'] as Map<String, dynamic>?)?['episodes'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .toList();+ if (episodes.isEmpty) return false;+ int published(Map<String, dynamic> e) =>+ (e['publishedAt'] as num?)?.toInt() ?? (e['addedAt'] as num?)?.toInt() ?? 0;+ episodes.sort((a, b) => published(b).compareTo(published(a)));+ final progress = await _progressMap(api);+ Map<String, dynamic>? state(Map<String, dynamic> e) => progress['$showId-${e['id']}'];+ var pick = episodes.first;+ if (!latest) {+ final going = episodes.where((e) => _isGoing(state(e))).toList()+ ..sort((a, b) => _lastUpdate(state(b)).compareTo(_lastUpdate(state(a))));+ pick = going.isNotEmpty+ ? going.first+ : episodes.firstWhere((e) => state(e)?['isFinished'] != true, orElse: () => episodes.first);+ }+ final episodeId = pick['id'] as String?;+ if (episodeId == null) return false;+ return _playItem(showId, episodeId);+ }++ /// The book in the series the listener is on, or else the first unfinished.+ Future<bool> _playSeries(String seriesId, String libraryId) async {+ final api = await AndroidAutoService().getApi();+ if (api == null) return false;+ final books = (await api.getAllBooksBySeries(libraryId, seriesId)).whereType<Map<String, dynamic>>().toList();+ if (books.isEmpty) return false;+ final progress = await _progressMap(api);+ Map<String, dynamic>? state(Map<String, dynamic> b) => progress[b['id']];+ final going = books.where((b) => _isGoing(state(b))).toList()+ ..sort((a, b) => _lastUpdate(state(b)).compareTo(_lastUpdate(state(a))));+ final pick = going.isNotEmpty+ ? going.first+ : books.firstWhere((b) => state(b)?['isFinished'] != true, orElse: () => books.first);+ final id = pick['id'] as String?;+ return id != null && await _playItem(id, null);+ }++ static bool _isGoing(Map<String, dynamic>? p) =>+ p != null && p['isFinished'] != true && ((p['progress'] as num?) ?? 0) > 0;++ static int _lastUpdate(Map<String, dynamic>? p) => (p?['lastUpdate'] as num?)?.toInt() ?? 0;++ Future<Map<String, Map<String, dynamic>>> _progressMap(ApiService api) async {+ final at = _progressAt;+ if (at != null && DateTime.now().difference(at) < const Duration(minutes: 2)) return _progress;+ final list = await api.getAllProgress();+ if (list == null) return _progress;+ _progress = {+ for (final p in list)+ if (p['libraryItemId'] is String)+ (p['episodeId'] is String && (p['episodeId'] as String).isNotEmpty)+ ? '${p['libraryItemId']}-${p['episodeId']}'+ : p['libraryItemId'] as String: p,+ };+ _progressAt = DateTime.now();+ return _progress;+ }++ // App Shortcuts++ Future<Map<String, dynamic>> _control(Map<dynamic, dynamic> args) async {+ final action = args['action'] as String? ?? '';+ final player = AudioPlayerService();+ final handler = AudioPlayerService.handler;+ debugPrint('[Siri] control $action hasBook=${player.hasBook}');+ var ok = player.hasBook;+ switch (action) {+ case 'resume':+ ok = await _resume();+ case 'pause':+ if (ok) await player.pause();+ case 'skipBack':+ if (ok) await handler?.rewind();+ case 'skipForward':+ if (ok) await handler?.fastForward();+ case 'nextChapter':+ if (ok) await handler?.customAction('nextChapter');+ case 'previousChapter':+ if (ok) await handler?.customAction('previousChapter');+ case 'sleepMinutes':+ final minutes = (args['minutes'] as num?)?.toInt() ?? 0;+ ok = ok && minutes > 0;+ if (ok) SleepTimerService().setTimeSleep(Duration(minutes: minutes));+ case 'sleepChapterEnd':+ if (ok) SleepTimerService().setChapterSleep(1);+ case 'cancelSleep':+ ok = SleepTimerService().isActive;+ if (ok) SleepTimerService().cancelByUser();+ case 'bookmark':+ ok = ok && (await handler?.customAction('bookmark')) == true;+ case 'status':+ break;+ default:+ ok = false;+ }+ final position = player.position.inSeconds;+ final duration = player.totalDuration.round();+ return {+ 'ok': ok,+ 'hasBook': player.hasBook,+ 'playing': player.isPlaying,+ 'title': player.currentTitle ?? '',+ 'author': player.currentAuthor ?? '',+ 'chapter': player.currentChapter?['title'] as String? ?? '',+ 'position': position,+ 'duration': duration,+ 'speed': player.speed,+ };+ }++ // What Siri learns++ void _onPlayerChanged() {+ final player = AudioPlayerService();+ if (!player.hasBook || !player.isPlaying) return;+ final key = '${player.currentItemId}|${player.currentEpisodeId ?? ''}';+ if (key == _lastPlayKey) return;+ _lastPlayKey = key;+ unawaited(_donate(player));+ scheduleCatalogUpdate(delay: const Duration(seconds: 30));+ }++ Future<void> _donate(AudioPlayerService player) async {+ final itemId = player.currentItemId;+ if (itemId == null) return;+ final episodeId = player.currentEpisodeId;+ final key = episodeId == null ? itemId : '$itemId-$episodeId';+ final download = DownloadService().isDownloaded(key) ? DownloadService().getInfo(key) : null;+ final entry = SiriEntry(+ kind: episodeId == null ? 'book' : 'episode',+ itemId: itemId,+ episodeId: episodeId,+ title: player.currentTitle ?? '',+ author: player.currentAuthor ?? '',+ coverPath: download?.localCoverPath,+ );+ if (entry.title.isEmpty) return;+ try {+ await _channel.invokeMethod('donate', _itemJson(entry));+ } catch (e) {+ debugPrint('[Siri] donate failed: $e');+ }+ }++ // The list of books Siri can name++ void scheduleCatalogUpdate({Duration delay = const Duration(seconds: 5)}) {+ if (!_initialized) return;+ _catalogTimer?.cancel();+ _catalogTimer = Timer(delay, () => unawaited(_rebuildCatalog()));+ }++ Future<void> _ensureCatalogLoaded() async {+ if (_catalogLoaded) return;+ _catalogLoaded = true;+ if (_catalog.isNotEmpty) return;+ try {+ final file = await _catalogFile();+ if (file == null || !file.existsSync()) return;+ final data = jsonDecode(await file.readAsString()) as Map<String, dynamic>;+ _catalog = (data['entries'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .map(SiriEntry.fromJson)+ .toList();+ debugPrint('[Siri] loaded ${_catalog.length} entries from the last run');+ } catch (e) {+ debugPrint('[Siri] catalog read failed: $e');+ }+ }++ Future<File?> _catalogFile() async {+ try {+ final dir = await _widgetChannel.invokeMethod<String>('getGroupContainerPath');+ if (dir == null) return null;+ return File('$dir/$catalogFileName');+ } catch (_) {+ return null;+ }+ }++ Future<void> _rebuildCatalog() async {+ if (_rebuilding) return;+ _rebuilding = true;+ if (!_askedAutoRefresh) {+ // On iOS the car's browse lists only fill when CarPlay connects; one+ // refresh a launch gives Siri every library's Continue and Recent rows.+ // It calls back through serverDataListeners when the server answers.+ _askedAutoRefresh = true;+ unawaited(AndroidAutoService().refresh());+ }+ try {+ final entries = <String, SiriEntry>{};+ void add(SiriEntry? e) {+ if (e == null || e.title.isEmpty) return;+ final had = entries[e.id];+ if (had == null) {+ entries[e.id] = e;+ } else if (had.series.isEmpty && e.series.isNotEmpty) {+ entries[e.id] = had.copyWith(series: e.series);+ }+ }++ for (final item in libraryItems?.call() ?? const <Map<String, dynamic>>[]) {+ if (item['books'] is List && item['name'] is String) {+ final books = (item['books'] as List).whereType<Map<String, dynamic>>().toList();+ final libraryId = item['libraryId'] as String? ??+ (books.isNotEmpty ? books.first['libraryId'] as String? : null);+ if (item['id'] is String && libraryId != null) {+ add(SiriEntry(kind: 'series', itemId: item['id'] as String, libraryId: libraryId, title: item['name'] as String));+ }+ for (final b in books) {+ add(entryFromItem(b));+ }+ continue;+ }+ add(entryFromItem(item));+ add(_episodeFromItem(item));+ }+ final auto = AndroidAutoService();+ for (final e in [...auto.continueListening, ...auto.recentlyAdded, ...auto.downloaded]) {+ add(_entryFromAuto(e));+ }+ final downloads = DownloadService();+ final downloadedKeys = <String>{};+ for (final d in downloads.downloadedItems) {+ downloadedKeys.add(d.itemId);+ add(_entryFromDownload(d));+ }++ var list = entries.values.map((e) {+ final key = e.episodeId == null ? e.itemId : '${e.itemId}-${e.episodeId}';+ if (!downloadedKeys.contains(key)) return e;+ final info = downloads.getInfo(key);+ return e.copyWith(downloaded: true, coverPath: e.coverPath ?? info.localCoverPath);+ }).toList();+ final api = await auto.getApi();+ list = await _withProgress(list, api: api);+ _catalog = list;+ _catalogLoaded = true;+ await _publishCatalog(list);+ } catch (e) {+ debugPrint('[Siri] catalog rebuild failed: $e');+ } finally {+ _rebuilding = false;+ }+ }++ Future<List<SiriEntry>> _withProgress(List<SiriEntry> list, {ApiService? api}) async {+ final progress = api == null ? _progress : await _progressMap(api);+ if (progress.isEmpty) return list;+ final showLatest = <String, Map<String, dynamic>>{};+ for (final p in progress.values) {+ if (p['episodeId'] is! String) continue;+ final show = p['libraryItemId'] as String;+ if (_lastUpdate(p) > _lastUpdate(showLatest[show])) showLatest[show] = p;+ }+ return list.map((e) {+ final key = e.kind == 'episode' ? '${e.itemId}-${e.episodeId}' : e.itemId;+ final p = e.kind == 'podcast' ? showLatest[e.itemId] : progress[key];+ if (p == null) return e;+ return e.copyWith(+ progress: ((p['progress'] as num?) ?? 0).toDouble(),+ finished: e.kind != 'podcast' && p['isFinished'] == true,+ lastPlayed: _lastUpdate(p),+ );+ }).toList();+ }++ Future<void> _publishCatalog(List<SiriEntry> list) async {+ final ordered = [...list]..sort((a, b) {+ final r = (b.inProgress ? 1 : 0).compareTo(a.inProgress ? 1 : 0);+ if (r != 0) return r;+ return b.lastPlayed.compareTo(a.lastPlayed);+ });+ final file = await _catalogFile();+ if (file != null) {+ try {+ await file.writeAsString(jsonEncode({+ 'updatedAt': DateTime.now().millisecondsSinceEpoch,+ 'entries': ordered.take(20000).map((e) => e.toJson()).toList(),+ }));+ } catch (e) {+ debugPrint('[Siri] catalog write failed: $e');+ }+ }+ List<String> unique(Iterable<String> values, int cap) {+ final seen = <String>{};+ final out = <String>[];+ for (final v in values) {+ final t = v.trim();+ if (t.isEmpty || !seen.add(t.toLowerCase())) continue;+ out.add(t);+ if (out.length == cap) break;+ }+ return out;+ }++ final books = ordered.where((e) => e.kind == 'book');+ final titles = unique(books.map((e) => e.title), 500);+ final authors = unique(books.expand((e) => e.author.split(RegExp(r',|&'))), 200);+ final series = unique(ordered.expand((e) => e.kind == 'series' ? [e.title] : e.series), 200);+ final shows = unique(ordered.where((e) => e.kind == 'podcast').map((e) => e.title), 100);+ final upNext = ordered.where((e) => e.inProgress && e.kind != 'series').take(5).map(_itemJson).toList();+ debugPrint('[Siri] catalog ${ordered.length} entries, ${titles.length} titles, '+ '${authors.length} authors, ${shows.length} shows');+ try {+ await _channel.invokeMethod('catalogUpdated', {+ 'count': ordered.length,+ 'titles': [...titles, ...series],+ 'authors': authors,+ 'shows': shows,+ 'upNext': upNext,+ });+ } catch (e) {+ debugPrint('[Siri] catalogUpdated failed: $e');+ }+ await _maybeAskForSiri(ordered.isNotEmpty);+ }++ // Siri permission++ Future<String> authorizationStatus() async {+ if (!Platform.isIOS) return 'unsupported';+ try {+ return await _channel.invokeMethod<String>('authorizationStatus') ?? 'notDetermined';+ } catch (_) {+ return 'notDetermined';+ }+ }++ Future<String> requestAuthorization() async {+ if (!Platform.isIOS) return 'unsupported';+ try {+ final status = await _channel.invokeMethod<String>('requestAuthorization') ?? 'notDetermined';+ if (status == 'authorized') scheduleCatalogUpdate(delay: Duration.zero);+ return status;+ } catch (_) {+ return 'notDetermined';+ }+ }++ Future<void> openSystemSettings() async {+ try {+ await _channel.invokeMethod('openSettings');+ } catch (_) {}+ }++ /// One prompt, the first time there is something to ask Siri about and the+ /// listener is looking at the app. Settings has the switch after that.+ Future<void> _maybeAskForSiri(bool hasBooks) async {+ if (!hasBooks) return;+ final prefs = await SharedPreferences.getInstance();+ if (prefs.getBool('siri_auth_asked') == true) return;+ if (WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed) return;+ if (await authorizationStatus() != 'notDetermined') {+ await prefs.setBool('siri_auth_asked', true);+ return;+ }+ await prefs.setBool('siri_auth_asked', true);+ await requestAuthorization();+ }++ // Item shapes++ /// A book or podcast show from an Audiobookshelf-shaped library item.+ static SiriEntry? entryFromItem(Map<String, dynamic> item, {String? libraryId}) {+ final id = item['id'] as String?;+ final media = item['media'] as Map<String, dynamic>?;+ final meta = media?['metadata'] as Map<String, dynamic>?;+ final title = meta?['title'] as String?;+ if (id == null || media == null || title == null || title.trim().isEmpty) return null;+ final podcast = item['mediaType'] == 'podcast';+ if (!podcast && !_hasAudio(media)) return null;+ return SiriEntry(+ kind: podcast ? 'podcast' : 'book',+ itemId: id,+ libraryId: item['libraryId'] as String? ?? libraryId,+ title: title.trim(),+ author: podcast ? (meta?['author'] as String? ?? '') : _authorOf(meta!),+ series: podcast ? const [] : _seriesOf(meta!),+ );+ }++ static SiriEntry? _episodeFromItem(Map<String, dynamic> item) {+ final ep = item['recentEpisode'] as Map<String, dynamic>?;+ final id = item['id'] as String?;+ final episodeId = ep?['id'] as String?;+ final title = ep?['title'] as String?;+ if (id == null || episodeId == null || title == null || title.isEmpty) return null;+ final show = ((item['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?)?['title'] as String?;+ return SiriEntry(+ kind: 'episode',+ itemId: id,+ episodeId: episodeId,+ libraryId: item['libraryId'] as String?,+ title: title,+ author: show ?? '',+ );+ }++ static bool _hasAudio(Map<String, dynamic> media) {+ if (media['narration'] != null) return true;+ for (final k in ['numTracks', 'numAudioFiles']) {+ final n = media[k];+ if (n is num) return n > 0;+ }+ for (final k in ['tracks', 'audioFiles']) {+ final l = media[k];+ if (l is List) return l.isNotEmpty;+ }+ final d = media['duration'];+ if (d is num) return d > 0;+ return true;+ }++ static String _authorOf(Map<String, dynamic> meta) {+ final name = meta['authorName'] as String?;+ if (name != null && name.isNotEmpty) return name;+ return (meta['authors'] as List<dynamic>? ?? const [])+ .map((a) => a is Map ? a['name'] as String? ?? '' : '$a')+ .where((n) => n.isNotEmpty)+ .join(', ');+ }++ static final _seriesNumber = RegExp(r'\s+#\s*[\d.]+.*$');++ static List<String> _seriesOf(Map<String, dynamic> meta) {+ final list = meta['series'];+ if (list is List) {+ final names = list+ .map((s) => s is Map ? s['name'] as String? ?? '' : '')+ .where((n) => n.isNotEmpty)+ .toList();+ if (names.isNotEmpty) return names;+ }+ final joined = meta['seriesName'] as String?;+ if (joined == null || joined.isEmpty) return const [];+ return joined+ .split(', ')+ .map((s) => s.replaceFirst(_seriesNumber, '').trim())+ .where((s) => s.isNotEmpty)+ .toList();+ }++ static SiriEntry? _entryFromAuto(AutoBookEntry e) {+ if (e.title.isEmpty) return null;+ if (e.mediaType == 'podcast' && e.episodeId != null) {+ final show = e.showId ?? (e.id.length > 36 ? e.id.substring(0, 36) : e.id);+ return SiriEntry(+ kind: 'episode',+ itemId: show,+ episodeId: e.episodeId,+ libraryId: e.libraryId,+ title: e.title,+ author: e.author,+ );+ }+ return SiriEntry(+ kind: e.mediaType == 'podcast' ? 'podcast' : 'book',+ itemId: e.id,+ libraryId: e.libraryId,+ title: e.title,+ author: e.author,+ );+ }++ static SiriEntry? _entryFromDownload(DownloadInfo d) {+ final title = d.title;+ if (title == null || title.isEmpty) return null;+ final key = d.itemId;+ final episode = key.length > 37 && key[36] == '-';+ return SiriEntry(+ kind: episode ? 'episode' : 'book',+ itemId: episode ? key.substring(0, 36) : key,+ episodeId: episode ? key.substring(37) : null,+ libraryId: d.libraryId,+ title: title,+ author: d.author ?? '',+ downloaded: true,+ coverPath: d.localCoverPath,+ );+ }+}diff --git a/lib/services/up_next_narration.dart b/lib/services/up_next_narration.dartnew file mode 100644index 00000000..364c55da--- /dev/null+++ b/lib/services/up_next_narration.dart@@ -0,0 +1,95 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_local_notifications/flutter_local_notifications.dart';+import 'package:provider/provider.dart';++import '../l10n/app_localizations.dart';+import '../main.dart' show rootNavigatorKey;+import '../providers/auth_provider.dart';+import '../providers/library_provider.dart';+import '../widgets/narration_download_dialog.dart';+import '../widgets/overlay_toast.dart';+import 'audio_player_service.dart';+import 'download_service.dart';+import 'narrated_books.dart';++/// An Audiobookshelf EPUB that reads itself aloud plays only once its+/// narration is downloaded, so a queue must never reach one unready. Starting+/// a book from the app when it is three quarters done offers the download of+/// an EPUB that is next in the queue; a queue that gets there anyway stops+/// (never skipping it) and says why.+class UpNextNarration {+ UpNextNarration._();+ static final UpNextNarration instance = UpNextNarration._();++ static const _nearTheEnd = 0.75;++ // Asked once a run for each up-next book, so "Not now" sticks.+ final Set<String> _asked = {};++ /// Whether [key] is a narrated EPUB on Audiobookshelf that can't play yet.+ bool needsDownload(String key) {+ if (key.length > 36 || !NarratedBooks.contains(key)) return false;+ final dl = DownloadService();+ return !dl.isDownloaded(key) && !dl.isDownloading(key);+ }++ /// A book was started from the app: past three quarters, a narrated EPUB+ /// next in the queue that still needs downloading is offered now.+ Future<void> checkOnPlay(LibraryProvider lib, String itemId) async {+ try {+ final player = AudioPlayerService();+ final total = player.totalDuration;+ if (total <= 0) return;+ final done = player.position.inMilliseconds / 1000.0 / total;+ if (done < _nearTheEnd) return;+ final next = await lib.upNextEntry(currentItemId: itemId);+ if (next == null || !needsDownload(next.key) || !_asked.add(next.key)) return;+ final ctx = rootNavigatorKey.currentContext;+ if (ctx == null || !ctx.mounted) return;+ final api = ctx.read<AuthProvider>().apiService;+ if (api == null || api.isBookOrbit) return;+ debugPrint('[UpNext] $itemId is ${(done * 100).toStringAsFixed(0)}% done and '+ '${next.key} is next, narration not downloaded - offering it');+ final l = AppLocalizations.of(ctx)!;+ await showNarrationDownloadDialog(+ ctx,+ itemId: next.key,+ title: next.bookTitle,+ heading: l.narrationUpNextTitle,+ message: l.narrationUpNextBody(next.bookTitle),+ );+ } catch (e) {+ debugPrint('[UpNext] heads-up check failed: $e');+ }+ }++ /// The queue reached [key] without its narration: playback stops here and+ /// says why, on screen or as a notification.+ Future<void> stopped(String key, String title) async {+ debugPrint('[UpNext] queue stopped before $key: narration not downloaded');+ final ctx = rootNavigatorKey.currentContext;+ final l = ctx == null ? null : AppLocalizations.of(ctx);+ final onScreen = WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;+ if (ctx != null && l != null && onScreen) {+ showOverlayToast(ctx, l.narrationQueueStopped(title), icon: Icons.download_rounded);+ return;+ }+ try {+ await FlutterLocalNotificationsPlugin().show(+ key.hashCode & 0x7FFFFFFF,+ l?.narrationDownloadTitle ?? 'Download to listen',+ l?.narrationQueueStopped(title) ?? 'Stopped before $title. Download it to keep going.',+ NotificationDetails(+ android: Platform.isAndroid+ ? const AndroidNotificationDetails('up_next', 'Up next', importance: Importance.defaultImportance)+ : null,+ iOS: const DarwinNotificationDetails(),+ ),+ );+ } catch (e) {+ debugPrint('[UpNext] notification failed: $e');+ }+ }+}diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex dea75c25..85632cb6 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -9,6 +9,11 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:provider/provider.dart';import 'overlay_toast.dart';+import 'narration_download_dialog.dart';+import 'progress_dialog.dart';+import '../services/media_overlay.dart';+import '../services/narration_service.dart';+import '../services/read_listen_sync.dart';import '../services/book_dock.dart';import '../services/bookorbit_mapper.dart';import 'absorb_placement.dart';@@ -240,6 +245,87 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {return _rawCoverScheme;}+ // What this phone knows about the EPUB reading itself aloud: true, false+ // (checked, it doesn't), or null (not looked at yet).+ bool? _knownNarrated;+ // An Audiobookshelf ebook-only book whose EPUB reads itself aloud: the+ // sheet shows it as an audiobook, the way BookOrbit's arrive.+ MediaOverlay? _localNarration;++ /// Looks into an Audiobookshelf ebook-only EPUB on the server (its index+ /// and timings only) to see whether it reads itself aloud.+ Future<void> _probeNarration() async {+ final item = _item;+ final auth = context.read<AuthProvider>();+ final api = auth.apiService;+ if (item == null || api == null || auth.isBookOrbit || _localNarration != null) return;+ if (!PlayerSettings.isEbookOnly(item, countNarration: false)) return;+ final o = await NarrationService.instance.probe(api, item);+ if (o != null) await NarrationService.instance.markAudiobook(widget.itemId, o);+ final known = await NarrationService.instance.knownNarrated(widget.itemId);+ if (!mounted) return;+ setState(() {+ _localNarration = o;+ _knownNarrated = known;+ });+ }++ /// Puts the narration on the phone (just the audio, out of the EPUB on the+ /// server), with how far along it is. False when there is none.+ Future<bool> _prepareNarration() async {+ final l = AppLocalizations.of(context)!;+ final api = context.read<AuthProvider>().apiService;+ final item = _item;+ if (api == null || item == null) return false;+ debugPrint('[Narration] ${widget.itemId} can not stream - downloading the narration first');+ final label = ValueNotifier<String>(l.narrationPreparing);+ showProgressDialogListenable(context, label);+ var ok = false;+ try {+ ok = await NarrationService.instance.prepareLocal(api, item, onProgress: (p) {+ label.value = '${l.narrationPreparing} ${(p * 100).clamp(0, 100).toStringAsFixed(0)}%';+ });+ } catch (e) {+ debugPrint('[Narration] getting the narration failed: $e');+ }+ if (mounted) Navigator.of(context, rootNavigator: true).pop();+ Future.delayed(const Duration(milliseconds: 500), label.dispose);+ if (!mounted) return false;+ final o = ok ? await NarrationService.instance.localOverlay(widget.itemId) : null;+ final known = await NarrationService.instance.knownNarrated(widget.itemId);+ if (!mounted) return false;+ setState(() {+ _localNarration = o ?? _localNarration;+ _knownNarrated = known;+ });+ if (!ok) showOverlayToast(context, l.narrationNone, icon: Icons.headphones_rounded);+ return ok;+ }++ /// The Listen button on a big EPUB this phone couldn't look into (a server+ /// without range requests): fetch it whole, then play like Absorb.+ Future<void> _listenToNarration() async {+ if (!await _prepareNarration() || !mounted) return;+ final o = _localNarration;+ if (o == null) return;+ final shaped = NarrationService.instance.withNarration(_item!, o);+ final media = shaped['media'] as Map<String, dynamic>;+ final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};+ setState(() {+ _item = shaped;+ _isAbsorbing = true;+ });+ await _startAbsorb(+ context,+ auth: context.read<AuthProvider>(),+ title: metadata['title'] as String? ?? '',+ author: metadata['authorName'] as String? ?? '',+ coverUrl: _coverUrl,+ duration: (media['duration'] as num?)?.toDouble() ?? 0,+ chapters: media['chapters'] as List<dynamic>? ?? const [],+ );+ }+@override void initState() {super.initState();// Quick-actions sheet seeds from the tile's item map so it paints instantly@@ -254,6 +340,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {_loadItem();_loadBookmarks();_warmStats();+ NarrationService.instance.knownNarrated(widget.itemId).then((known) {+ if (known != null && mounted) setState(() => _knownNarrated = known);+ });SocketService().addItemUpdatedListener(_onSocketItemUpdated);_loadCoverShape();PlayerSettings.getShowGoodreadsButton().then((v) { if (mounted) setState(() => _showGoodreads = v); });@@ -429,7 +518,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final start = (s['startTime'] as num?)?.toDouble() ?? 0;final end = (s['currentTime'] as num?)?.toDouble() ?? start;final device = s['deviceInfo'] as Map<String, dynamic>?;- final where = (device?['deviceName'] as String?) ?? (device?['clientName'] as String?) ?? '';+ final place = (device?['deviceName'] as String?) ?? (device?['clientName'] as String?) ?? '';+ final where = s['mediaPlayer'] == ApiService.readingMediaPlayer+ ? [place, AppLocalizations.of(context)!.sessionReading].where((p) => p.isNotEmpty).join(' · ')+ : place;return Padding(padding: const EdgeInsets.fromLTRB(14, 8, 14, 8),child: Row(children: [@@ -492,6 +584,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}setState(() { _item = finalItem; _isLoading = false; });+ unawaited(_probeNarration());_loadCoverShape();if (BookDockInfo.of(finalItem)?.isWorking ?? false) {_dockPoll?.cancel();@@ -730,6 +823,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {Widget _buildContent(BuildContext context, ColorScheme cs, TextTheme tt, AppLocalizations l) {final accent =(PlayerSettings.einkMode ? null : _coverScheme?.primary) ?? cs.primary;+ // A reload brings the server's ebook-only shape back; the narration found+ // on this phone makes it an audiobook again.+ final narration = _localNarration;+ if (narration != null) _item = NarrationService.instance.withNarration(_item!, narration);final media = _item!['media'] as Map<String, dynamic>? ?? {};final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final chapters = media['chapters'] as List<dynamic>? ?? [];@@ -903,13 +1000,57 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {const SizedBox(height: 20),const SizedBox(height: 12),if (isEbookOnly && ebookFile != null && canReadEbook(ebookFile))- SizedBox(height: 52, child: FilledButton.icon(- onPressed: () => _openEbookReader(context, auth, ebookFile, title),- icon: const Icon(Icons.menu_book_rounded, size: 24),- label: Text(l.readEbook,- style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onPrimary)),- style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))),- ))+ // Reading progress fills the button the same way listening progress+ // fills Absorb.+ Builder(builder: (context) {+ final onAccent = _coverScheme?.onPrimary ?? cs.onPrimary;+ // A library refresh on BookOrbit carries an ebook-only book's+ // reading percent as its plain progress, with no ebook field.+ final saved = lib.getEbookProgress(widget.itemId);+ final ebookProgress = saved > 0 ? saved : progress;+ final showFill = ebookProgress > 0 && ebookProgress < 1 && !isFinished;+ return SizedBox(+ height: 52,+ child: Material(+ color: accent,+ borderRadius: BorderRadius.circular(16),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () => _openEbookReader(context, auth, ebookFile, title),+ child: Stack(children: [+ if (showFill)+ FractionallySizedBox(+ widthFactor: ebookProgress.clamp(0.0, 1.0),+ child: Container(color: onAccent.withValues(alpha: 0.22)),+ ),+ Center(+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.menu_book_rounded, size: 24, color: onAccent),+ const SizedBox(width: 8),+ Text(l.readEbook,+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: onAccent)),+ ]),+ ),+ if (showFill)+ Positioned(+ right: 14,+ top: 0,+ bottom: 0,+ child: Center(+ child: Text(+ '${(ebookProgress * 100).toStringAsFixed(0)}%',+ style: tt.labelMedium?.copyWith(+ fontWeight: FontWeight.w700,+ color: onAccent.withValues(alpha: 0.85),+ ),+ ),+ ),+ ),+ ]),+ ),+ ),+ );+ })else if (isEbookOnly && ebookFile != null)// Ebook-only but not readable in-app (CBR) - can't open it, so the// primary action exports the file to the device instead.@@ -1048,6 +1189,65 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {},),),+ ValueListenableBuilder<Map<String, SyncTarget>>(+ valueListenable: ReadListenSync.instance.syncing,+ builder: (context, syncing, _) {+ final to = syncing[widget.itemId];+ return AnimatedSize(+ duration: const Duration(milliseconds: 200),+ child: to == null+ ? const SizedBox(width: double.infinity)+ : Padding(+ padding: const EdgeInsets.only(top: 10),+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [+ SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(strokeWidth: 2, color: accent),+ ),+ const SizedBox(width: 10),+ Flexible(+ child: Text(+ to == SyncTarget.audio ? l.syncFindingAudio : l.syncFindingEbook,+ style: tt.labelMedium?.copyWith(color: cs.onSurfaceVariant),+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ]),+ ),+ );+ },+ ),+ // A big EPUB this phone couldn't look into (a server without range+ // requests) may read itself aloud; tapping finds out. A checked one+ // shows as an audiobook instead.+ if (isEbookOnly &&+ ebookFile != null &&+ ebookExtFromFile(ebookFile) == '.epub' &&+ !lib.isOffline &&+ _knownNarrated == null &&+ ((ebookFile['metadata'] as Map?)?['size'] as num? ?? 0) > 150 * 1024 * 1024) ...[+ const SizedBox(height: 8),+ SizedBox(+ height: 40,+ child: Material(+ color: accent.withValues(alpha: 0.14),+ borderRadius: BorderRadius.circular(14),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: _listenToNarration,+ child: Center(+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.headphones_rounded, size: 18, color: accent),+ const SizedBox(width: 8),+ Text(l.narrationListen,+ style: tt.labelLarge?.copyWith(fontWeight: FontWeight.w600, color: accent)),+ ]),+ ),+ ),+ ),+ ),+ ],// A companion ebook gets its own, smaller button under Absorb with the// reading progress filled in the same way. Ebook-only books already// have Read as the big button above.@@ -3005,7 +3205,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (api == null) return;setState(() => _ebookOfflineDownloading = true);try {- await fetchEbookToCache(api, widget.itemId, ebookFile, title);+ await NarrationService.instance.readerFile(api, widget.itemId, ebookFile, title);await DownloadService().registerEbookDownload(api: api,itemId: widget.itemId,@@ -3366,6 +3566,30 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {/// [startTime] plays from there instead of the saved position (a chapter/// tapped in the list); on the live session it is a seek.Future<void> _startAbsorb(BuildContext context, {required AuthProvider auth, required String title, required String author, required String? coverUrl, required double duration, required List<dynamic> chapters, double? startTime}) async {+ // An Audiobookshelf narrated EPUB plays once its narration is downloaded:+ // asked first, with the reason.+ final narration = (_item?['media'] as Map?)?['narration'] as Map?;+ if (narration?['local'] == true && !NarrationService.instance.hasLocalAudio(widget.itemId)) {+ if (mounted) setState(() => _isAbsorbing = false);+ await showNarrationDownloadDialog(+ context,+ itemId: widget.itemId,+ title: title,+ author: author,+ coverUrl: coverUrl,+ libraryId: _item?['libraryId'] as String?,+ );+ return;+ }+ // Leaving the reader may still be finding this book's spot in the audio:+ // wait for it, so playback starts at the page rather than moving later.+ final finding = ReadListenSync.instance.audioSpotBeingFound(widget.itemId);+ if (startTime == null && finding != null) {+ debugPrint('[SyncSpot] ${widget.itemId}: waiting for the reading spot before playing');+ final t = await finding.timeout(const Duration(seconds: 20), onTimeout: () => null);+ if (!context.mounted) return;+ if (t != null) startTime = t;+ }// Discard, not stop: we're about to start playback ourselves, so briefly// resuming the previous book would just be an audible blip.await _preview?.discard();diff --git a/lib/widgets/bookmark_detail_dialog.dart b/lib/widgets/bookmark_detail_dialog.dartindex 703230ad..dbe89aba 100644--- a/lib/widgets/bookmark_detail_dialog.dart+++ b/lib/widgets/bookmark_detail_dialog.dart@@ -14,6 +14,7 @@ import '../services/bookmark_preview_player.dart';import '../services/chapter_lookup.dart';import '../services/download_service.dart';import '../services/ebook_cache.dart';+import '../services/narration_service.dart';import '../services/transcription_service.dart';import '../utils/episode_key.dart';import '../utils/passage_match.dart';@@ -258,7 +259,7 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {if (!f.existsSync() || await f.length() <= 0) {final api = widget.api;if (api == null) return null;- f = await fetchEbookToCache(api, widget.itemId, ebookFile, '');+ f = await NarrationService.instance.readerFile(api, widget.itemId, ebookFile, '');}return await compute(correctFromEpub, (epubPath: f.path, transcript: transcript));} catch (e) {diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex da18c879..89061c50 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -15,6 +15,7 @@ import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../screens/app_shell.dart';import '../services/api_service.dart';+import '../services/audio_locator.dart';import '../services/audio_player_service.dart';import '../services/chapter_lookup.dart';import '../services/chromecast_service.dart';@@ -27,6 +28,13 @@ import '../services/reader_font_service.dart';import '../services/scoped_prefs.dart';import '../services/lyrics_service.dart';import '../services/read_along_script.dart';+import '../services/read_listen_sync.dart';+import '../services/ebook_history.dart';+import '../services/local_session_service.dart';+import 'absorbing_shared.dart' show dateLabel, timeOfDay;+import '../services/media_overlay.dart';+import '../services/narration_script.dart';+import '../services/narration_service.dart';import '../services/screen_wake.dart';import '../services/sync_point_store.dart';import '../services/transcript_line_store.dart';@@ -35,6 +43,7 @@ import '../services/volume_key_service.dart';import '../utils/chapter_title_match.dart';import 'overlay_toast.dart';import 'transcription_download_prompt.dart';+import 'narration_download_dialog.dart';import 'progress_dialog.dart';import 'quote_share_sheet.dart';import 'book_detail_sheet.dart';@@ -133,6 +142,27 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// epub.js can map percentages to pages.double? _pendingPercentJump;String? _firstShownCfi;+ // The place is written back only once the reader has moved from where it+ // opened. The landing can be off from the server's spot (another app's+ // page size, a percent jump, a slow server), and saving it replaced the+ // real place before a single page was turned.+ bool _holdOpenSpot = true;++ // Reading time kept as a session (the Tt switch): counted while the page+ // is on screen and has moved in the last few minutes, and not while this+ // book's audio plays (that listening session already counts it).+ static const _kLogReading = 'ereader_log_reading';+ bool _logReading = false;+ Timer? _readingTimer;+ ApiService? _readingApi;+ String? _readingSessionId;+ DateTime? _readingStartedAt;+ double? _readingStartPct;+ int _readingSeconds = 0;+ int _readingSent = 0;+ DateTime _readingActiveAt = DateTime.now();+ bool _readingAudioWasOn = false;+ double _audioTotal = 0;bool _showControls = false;List<EpubChapter> _chapters = [];double _progress = 0;@@ -242,6 +272,28 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsDateTime? _readAlongSeenSince;DateTime _readAlongOffPageLog = DateTime.fromMillisecondsSinceEpoch(0);+ // A narrated EPUB (EPUB 3 media overlays) knows which sentence is read+ // when, so its read along follows those timings instead of transcribing.+ MediaOverlay? _narration;+ bool _narrationReadAlong = false;+ OverlayClip? _narrationWentTo;+ DateTime _narrationTurnAt = DateTime.fromMillisecondsSinceEpoch(0);+ bool _narrationTickBusy = false;+ // Where the lit sentence was on the last tick: on, low, before, after.+ String? _narrationWhere;++ bool get _narrationOnScreen => _narrationWhere == 'on' || _narrationWhere == 'low';++ bool _narrationFromServer = false;+ bool _audioIsNarration = false;++ /// Read along can follow the narration when the book's audio is that+ /// narration: BookOrbit plays it as the audio, and an Audiobookshelf+ /// ebook-only book has it fetched out of the EPUB. A book with its own+ /// audiobook keeps transcription.+ bool get _useNarration =>+ _narration != null && (_narrationFromServer || !_hasAudio || _audioIsNarration);+// Reader settingsint _fontSize = 16;double _lineHeight = 1.4;@@ -267,6 +319,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// Keep the title and progress bar on screen above the page instead of// fading them in over it. The page gets shorter, never covered.bool _pinTop = false;+ // What the top bar's progress follows: 'book', 'chapter' or 'both'.+ String _topBarProgress = 'book';// Hold the screen on for the whole read, not only while auto scroll or// read along moves the page (GH #384).bool _keepAwake = true;@@ -292,6 +346,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsstatic const _kTheme = 'ereader_theme';static const _kFont = 'ereader_font';static const _kPinTop = 'ereader_pin_top';+ static const _kTopBarProgress = 'ereader_top_bar_progress';static const _kKeepAwake = 'ereader_keep_awake';// App-wide, not per account: one switch for every server's books.static const _kScroll = 'ereader_scroll_mode';@@ -326,6 +381,14 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsvoid initState() {super.initState();WidgetsBinding.instance.addObserver(this);+ ReadListenSync.instance.readerOpened(widget.itemId);+ _readingApi = context.read<AuthProvider>().apiService;+ ScopedPrefs.getBool(_kLogReading).then((on) {+ if (on == true && mounted) {+ setState(() => _logReading = true);+ _startReadingClock();+ }+ });_epubController = EpubController();_quietLib = context.read<LibraryProvider>();_quietLib.setReaderQuiet(true);@@ -353,12 +416,12 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObslate final EreaderVolumeNav _volumeNav = EreaderVolumeNav(onPrev: () {if (_autoScroll) return;- _readAlongUserMoved('volume key');+ _userMoved('volume key');_epubController?.prev();},onNext: () {if (_autoScroll) return;- _readAlongUserMoved('volume key');+ _userMoved('volume key');_epubController?.next();},);@@ -395,7 +458,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsstate == AppLifecycleState.hidden) {// Leaving the foreground: snapshot the real page and stop trusting// relocations until we're back (they'll be resize artifacts).- if (_readerActive) _bgCfi = _currentCfi;+ if (_readerActive) {+ _bgCfi = _currentCfi;+ unawaited(_narrationCarryReadingSpot());+ if (_logReading) unawaited(_sendReadingTime());+ }_readerActive = false;// Following along costs transcription and a WebView call several times// a second, and nobody is reading a page they can't see.@@ -427,6 +494,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_audioDuration = dur;_audioChapters = media['chapters'] as List<dynamic>? ?? const [];_hasAudio = dur > 0;+ _audioTotal = dur;+ _audioIsNarration = media['narration'] != null;});} catch (_) {}}@@ -499,6 +568,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_themeId = await ScopedPrefs.getString(_kTheme) ?? '';_fontId = await ScopedPrefs.getString(_kFont) ?? 'original';_pinTop = await ScopedPrefs.getBool(_kPinTop) ?? false;+ final barProgress = await ScopedPrefs.getString(_kTopBarProgress);+ if (barProgress == 'chapter' || barProgress == 'both') _topBarProgress = barProgress!;_keepAwake = await ScopedPrefs.getBool(_kKeepAwake) ?? true;_barAction = await ScopedPrefs.getString(_kBarAction) ?? 'speed';if (mounted) _syncScreenWake();@@ -734,6 +805,12 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsawait ScopedPrefs.setBool(_kKeepAwake, on);}+ Future<void> _updateTopBarProgress(String mode) async {+ if (mode == _topBarProgress) return;+ setState(() => _topBarProgress = mode);+ await ScopedPrefs.setString(_kTopBarProgress, mode);+ }+Future<void> _updatePinTop(bool on) async {if (on == _pinTop) return;// The WebView gets shorter or taller, so epub.js re-paginates and@@ -756,6 +833,12 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs@overridevoid dispose() {+ _narrationSpotTimer?.cancel();+ unawaited(_narrationCarryReadingSpot());+ ReadListenSync.instance.readerClosed(widget.itemId, _currentCfi, moved: !_holdOpenSpot);+ _rememberSpot(EbookSpotReason.closed);+ _readingTimer?.cancel();+ if (_logReading) unawaited(_sendReadingTime(closing: true));_stopReadAlong();_speedToast?.dismiss();_autoScrollSleepTimer?.cancel();@@ -840,10 +923,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsvoid _commitReaderTap(String action) {if (action == 'prev') {- _readAlongUserMoved('tap');+ _userMoved('tap');_epubController?.prev();} else if (action == 'next') {- _readAlongUserMoved('tap');+ _userMoved('tap');_epubController?.next();} else {_toggleControls();@@ -973,23 +1056,49 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// the web reader or another device may have moved on, and a BookOrbit/// library refresh carries no ebook position at all, which left the reader/// starting over and then saving the start on top of the real spot. A place- /// this phone hasn't sent yet wins, and a slow server keeps the phone's.+ /// this phone hasn't sent yet wins unless the server's ebook place is newer,+ /// and a slow server keeps the phone's.Future<void> _pullServerPosition(ApiService api) async {if (widget.openAtCfi != null || !mounted) return;final lib = context.read<LibraryProvider>();if (lib.isOffline) return;try {- final pending = await ProgressSyncService().getPendingEbookProgress();- if (pending.containsKey(widget.itemId)) return;+ final pending =+ (await ProgressSyncService().getPendingEbookProgress())[widget.itemId];final server = await api- .getItemProgress(widget.itemId)- .timeout(const Duration(seconds: 3), onTimeout: () => null);- if (!mounted) return;- final loc = server?['ebookLocation'] as String?;- if (loc == null || !loc.startsWith('epubcfi(')) return;+ .getEbookPosition(widget.itemId)+ .timeout(const Duration(seconds: 6), onTimeout: () {+ debugPrint('[EbookReader] server position check timed out item=${widget.itemId}');+ return null;+ });+ if (!mounted || server == null) return;+ if (pending != null) {+ final serverAt = (server['ebookUpdatedAt'] as num?)?.toInt();+ final pendingAt = (pending['ts'] as num?)?.toInt();+ if (serverAt == null || pendingAt == null || pendingAt >= serverAt) return;+ debugPrint('[EbookReader] dropping the queued place for item=${widget.itemId}: '+ 'the server moved on after it');+ await ProgressSyncService().dropPendingEbookProgress(widget.itemId);+ if (!mounted) return;+ }+ final loc = server['ebookLocation'] as String?;+ final serverProgress = (server['ebookProgress'] as num?)?.toDouble();final local = lib.getProgressData(widget.itemId);+ if (loc == null || !loc.startsWith('epubcfi(')) {+ // Kobo and KOReader leave a percent with no CFI: open there rather+ // than at the phone's older place or the start.+ if (serverProgress == null || serverProgress <= 0 || serverProgress >= 1) return;+ final localProgress = (local?['ebookProgress'] as num?)?.toDouble();+ if (localProgress != null && (localProgress - serverProgress).abs() < 0.005) return;+ debugPrint('[EbookReader] taking the server percent item=${widget.itemId} '+ 'pct=$serverProgress (no CFI)');+ _initialCfi = null;+ _progress = serverProgress;+ _pendingPercentJump = serverProgress;+ return;+ }if (local?['ebookLocation'] == loc) return;- final progress = (server!['ebookProgress'] as num?)?.toDouble() ??+ final progress = serverProgress ??(local?['ebookProgress'] as num?)?.toDouble() ??0;debugPrint('[EbookReader] taking the server position item=${widget.itemId} '@@ -1016,12 +1125,16 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfinal playing = AudioPlayerService().isPlaying;debugPrint('[EbookReader] open item=${widget.itemId} ext=${ebookExtFromFile(widget.ebookFile)} ''cached=${await isEbookCached(widget.itemId, widget.ebookFile)} playing=$playing');- final file = await fetchEbookToCache(api, widget.itemId, widget.ebookFile, widget.title);+ // Asked while the file downloads, so a slow answer costs no extra wait.+ final serverSpot = _otherAccount ? null : _pullServerPosition(api);+ final file = await NarrationService.instance+ .readerFile(api, widget.itemId, widget.ebookFile, widget.title);+ unawaited(_loadNarration(api, file));if (_otherAccount) {await _restoreOtherAccountSpot();} else {unawaited(_rememberForOffline(api));- await _pullServerPosition(api);+ await serverSpot;}final len = file.existsSync() ? await file.length() : 0;final locations = await loadCachedLocations(file);@@ -1062,6 +1175,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}void _syncProgress(String cfi, double progress) {+ _readingActiveAt = DateTime.now();+ // Read along and auto scroll move the page on their own; those count.+ if (_readAlongOn || _autoScroll) _holdOpenSpot = false;+ if (_holdOpenSpot) return;+ if (_useNarration && !_readAlongOn) _noteNarrationSpot();if (_otherAccount) {unawaited(DownloadService().saveOtherAccountReadingSpot(widget.itemId, cfi, progress));return;@@ -1572,7 +1690,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}void _navigateToChapter(String href) {- _readAlongUserMoved('chapter');+ _userMoved('chapter');final escaped = href.replaceAll("'", "\\'");_epubController?.webViewController?.evaluateJavascript(source: '''@@ -1822,6 +1940,17 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_updateScroll(v);},),+ SwitchListTile(+ contentPadding: EdgeInsets.zero,+ title: Text(l.readerLogReading, style: tt.bodyMedium),+ subtitle: Text(l.readerLogReadingHint,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ value: _logReading,+ onChanged: (v) {+ _setLogReading(v);+ setSheetState(() {});+ },+ ),const SizedBox(height: 4),// Page layout — Auto shows two pages on wide screens (tablets).@@ -1861,6 +1990,29 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_updatePinTop(v);},),+ Row(children: [+ Icon(Icons.linear_scale_rounded, size: 20, color: cs.onSurfaceVariant),+ const SizedBox(width: 12),+ Text(l.readerTopBarProgress, style: tt.bodyMedium),+ ]),+ const SizedBox(height: 8),+ SizedBox(+ width: double.infinity,+ child: SegmentedButton<String>(+ segments: [+ ButtonSegment(value: 'book', label: Text(l.readerTopBarProgressBook)),+ ButtonSegment(value: 'chapter', label: Text(l.readerTopBarProgressChapter)),+ ButtonSegment(value: 'both', label: Text(l.readerTopBarProgressBoth)),+ ],+ selected: {_topBarProgress},+ showSelectedIcon: false,+ onSelectionChanged: (s) {+ setSheetState(() {});+ _updateTopBarProgress(s.first);+ },+ ),+ ),+ const SizedBox(height: 4),SwitchListTile(contentPadding: EdgeInsets.zero,title: Text(l.readerKeepAwake, style: tt.bodyMedium),@@ -1921,15 +2073,16 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// Read along, mirrored from the transcription settings so the// reader can change them without leaving the book.- if (_transcriptionOn) ...[+ if (_transcriptionOn || _useNarration) ...[Row(children: [Icon(Icons.graphic_eq_rounded, size: 20, color: cs.onSurfaceVariant),const SizedBox(width: 12),Expanded(child: Text(l.readAlong, style: tt.bodyMedium)),]),const SizedBox(height: 8),- // E-ink always follows by sentence, so the choice is hidden.- if (!PlayerSettings.einkMode) ...[+ // E-ink always follows by sentence, and an EPUB's own+ // narration is timed by the sentence, so the choice is hidden.+ if (!PlayerSettings.einkMode && !_useNarration) ...[SizedBox(width: double.infinity,child: SegmentedButton<String>(@@ -2385,6 +2538,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}void _jumpToSearchResult(EpubSearchResult result) {+ _rememberSpot(EbookSpotReason.beforeJump);+ _holdOpenSpot = false;final wc = _epubController?.webViewController;final query = _lastSearchedQuery;final occ = _resultOccByCfi[result.cfi] ?? 0;@@ -2502,6 +2657,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs{double? positionSeconds}) async {final l = AppLocalizations.of(context)!;if (_finding) return;+ _holdOpenSpot = false;setState(() => _finding = true);showProgressDialog(context, l.findInEbookSearching);@@ -2779,6 +2935,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs{bool flash = true}) async {final wc = _epubController?.webViewController;if (wc == null || href.isEmpty || excerpt.trim().isEmpty) return false;+ if (!_readAlongOn) _rememberSpot(EbookSpotReason.beforeJump);// A hit that runs across several paragraphs gives epub.js a range it// displays ten pages short of (seen with a 12s read along window). The// first paragraph on its own lands on the right page.@@ -2863,61 +3020,16 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsreturn false;}- // Find in audiobook: how much audio each probe transcribes, how many- // estimate-correct-retry rounds the main anchor gets, and the ceiling once- // the fallback candidates (player position, book percentage, neighbouring- // chapters) have taken two rounds each. A probe is roughly ten seconds.- static const double _probeWindowSeconds = 30.0;- static const int _maxProbes = 5;- static const int _maxTotalProbes = 12;- // Narration pace measured on real books: ~0.07-0.08 s per character. Used- // when no audio chapter anchors the estimate, and to reject absurd- // chapter-derived rates (3-second "chapters" exist in the wild).- static const double _fallbackSecPerChar = 0.075;- // How far a failed probe shifts the search around the original estimate,- // at minimum; a long section widens it so the probes spread across it.- static const double _scanStepSeconds = 90.0;static const double _catchUpMinGapSeconds = 300;/// Where the audiobook should be for the page at [cfi] and the range it- /// could sit in, from sync points or a uniquely named audio chapter. Nothing- /// is transcribed.+ /// could sit in. Nothing is transcribed.Future<({double est, double lo, double hi})?> _audioEstimateForPage(String cfi) async {final api = context.read<AuthProvider>().apiService;final info = await _selectionSectionInfo(cfi, '');if (info == null) return null;- final si = (info['si'] as num).toInt();- final offset = (info['offset'] as num).toDouble();- final total = (info['total'] as num).toDouble();- if (total <= 0 || offset < 0) return null;- final audio = await resolveAudioChapters(widget.itemId, api);- if (audio.duration <= 0) return null;- final spine = await _spineHrefs();- await SyncPointStore.instance.load(- widget.itemId,- audioDuration: audio.duration,- spineLength: spine.isEmpty ? null : spine.length,- );- final sync = await _syncPointCandidate(- si: si,- offset: offset,- total: total,- fallbackRate: _fallbackSecPerChar,- top: audio.duration);- if (sync != null) return (est: sync.est, lo: sync.lo, hi: sync.hi);- // A title that several audio chapters share can't place the page.- final tocTitle = _chapterForHref(info['href'] as String? ?? '');- final named = [- for (final ch in audio.chapters)- if (ch is Map<String, dynamic> &&- chapterTitlesAgree(ch['title'] as String?, tocTitle))- ch,- ];- if (named.length != 1) return null;- final a =- _chapterAnchorEstimate(named.first, offset, total, audio.duration);- return (est: a.est, lo: a.lo, hi: a.hi);+ return _audioLocator.estimate(info, api);}/// Offers to close a big gap between the page and the audiobook. Opening@@ -2925,6 +3037,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// ([audioStarting]) can offer either. Nothing moves until the toast is tapped.Future<void> _maybeOfferCatchUp({required bool audioStarting}) async {if (!mounted || !_readerActive || !_hasAudio || !_transcriptionOn) return;+ // A narrated book keeps page and audio together by itself.+ if (_useNarration) return;if (_readAlongOn || _finding) return;// These opens put a page on screen that is not where the reading stopped.if (widget.findText != null ||@@ -3003,7 +3117,21 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsi++) {await Future.delayed(const Duration(milliseconds: 500));}- if (mounted) await _maybeOfferCatchUp(audioStarting: false);+ if (!mounted) return;+ if (_hasAudio && !_useNarration && await PlayerSettings.getSyncReadingListening()) {+ // Kept in sync: listening that got ahead moves the page by itself.+ final cfi = await ReadListenSync.instance.ebookSpotForReader(widget.itemId);+ if (cfi == null || !mounted || !_holdOpenSpot || _readAlongOn) return;+ debugPrint('[SyncSpot] opened behind the audio - going to $cfi');+ _rememberSpot(EbookSpotReason.beforeSync);+ await _epubController?.display(cfi: cfi);+ if (mounted) {+ showOverlayToast(context, AppLocalizations.of(context)!.syncEbookMoved,+ icon: Icons.headphones_rounded);+ }+ return;+ }+ await _maybeOfferCatchUp(audioStarting: false);}/// Find in ebook from inside the reader, at the audiobook's position@@ -3081,6 +3209,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfinal selText = textOverride ?? _selectionText ?? '';_dismissSelection();if (cfi == null) return;+ if (_useNarration) {+ await _playNarrationFromCfi(cfi);+ return;+ }if (!TranscriptionService.instance.canTranscribeBook(widget.itemId)) {showOverlayToast(context, l.transcriptionNotDownloadedBook,icon: Icons.download_rounded);@@ -3180,547 +3312,16 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}}+ AudioLocator get _audioLocator => AudioLocator(widget.itemId, _ReaderBookText(this));+Future<double?> _locateAudioForSelection(String cfi, String selText) async {+ final api = context.read<AuthProvider>().apiService;final info = await _selectionSectionInfo(cfi, selText);if (info == null) {debugPrint('[FindAudio] selection offset not resolved');return null;}- final si = (info['si'] as num).toInt();- final offset = (info['offset'] as num).toDouble();- final total = (info['total'] as num).toDouble();- final href = info['href'] as String? ?? '';- if (total <= 0 || offset < 0) return null;-- final api = context.read<AuthProvider>().apiService;- final audio = await resolveAudioChapters(widget.itemId, api);- if (audio.chapters.isEmpty) {- debugPrint('[FindAudio] no audio chapters');- return null;- }- final spineAll = await _spineHrefs();- await SyncPointStore.instance.load(- widget.itemId,- audioDuration: audio.duration > 0 ? audio.duration : null,- spineLength: spineAll.isEmpty ? null : spineAll.length,- );- Future<double> remember(double t) async {- await SyncPointStore.instance.add(- widget.itemId,- SyncPoint(t: t, si: si, off: offset, src: 'a'),- );- return t;- }-- // Which audio chapter is this section? That anchors both the initial- // estimate and the seconds-per-character correction rate. Books whose- // chapters are plain names (alternating POV) repeat titles, so collect- // every agreeing audio chapter and pick by occurrence - the 3rd "Sydney"- // section anchors on the 3rd "Sydney" audio chapter. When the counts- // don't line up, take the one nearest the selection's position in the- // book, and keep a runner-up to probe if the first anchor turns out wrong.- final tocTitle = _chapterForHref(href);- final bookEnd = audio.duration > 0 ? audio.duration : double.infinity;- final pct = (info['pct'] as num?)?.toDouble();- final agreeing = <Map<String, dynamic>>[];- for (final ch in audio.chapters) {- final m = ch as Map<String, dynamic>;- if (chapterTitlesAgree(m['title'] as String?, tocTitle)) agreeing.add(m);- }- Map<String, dynamic>? audioCh;- Map<String, dynamic>? audioChAlt;- if (agreeing.length == 1) {- audioCh = agreeing.first;- } else if (agreeing.length > 1) {- // Occurrence counting walks the spine and counts transitions into the- // title, so a chapter split across several files still counts once and- // two same-named chapters separated by an unnamed split file count- // twice.- final hrefs = await _spineHrefs();- var occurrence = 0;- String? prev;- for (var i = 0; i <= si && i < hrefs.length; i++) {- final t = _chapterForHref(hrefs[i]);- if (t == tocTitle && prev != tocTitle) occurrence++;- prev = t;- }- final targetFrac = (pct != null && pct > 0)- ? pct- : (hrefs.isNotEmpty ? si / hrefs.length : 0.5);- double fracOf(Map<String, dynamic> m) {- final s = (m['start'] as num?)?.toDouble() ?? 0;- final e = (m['end'] as num?)?.toDouble() ?? s;- return audio.duration > 0 ? ((s + e) / 2) / audio.duration : 0;- }- final byFrac = List<Map<String, dynamic>>.from(agreeing)- ..sort((x, y) => (fracOf(x) - targetFrac)- .abs()- .compareTo((fracOf(y) - targetFrac).abs()));- final picked = (occurrence >= 1 && occurrence <= agreeing.length)- ? agreeing[occurrence - 1]- : byFrac.first;- audioCh = picked;- for (final m in byFrac) {- if (!identical(m, picked)) {- audioChAlt = m;- break;- }- }- debugPrint('[FindAudio] "$tocTitle" matches ${agreeing.length} audio '- 'chapters, occurrence #$occurrence -> '- '"${picked['title']}"@${((picked['start'] as num?)?.toDouble() ?? 0).toStringAsFixed(0)}s'- '${audioChAlt != null ? ', runner-up @${((audioChAlt['start'] as num?)?.toDouble() ?? 0).toStringAsFixed(0)}s' : ''}');- }-- double lo, hi, rate;- double est;- var anchorRate = double.nan;- if (audioCh != null) {- final a = _chapterAnchorEstimate(audioCh, offset, total, bookEnd);- lo = a.lo;- hi = a.hi;- rate = a.rate;- est = a.est;- final chStart = (audioCh['start'] as num?)?.toDouble() ?? 0;- final chEnd = (audioCh['end'] as num?)?.toDouble() ?? bookEnd;- anchorRate = (chEnd - chStart) / total;- if (anchorRate > 0.2 && chEnd.isFinite) {- // One audio chapter covering several ebook sections (a whole part- // with no chapter markers): pace through the text of the sections- // before this one under the same TOC entry, and take the rate from- // the run as a whole rather than this section alone.- final hrefs = await _spineHrefs();- var first = si;- while (first > 0 &&- first > si - 12 &&- first - 1 < hrefs.length &&- _chapterForHref(hrefs[first - 1]) == tocTitle) {- first--;- }- var last = si;- while (last + 1 < hrefs.length &&- last < si + 12 &&- (_chapterForHref(hrefs[last + 1]) ?? tocTitle) == tocTitle) {- last++;- }- final counts = await _sectionCharCounts(first, last);- if (counts.length == last - first + 1) {- double before = 0, run = 0;- for (var i = 0; i < counts.length; i++) {- final n = first + i == si ? total : counts[i];- run += n;- if (first + i < si) before += n;- }- final runRate = run > 0 ? (chEnd - chStart) / run : double.nan;- rate = (runRate >= 0.03 && runRate <= 0.2)- ? runRate- : _fallbackSecPerChar;- est = (chStart + (before + offset) * rate).clamp(chStart, chEnd);- lo = chStart;- hi = chEnd;- debugPrint('[FindAudio] anchor spans sections $first-$last '- '(${run.toInt()} chars, ${before.toInt()} before this one) '- 'rate=${rate.toStringAsFixed(4)} est=${est.toStringAsFixed(1)}');- }- }- // A marker that sits a little late (the part's interlude narrated under- // the previous chapter) puts the passage just before the anchor, where- // a scan clamped at the chapter start can never look.- lo = (lo - 900).clamp(0.0, lo);- debugPrint('[FindAudio] si=$si target@${offset.toInt()}/${total.toInt()} '- 'toc="$tocTitle" audioCh="${audioCh['title']}" '- '${lo.toStringAsFixed(0)}-${hi.isFinite ? hi.toStringAsFixed(0) : '?'}s '- 'rate=${rate.toStringAsFixed(4)} est=${est.toStringAsFixed(1)}');- } else {- // Calibre-split books often have spine sections the TOC never names- // (toc=null), or titles no audio chapter agrees with. Best fallback:- // anchor on the nearest PRECEDING section that does map to an audio- // chapter and pace forward through the intervening text. The whole-book- // percentage is the last resort - on books with songs or front matter- // it was measured ~800s off, far outside the probes' scan range.- double? anchoredEst;- var anchorStart = 0.0;- final hrefs = await _spineHrefs();- for (var a = si - 1; a >= 0 && a >= si - 8; a--) {- if (a >= hrefs.length) continue;- final aTitle = _chapterForHref(hrefs[a]);- if (aTitle == null) continue;- Map<String, dynamic>? aCh;- for (final ch in audio.chapters) {- final m = ch as Map<String, dynamic>;- if (chapterTitlesAgree(m['title'] as String?, aTitle)) {- aCh = m;- break;- }- }- if (aCh == null) continue;- final aStart = (aCh['start'] as num?)?.toDouble() ?? 0;- final counts = await _sectionCharCounts(a, si - 1);- if (counts.length == si - a) {- final between = counts.fold<double>(0, (x, y) => x + y);- anchorStart = aStart;- anchoredEst = aStart + (between + offset) * _fallbackSecPerChar;- debugPrint('[FindAudio] anchored on si=$a "${aCh['title']}" '- 'start=${aStart.toStringAsFixed(0)} '- 'charsBetween=${between.toInt()} est=${anchoredEst.toStringAsFixed(1)}');- }- break;- }-- if (anchoredEst != null) {- lo = anchorStart;- hi = bookEnd;- rate = _fallbackSecPerChar;- est = anchoredEst;- } else if (pct != null && pct > 0 && audio.duration > 0) {- lo = 0;- hi = audio.duration;- rate = _fallbackSecPerChar;- est = (pct * audio.duration).clamp(0.0, audio.duration);- debugPrint('[FindAudio] fallback estimate (toc="$tocTitle") '- 'pct=${(pct * 100).toStringAsFixed(2)}% est=${est.toStringAsFixed(1)}');- } else {- debugPrint('[FindAudio] no audio chapter matches toc="$tocTitle", '- 'no anchor, no location percentage - giving up');- return null;- }- }- if (hi.isInfinite) hi = est + 3600;-- // The section's narration length sets how far apart the probes spread:- // 90s steps suit a short section, a 40-minute chapter wants them wider so- // five probes cover it instead of one corner.- final scanStep = (total * rate / 4).clamp(_scanStepSeconds, 300.0);- final dur = audio.duration;- final probed = <double>[est];- var probesLeft = _maxTotalProbes;-- Future<double?> run(String label, double e, double from, double to,- double pace, int rounds, {double? step}) async {- if (probesLeft <= 0) return null;- final n = rounds < probesLeft ? rounds : probesLeft;- probesLeft -= n;- debugPrint('[FindAudio] $label est=${e.toStringAsFixed(1)} '- 'window ${from.toStringAsFixed(0)}-${to.toStringAsFixed(0)}s '- 'rounds=$n');- return _probeForTarget(- si: si,- offset: offset,- estimate: e,- lo: from,- hi: to,- rate: pace,- duration: dur,- maxProbes: n,- scanStepSeconds: step ?? scanStep,- );- }-- // A spot this book has already been matched at, in this section or the- // one either side, beats any chapter-title guess: it is known, and two- // of them give the real pace between. Probed first, in a window sized to- // how far the pacing had to reach.- final sync = await _syncPointCandidate(- si: si,- offset: offset,- total: total,- fallbackRate: rate,- top: dur > 0 ? dur : est + 3600);- if (sync != null) {- probed.add(sync.est);- final window = sync.hi - sync.lo;- final r = await run(sync.label, sync.est, sync.lo, sync.hi, sync.rate, 3,- step: (window / 3).clamp(45.0, _scanStepSeconds));- if (r != null) return remember(r);- }-- final t = await run('anchor', est, lo, hi, rate, _maxProbes);- if (t != null) return remember(t);-- // The anchor never matched. Fallback candidates, most likely first, two- // rounds each.- final extras =- <({String label, double est, double lo, double hi, double rate})>[];- final top = dur > 0 ? dur : double.infinity;- final pctEst = (pct != null && pct > 0 && dur > 0)- ? (pct * dur).clamp(0.0, dur)- : null;-- // Where the audio is parked right now. People mostly look up the passage- // they just heard, so a player position near the estimate or the book- // percentage is the best lead there is.- final player = AudioPlayerService();- if (player.currentItemId == widget.itemId) {- final now = player.position.inMilliseconds / 1000.0;- final near = (now - est).abs() <= 1800 ||- (pctEst != null && (now - pctEst).abs() <= 1800);- if (near) {- extras.add((- label: 'player position',- est: now,- lo: (now - 900).clamp(0.0, now),- hi: (now + 900).clamp(now, top),- rate: _fallbackSecPerChar,- ));- }- }- // The whole-book percentage disagreeing with the anchor by more than a- // few minutes usually means the anchor is the wrong chapter.- if (pctEst != null && (pctEst - est).abs() > 300) {- extras.add((- label: 'book percentage',- est: pctEst,- lo: (pctEst - 1200).clamp(0.0, pctEst),- hi: (pctEst + 1200).clamp(pctEst, dur),- rate: _fallbackSecPerChar,- ));- }- // The same title elsewhere in the book.- if (audioChAlt != null) {- final alt = _chapterAnchorEstimate(audioChAlt, offset, total, bookEnd);- extras.add((- label: 'runner-up "${audioChAlt['title']}"',- est: alt.est,- lo: alt.lo,- hi: alt.hi.isFinite ? alt.hi : alt.est + 3600,- rate: alt.rate,- ));- }- // A chapter-derived pace far from real narration says the audio and- // ebook chapters are numbered differently (twice too fast means the ebook- // chapter holds twice the text the audio chapter narrates): try the- // neighbours, nearest to the book percentage first.- if (audioCh != null &&- (anchorRate.isNaN || anchorRate < 0.05 || anchorRate > 0.12)) {- final idx = audio.chapters.indexOf(audioCh);- final neighbours = <Map<String, dynamic>>[];- if (idx > 0) neighbours.add(audio.chapters[idx - 1] as Map<String, dynamic>);- if (idx >= 0 && idx + 1 < audio.chapters.length) {- neighbours.add(audio.chapters[idx + 1] as Map<String, dynamic>);- }- final withEst = neighbours- .map((n) => (ch: n, a: _chapterAnchorEstimate(n, offset, total, bookEnd)))- .toList();- if (pctEst != null) {- withEst.sort((x, y) =>- (x.a.est - pctEst).abs().compareTo((y.a.est - pctEst).abs()));- }- for (final n in withEst) {- extras.add((- label: 'neighbour "${n.ch['title']}"',- est: n.a.est,- lo: n.a.lo,- hi: n.a.hi.isFinite ? n.a.hi : n.a.est + 3600,- rate: n.a.rate,- ));- }- }-- for (final c in extras) {- if (probed.any((p) => (p - c.est).abs() <= 120)) {- debugPrint('[FindAudio] skip ${c.label}: '- 'est=${c.est.toStringAsFixed(1)} already probed');- continue;- }- probed.add(c.est);- final r = await run(c.label, c.est, c.lo, c.hi, c.rate, 2);- if (r != null) return remember(r);- }- debugPrint('[FindAudio] no candidate matched');- return null;- }-- /// Where the sync points say [offset] in section [si] should be in the- /// audio. Same-section points first; failing that the last point of the- /// previous section or the first of the next, paced through the text in- /// between. Null when nothing recorded is close enough to help.- Future<({String label, double est, double lo, double hi, double rate})?>- _syncPointCandidate({- required int si,- required double offset,- required double total,- required double fallbackRate,- required double top,- }) async {- final pts = SyncPointStore.instance.cached(widget.itemId);- if (pts.isEmpty) return null;- final same = pts.where((p) => p.si == si).toList();- var e = SyncPointEstimator.inSection(same, offset, fallbackRate);- var label = 'sync points';- if (e == null) {- SyncPoint? prev, next;- for (final p in pts) {- if (p.si == si - 1 && (prev == null || p.off > prev.off)) prev = p;- if (p.si == si + 1 && (next == null || p.off < next.off)) next = p;- }- if (prev != null) {- final counts = await _sectionCharCounts(si - 1, si - 1);- if (counts.length == 1 && counts.first > 0) {- final chars = (counts.first - prev.off) + offset;- if (chars * fallbackRate <= 1800) {- e = SyncPointEstimator.fromPoint(prev, chars, fallbackRate);- label = 'sync point in the previous section';- }- }- }- if (e == null && next != null) {- final chars = (total - offset) + next.off;- if (chars * fallbackRate <= 1800) {- e = SyncPointEstimator.fromPoint(next, -chars, fallbackRate);- label = 'sync point in the next section';- }- }- }- if (e == null) return null;- debugPrint('[FindAudio] $label (${e.how}) from ${pts.length} points: '- 'est=${e.est.toStringAsFixed(1)} rate=${e.rate.toStringAsFixed(4)}');- return (- label: '$label (${e.how})',- est: e.est.clamp(0.0, top),- lo: e.lo.clamp(0.0, top),- hi: e.hi.clamp(0.0, top),- rate: e.rate,- );- }-- /// Initial search window and seconds-per-character pacing from an audio- /// chapter anchor.- ({double lo, double hi, double rate, double est}) _chapterAnchorEstimate(- Map<String, dynamic> ch, double offset, double total, double bookEnd) {- final chStart = (ch['start'] as num?)?.toDouble() ?? 0;- final chEnd = (ch['end'] as num?)?.toDouble() ?? bookEnd;- final chRate = (chEnd - chStart) / total;- if (chRate >= 0.03 && chRate <= 0.2) {- return (- lo: chStart,- hi: chEnd,- rate: chRate,- est: chStart + offset * chRate,- );- }- // Mis-tagged audio chapters (a 3-second "chapter" was seen in the wild)- // give an absurd rate. Trust the chapter START as an anchor, pace the- // estimate at normal narration speed, leave the end open.- return (- lo: chStart,- hi: bookEnd,- rate: _fallbackSecPerChar,- est: chStart + offset * _fallbackSecPerChar,- );- }-- /// Probe-transcribes around [estimate], correcting toward the selection at- /// [offset] each round. Returns the resolved global time, or null when- /// [maxProbes] rounds never matched the section text.- Future<double?> _probeForTarget({- required int si,- required double offset,- required double estimate,- required double lo,- required double hi,- required double rate,- required double duration,- required int maxProbes,- required double scanStepSeconds,- }) async {- var est = estimate;- final baseEst = est;- var scanStep = 0;- for (var attempt = 0; attempt < maxProbes; attempt++) {- final maxStart =- (hi - _probeWindowSeconds) > lo ? hi - _probeWindowSeconds : lo;- var probeStart = (est - _probeWindowSeconds / 2).clamp(lo, maxStart);- // A chapter start is usually a file start too. A window centred on it- // begins in the previous file and gets cut at the boundary, so it only- // ever hears the end of the last chapter. Start at the boundary instead- // so the estimate is inside what gets transcribed.- final boundary = TranscriptionService.instance- .trackBoundaryBetween(widget.itemId, probeStart, est);- if (boundary != null) {- debugPrint('[FindAudio] probe#$attempt window start '- '${probeStart.toStringAsFixed(1)} -> file boundary '- '${boundary.toStringAsFixed(1)}');- probeStart = boundary.clamp(lo, maxStart > boundary ? maxStart : boundary);- }-- List<({double start, double end, String text})> segs;- try {- segs = await TranscriptionService.instance.transcribeWindowSegments(- itemId: widget.itemId,- startSeconds: probeStart,- windowSeconds: _probeWindowSeconds,- preferAccuracy: false,- );- } on TranscriptionException catch (e) {- // A silent or music-only window transcribes to nothing, and a probe- // landing at the tail of a track file gets truncated to nearly zero- // (windows don't span file boundaries) - scan on rather than giving- // up. Setup problems can't be scanned away.- if (e.kind != TranscriptionError.empty &&- e.kind != TranscriptionError.extractFailed) {- rethrow;- }- segs = const [];- }- final probeText = segs.map((s) => s.text).join(' ').trim();- final match =- probeText.isEmpty ? null : await _locateTranscriptInSection(si, probeText);- final fine = match == null ? 0.0 : (match['fine'] as num).toDouble();-- if (match == null || fine < 0.5) {- // Bad probe (music, silence, or the estimate is off enough that the- // audio here isn't in this section): scan around the original- // estimate instead of declining on the first miss.- scanStep = scanStep >= 0 ? -(scanStep + 1) : -scanStep;- est = (baseEst + scanStep * scanStepSeconds).clamp(lo, hi);- debugPrint('[FindAudio] probe#$attempt start=${probeStart.toStringAsFixed(1)} '- 'no usable match (fine=${fine.toStringAsFixed(3)}) - '- 'scanning to ${est.toStringAsFixed(1)}');- continue;- }-- final mOff = (match['s'] as num).toDouble();- final mEnd = (match['e'] as num).toDouble();- debugPrint('[FindAudio] probe#$attempt start=${probeStart.toStringAsFixed(1)} '- 'match=${mOff.toInt()}-${mEnd.toInt()} '- 'fine=${fine.toStringAsFixed(3)} target=${offset.toInt()}');-- if (offset >= mOff && offset <= mEnd) {- // Target is inside the probed audio: walk the segments to the one- // covering the target's share of the matched text.- final frac = (mEnd - mOff) > 0 ? (offset - mOff) / (mEnd - mOff) : 0.0;- final lens = segs.map((s) => s.text.length + 1).toList();- final totalLen = lens.fold<int>(0, (a, b) => a + b);- final targetChar = frac * totalLen;- var t = probeStart + segs.last.start;- var acc = 0.0;- for (var i = 0; i < segs.length; i++) {- if (targetChar <= acc + lens[i] || i == segs.length - 1) {- final inFrac = lens[i] > 0- ? ((targetChar - acc) / lens[i]).clamp(0.0, 1.0)- : 0.0;- t = probeStart + segs[i].start + inFrac * (segs[i].end - segs[i].start);- break;- }- acc += lens[i];- }- debugPrint('[FindAudio] resolved t=${t.toStringAsFixed(1)}s');- return duration > 0 ? t.clamp(0.0, duration) : t;- }-- // Probe landed off-target: correct by the miss distance and retry. A- // correction too small to move the next probe means the rate is off -- // step most of a window toward the target instead.- var correction = (offset - (mOff + mEnd) / 2) * rate;- if (correction.abs() < 2.0) {- correction = correction.isNegative- ? -_probeWindowSeconds * 0.75- : _probeWindowSeconds * 0.75;- }- est = (est + correction).clamp(lo, hi);- }- debugPrint('[FindAudio] gave up after $maxProbes probes');- return null;+ return _audioLocator.locate(info, api);}/// Spine hrefs by spine index, for mapping neighboring sections to TOC and@@ -4048,12 +3649,359 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// pipeline for lines, so the cache is shared with the player overlay. A/// book that isn't playing yet gets loaded and started - nobody presses/// read along on a book they don't want to hear.+ Future<void> _loadNarration(ApiService api, File epub) async {+ try {+ final n = await NarrationService.instance.overlayFor(api, widget.itemId, epub: epub);+ if (n == null || !mounted) return;+ _narrationApi = api;+ _narrationLib = context.read<LibraryProvider>();+ setState(() {+ _narration = n.overlay;+ _narrationFromServer = n.fromServer;+ });+ unawaited(_narrationOpenAtAudio());+ debugPrint('[ReadAlong] ${widget.itemId} is narrated (${n.fromServer ? 'server' : 'EPUB'}): '+ '${n.overlay.clips.length} sentences');+ } catch (e) {+ debugPrint('[ReadAlong] narration check failed: $e');+ }+ }++ /// The narrated sentence named by a script answer of {href, ids}: the+ /// first id in it that the narration reads.+ OverlayClip? _narrationClipIn(Object? raw) {+ final n = _narration;+ if (n == null || raw is! String || raw.isEmpty) return null;+ final page = jsonDecode(raw) as Map<String, dynamic>;+ final href = page['href'] as String? ?? '';+ final byId = <String, OverlayClip>{};+ for (final c in n.clips) {+ final f = c.fragment;+ if (f != null && MediaOverlay.sameDoc(c.textHref, href)) byId.putIfAbsent(f, () => c);+ }+ for (final id in (page['ids'] as List<dynamic>? ?? const []).whereType<String>()) {+ final c = byId[id];+ if (c != null) return c;+ }+ return n.clipFor(href, null);+ }++ /// The first narrated sentence on the page in view.+ Future<OverlayClip?> _narrationClipOnPage() async {+ final wc = _epubController?.webViewController;+ if (_narration == null || wc == null) return null;+ try {+ await wc.evaluateJavascript(source: _narrationBootstrapSource());+ return _narrationClipIn(await wc.evaluateJavascript(+ source: 'window.__absorbMO ? __absorbMO.onPage() : ""'));+ } catch (e) {+ debugPrint('[ReadAlong] narration page lookup failed: $e');+ return null;+ }+ }++ /// The book time of the first narrated sentence on the page in view.+ Future<double?> _narrationTimeOnPage() async {+ final clip = await _narrationClipOnPage();+ final n = _narration;+ return clip == null || n == null ? null : n.startOf(clip);+ }++ /// Plays the narration from the sentence [from]: a seek when this book is+ /// already in the player, otherwise a start there. An Audiobookshelf book+ /// gets its narration onto the phone first, with how far along that is.+ /// Null when the download question took over and nothing more needs saying.+ Future<bool?> _playNarrationFrom(OverlayClip? from) async {+ final player = AudioPlayerService();+ final n = _narration;+ if (player.currentItemId == widget.itemId && player.currentEpisodeId == null) {+ if (from != null && n != null) {+ await player.seekTo(Duration(milliseconds: (n.startOf(from) * 1000).round()));+ }+ if (!player.isPlaying) await player.play(fromUi: true);+ return true;+ }+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return false;+ final cover = context.read<LibraryProvider>().getCoverUrl(widget.itemId);+ if (!api.isBookOrbit && !NarrationService.instance.hasLocalAudio(widget.itemId)) {+ await showNarrationDownloadDialog(context,+ itemId: widget.itemId,+ title: widget.title,+ coverUrl: cover,+ libraryId: context.read<LibraryProvider>().selectedLibraryId);+ return null;+ }+ final item = await api.getLibraryItem(widget.itemId);+ if (item == null || !mounted) return false;+ var ok = false;+ try {+ ok = await NarrationService.instance.play(api, item, from: from, coverUrl: cover);+ } catch (e) {+ debugPrint('[ReadAlong] starting the narration failed: $e');+ }+ return ok;+ }++ /// "Play from here" on a narrated book: the selected sentence's own timing,+ /// then read along from it.+ Future<void> _playNarrationFromCfi(String cfi) async {+ final l = AppLocalizations.of(context)!;+ final n = _narration;+ final wc = _epubController?.webViewController;+ if (n == null || wc == null) return;+ OverlayClip? clip;+ try {+ await wc.evaluateJavascript(source: _narrationBootstrapSource());+ clip = _narrationClipIn(await wc.evaluateJavascript(+ source: 'window.__absorbMO ? __absorbMO.idsAt(${jsonEncode(cfi)}) : ""'));+ } catch (e) {+ debugPrint('[ReadAlong] selection lookup failed: $e');+ }+ if (!mounted) return;+ if (clip == null) {+ showOverlayToast(context, l.findInAudiobookNotFound, icon: Icons.search_off_rounded);+ return;+ }+ debugPrint('[ReadAlong] play from the selection: ${clip.textHref}#${clip.fragment} '+ 'at ${n.startOf(clip).toStringAsFixed(1)}s');+ final ok = await _playNarrationFrom(clip);+ if (ok == null || !mounted) return;+ if (!ok) {+ showOverlayToast(context, l.narrationNone, icon: Icons.headphones_rounded);+ return;+ }+ if (!_readAlongOn) await _startNarrationReadAlong();+ }++ bool _narrationOpenedAtAudio = false;++ /// Opening the reader on a narrated book: go to the sentence the audio is+ /// on when the book is in the player, or when the listening has got+ /// further than the reading. Reading follows listening, as listening+ /// follows reading ahead.+ Future<void> _narrationOpenAtAudio() async {+ final n = _narration;+ if (_narrationOpenedAtAudio || n == null || !_useNarration || !_didLoadRescue) return;+ if (widget.openAtCfi != null || widget.findText != null || widget.startReadAlong) return;+ _narrationOpenedAtAudio = true;+ final player = AudioPlayerService();+ double? at;+ if (player.currentItemId == widget.itemId && player.currentEpisodeId == null) {+ at = player.position.inMilliseconds / 1000.0;+ } else {+ final local = await ProgressSyncService().getLocal(widget.itemId);+ final saved = _narrationLib?.getProgressData(widget.itemId);+ final localAt = (local?['timestamp'] as num?)?.toInt() ?? 0;+ final savedAt = (saved?['lastUpdate'] as num?)?.toInt() ?? 0;+ final newer = local == null+ ? saved+ : saved == null+ ? local+ : (localAt >= savedAt ? local : saved);+ final heard = (newer?['currentTime'] as num?)?.toDouble() ?? 0;+ if (heard <= 0) return;+ // Measured in narration time against the page's first sentence, so a+ // long front matter can't make the audio look ahead when it isn't.+ final readAt = await _narrationTimeOnPage();+ if (readAt != null) {+ if (heard <= readAt + 1) return;+ } else {+ final read = (saved?['ebookProgress'] as num?)?.toDouble() ?? _progress;+ if (n.duration <= 0 || heard / n.duration <= read + 0.005) return;+ }+ at = heard;+ }+ if (!mounted) return;+ final clip = n.clipAt(at);+ final id = clip?.fragment;+ final wc = _epubController?.webViewController;+ if (clip == null || id == null || wc == null) return;+ debugPrint('[ReadAlong] opened while the narration is at ${clip.textHref}#$id - going there');+ _rememberSpot(EbookSpotReason.beforeSync);+ await wc.evaluateJavascript(source: _narrationBootstrapSource());+ await wc.evaluateJavascript(+ source: 'window.__absorbMO && __absorbMO.go(${jsonEncode(clip.textHref)}, ${jsonEncode(id)})');+ }++ // Where reading has got to in narration time, noted as pages turn, so+ // leaving by any route can hand it to the narration without the page.+ double? _narrationReadAt;+ Timer? _narrationSpotTimer;+ ApiService? _narrationApi;+ LibraryProvider? _narrationLib;++ void _noteNarrationSpot() {+ _narrationSpotTimer?.cancel();+ _narrationSpotTimer = Timer(const Duration(milliseconds: 1200), () async {+ if (!mounted || _readAlongOn) return;+ final t = await _narrationTimeOnPage();+ if (t != null) _narrationReadAt = t;+ });+ }++ /// Reading ahead of the narration, then leaving the reader: the narration+ /// moves to the page you reached, so play picks up where you were reading.+ /// Uses nothing from the page or the widget tree, so it can run on dispose.+ Future<void> _narrationCarryReadingSpot() async {+ final n = _narration;+ final t = _narrationReadAt;+ if (n == null || t == null || !_useNarration || _readAlongOn) return;+ _narrationReadAt = null;+ final player = AudioPlayerService();+ final inPlayer = player.currentItemId == widget.itemId && player.currentEpisodeId == null;+ if (inPlayer && player.isPlaying) return;+ final local = await ProgressSyncService().getLocal(widget.itemId);+ final heard = inPlayer+ ? player.position.inMilliseconds / 1000.0+ : (local?['currentTime'] as num?)?.toDouble() ??+ (_narrationLib?.getProgressData(widget.itemId)?['currentTime'] as num?)?.toDouble() ??+ 0;+ if (t <= heard + 20) return;+ debugPrint('[ReadAlong] read ahead of the narration '+ '(${heard.toStringAsFixed(0)}s -> ${t.toStringAsFixed(0)}s) - moving it to the page');+ if (inPlayer) {+ await player.seekTo(Duration(milliseconds: (t * 1000).round()));+ return;+ }+ final duration = n.duration;+ await ProgressSyncService().saveLocal(+ itemId: widget.itemId,+ currentTime: t,+ duration: duration,+ speed: (local?['speed'] as num?)?.toDouble() ?? 1.0,+ );+ try {+ await _narrationApi?.updateProgress(widget.itemId, currentTime: t, duration: duration);+ } catch (e) {+ debugPrint('[ReadAlong] narration spot not sent: $e');+ }+ }++ String _narrationBootstrapSource() =>+ narrationBootstrap(LyricsService.instance.readAlongColor, eink: PlayerSettings.einkMode);++ /// Read along from the narration's own timings. A book that isn't playing+ /// starts at the first sentence on the page in view.+ Future<void> _startNarrationReadAlong({bool fromResume = false}) async {+ final l = AppLocalizations.of(context)!;+ final player = AudioPlayerService();+ final playingThis =+ player.currentItemId == widget.itemId && player.currentEpisodeId == null;+ if (!playingThis) {+ if (fromResume) return;+ final ok = await _playNarrationFrom(await _narrationClipOnPage());+ if (ok == null || !mounted) return;+ if (!ok) {+ showOverlayToast(context, l.readAlongNeedsPlaying, icon: Icons.headphones_rounded);+ return;+ }+ }+ if (_autoScroll) {+ await _epubController?.autoScrollStop();+ if (mounted) {+ setState(() {+ _autoScroll = false;+ _autoScrollPaused = false;+ });+ }+ }+ await _epubController?.webViewController+ ?.evaluateJavascript(source: _narrationBootstrapSource());+ _narrationWentTo = null;+ _readAlongColor = LyricsService.instance.readAlongColor;+ if (mounted) {+ setState(() {+ _readAlongOn = true;+ _narrationReadAlong = true;+ _readAlongBrowsing = false;+ });+ }+ ScreenWake.hold('reader', true);+ _readAlongTimer?.cancel();+ _readAlongTimer = Timer.periodic(+ const Duration(milliseconds: 150), (_) => _narrationTick());+ debugPrint('[ReadAlong] following the narration for ${widget.itemId}');+ }++ Future<void> _narrationTick({bool force = false}) async {+ final n = _narration;+ if (!mounted || !_readAlongOn || !_narrationReadAlong || n == null) return;+ if (_narrationTickBusy) return;+ final player = AudioPlayerService();+ if (player.currentItemId != widget.itemId) {+ _stopReadAlong();+ return;+ }+ final clip = n.clipAt(player.position.inMilliseconds / 1000.0);+ final id = clip?.fragment;+ if (clip == null || id == null) return;+ final wc = _epubController?.webViewController;+ if (wc == null) return;+ _narrationTickBusy = true;+ try {+ if (LyricsService.instance.readAlongColor != _readAlongColor) {+ _readAlongColor = LyricsService.instance.readAlongColor;+ await wc.evaluateJavascript(+ source: 'window.__absorbMO && __absorbMO.setColor("${cssHex(_readAlongColor)}")');+ }+ var where = await wc.evaluateJavascript(+ source: 'window.__absorbMO ? __absorbMO.show(${jsonEncode(clip.textHref)}, ${jsonEncode(id)}) : ""');+ if (where == '' || where == null) {+ // A layout change remounts the page and its script goes with it.+ await wc.evaluateJavascript(source: _narrationBootstrapSource());+ where = await wc.evaluateJavascript(+ source: 'window.__absorbMO ? __absorbMO.show(${jsonEncode(clip.textHref)}, ${jsonEncode(id)}) : ""');+ }+ if (where is String && where != _narrationWhere && mounted) {+ setState(() => _narrationWhere = where as String);+ }+ if (_readAlongBrowsing) {+ // The narration reached the page being browsed: follow it again.+ if (_narrationOnScreen && DateTime.now().difference(_readAlongBrowseAt) > const Duration(seconds: 2)) {+ if (mounted) setState(() => _readAlongBrowsing = false);+ }+ return;+ }+ final now = DateTime.now();+ if (!force && now.difference(_narrationTurnAt) < const Duration(milliseconds: 700)) return;+ if (_scroll && (where == 'after' || where == 'before' || where == 'low')) {+ _narrationTurnAt = now;+ await wc.evaluateJavascript(+ source: 'window.__absorbMO && __absorbMO.reveal(${jsonEncode(clip.textHref)}, ${jsonEncode(id)})');+ } else if (where == 'after' || where == 'before') {+ _narrationTurnAt = now;+ _readAlongTurnPending = now;+ if (where == 'after') {+ _epubController?.next();+ } else {+ _epubController?.prev();+ }+ } else if (where == 'missing' && !identical(_narrationWentTo, clip)) {+ _narrationWentTo = clip;+ _narrationTurnAt = now;+ _readAlongTurnPending = now;+ debugPrint('[ReadAlong] narration moved to ${clip.textHref}#$id');+ await wc.evaluateJavascript(+ source: 'window.__absorbMO && __absorbMO.go(${jsonEncode(clip.textHref)}, ${jsonEncode(id)})');+ }+ } catch (e) {+ debugPrint('[ReadAlong] narration tick failed: $e');+ } finally {+ _narrationTickBusy = false;+ }+ }+Future<void> _toggleReadAlong() async {final l = AppLocalizations.of(context)!;if (_readAlongOn) {_stopReadAlong();return;}+ if (_useNarration) {+ await _startNarrationReadAlong();+ return;+ }final player = AudioPlayerService();if (player.currentItemId != widget.itemId ||player.currentEpisodeId != null) {@@ -4094,6 +4042,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsplayer.currentItemId == widget.itemId &&player.currentEpisodeId == null;if (!stillWanted()) return;+ if (_useNarration) {+ debugPrint('[ReadAlong] back in the foreground - following the narration again');+ await _startNarrationReadAlong(fromResume: true);+ return;+ }if (!await PlayerSettings.getTranscriptionEnabled()) return;if (!stillWanted() ||!TranscriptionService.instance.canTranscribeBook(widget.itemId)) {@@ -4489,6 +4442,15 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_readAlongTimer?.cancel();_readAlongTimer = null;_flushEbookPush();+ if (_narrationReadAlong) {+ _narrationReadAlong = false;+ _narrationWentTo = null;+ try {+ _epubController?.webViewController+ ?.evaluateJavascript(source: 'window.__absorbMO && __absorbMO.clear()')+ .catchError((_) => null);+ } catch (_) {}+ }// Runs from dispose() too, when the WebView may already be on its way out.try {_epubController?.webViewController@@ -4758,6 +4720,20 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}}+ /// A page turn, jump or scroll the reader asked for. From here on the+ /// place is the reader's own and gets saved.+ void _userMoved(String how) {+ _readingActiveAt = DateTime.now();+ if (const {'chapter', 'highlight', 'bookmark', 'history'}.contains(how)) {+ _rememberSpot(EbookSpotReason.beforeJump);+ }+ if (_holdOpenSpot) {+ _holdOpenSpot = false;+ debugPrint('[EbookReader] moved ($how) - saving the place from here item=${widget.itemId}');+ }+ _readAlongUserMoved(how);+ }+void _readAlongUserMoved(String how) {if (!_readAlongOn) return;_readAlongBrowseAt = DateTime.now();@@ -4791,6 +4767,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_readAlongBrowsing = false;_showControls = false;});+ if (_narrationReadAlong) {+ _narrationWentTo = null;+ await _narrationTick(force: true);+ return;+ }_readAlongAllowBack = true;_readAlongTurnPending = null;_readAlongStepped = false;@@ -5159,6 +5140,149 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}}+ void _rememberSpot(EbookSpotReason reason) {+ final cfi = _currentCfi;+ if (cfi == null || cfi.isEmpty) return;+ unawaited(EbookHistory.instance.record(widget.itemId,+ cfi: cfi, reason: reason, progress: _progress, chapter: _currentChapterTitle));+ }++ Widget _historyTab(BuildContext ctx, ScrollController scrollController) {+ final l = AppLocalizations.of(ctx)!;+ final cs = Theme.of(ctx).colorScheme;+ return FutureBuilder<List<EbookSpot>>(+ future: EbookHistory.instance.spots(widget.itemId),+ builder: (ctx, snap) {+ if (snap.connectionState != ConnectionState.done) {+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));+ }+ final spots = snap.data ?? const <EbookSpot>[];+ if (spots.isEmpty) {+ return Center(+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: Text(l.readerHistoryEmpty,+ textAlign: TextAlign.center, style: TextStyle(color: cs.onSurfaceVariant)),+ ),+ );+ }+ return ListView.builder(+ controller: scrollController,+ padding: const EdgeInsets.symmetric(vertical: 8),+ itemCount: spots.length,+ itemBuilder: (ctx, i) {+ final s = spots[i];+ final pct = s.progress == null ? null : '${(s.progress! * 100).round()}%';+ final why = switch (s.reason) {+ EbookSpotReason.closed => l.readerHistoryClosed,+ EbookSpotReason.beforeJump => l.readerHistoryBeforeJump,+ EbookSpotReason.beforeSync => l.readerHistoryBeforeSync,+ };+ return ListTile(+ dense: true,+ leading: Icon(+ switch (s.reason) {+ EbookSpotReason.closed => Icons.menu_book_rounded,+ EbookSpotReason.beforeJump => Icons.undo_rounded,+ EbookSpotReason.beforeSync => Icons.headphones_rounded,+ },+ color: cs.onSurfaceVariant,+ ),+ title: Text(s.chapter ?? pct ?? '', maxLines: 1, overflow: TextOverflow.ellipsis),+ subtitle: Text('$why · ${dateLabel(s.at, l)} ${timeOfDay(s.at, l)}',+ style: TextStyle(color: cs.onSurfaceVariant)),+ trailing: s.chapter != null && pct != null+ ? Text(pct, style: TextStyle(color: cs.onSurfaceVariant))+ : null,+ onTap: () {+ Navigator.pop(ctx);+ _userMoved('history');+ _epubController?.display(cfi: s.cfi);+ },+ );+ },+ );+ },+ );+ }++ Future<void> _setLogReading(bool on) async {+ debugPrint('[ReadingTime] ${widget.itemId}: counting reading time ${on ? 'on' : 'off'}');+ setState(() => _logReading = on);+ await ScopedPrefs.setBool(_kLogReading, on);+ if (on) {+ _readingActiveAt = DateTime.now();+ _startReadingClock();+ } else {+ _readingTimer?.cancel();+ _readingTimer = null;+ await _sendReadingTime(closing: true);+ }+ }++ void _startReadingClock() {+ _readingTimer ??= Timer.periodic(const Duration(seconds: 15), (_) => _readingTick());+ }++ void _readingTick() {+ if (!_logReading || !_readerActive) return;+ // This book's audio playing at either end of the tick means the time+ // is listening (read along included), counted by that session alone.+ final player = AudioPlayerService();+ final listening = player.isPlaying && player.currentItemId == widget.itemId;+ final listened = _readingAudioWasOn;+ _readingAudioWasOn = listening;+ if (listening || listened) return;+ if (!_autoScroll && DateTime.now().difference(_readingActiveAt) > const Duration(minutes: 5)) return;+ _readingSessionId ??= LocalSessionService().newSessionId();+ _readingStartedAt ??= DateTime.now().subtract(const Duration(seconds: 15));+ _readingStartPct ??= _progress;+ _readingSeconds += 15;+ if (_readingSeconds - _readingSent >= 60) unawaited(_sendReadingTime());+ }++ /// Sends the reading time so far. A new day starts a new session, as+ /// listening does.+ Future<void> _sendReadingTime({bool closing = false}) async {+ final id = _readingSessionId, started = _readingStartedAt, api = _readingApi;+ if (id == null || started == null || api == null) return;+ final seconds = _readingSeconds;+ if (seconds <= _readingSent && !closing) return;+ final local = await ProgressSyncService().getLocal(widget.itemId);+ final audioAt = (local?['currentTime'] as num?)?.toDouble() ?? 0;+ var ok = false;+ if (seconds >= 10) {+ ok = await api.logReadingTime(widget.itemId,+ sessionId: id,+ startedAt: started,+ seconds: seconds,+ audioAt: audioAt,+ audioDuration: _audioTotal,+ title: widget.title,+ ebookStart: _readingStartPct,+ ebookEnd: _progress);+ if (ok) _readingSent = seconds;+ debugPrint('[ReadingTime] ${widget.itemId}: ${seconds}s ${ok ? 'logged' : 'not sent'}');+ if (!ok && closing && !api.isBookOrbit) {+ await LocalSessionService().queue(ApiService.readingSession(widget.itemId,+ sessionId: id,+ startedAt: started,+ seconds: seconds,+ audioAt: audioAt,+ audioDuration: _audioTotal,+ title: widget.title));+ }+ }+ if (closing || DateUtils.dateOnly(started) != DateUtils.dateOnly(DateTime.now())) {+ debugPrint('[ReadingTime] ${widget.itemId}: session $id ended at ${seconds}s');+ _readingSessionId = null;+ _readingStartedAt = null;+ _readingStartPct = null;+ _readingSeconds = 0;+ _readingSent = 0;+ }+ }+void _showAnnotationsSheet() {final cs = Theme.of(context).colorScheme;final tt = Theme.of(context).textTheme;@@ -5178,7 +5302,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsmaxChildSize: 0.9,minChildSize: 0.3,builder: (ctx, scrollController) => DefaultTabController(- length: 2,+ length: 3,child: Column(children: [Padding(@@ -5198,6 +5322,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObstabs: [Tab(text: AppLocalizations.of(ctx)!.readerHighlights(highlights.length)),Tab(text: AppLocalizations.of(ctx)!.readerBookmarks(bookmarks.length)),+ Tab(text: AppLocalizations.of(ctx)!.readerHistory),],labelColor: cs.primary,unselectedLabelColor: cs.onSurfaceVariant,@@ -5256,7 +5381,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsdense: true,onTap: () {Navigator.pop(ctx);- _readAlongUserMoved('highlight');+ _userMoved('highlight');_epubController?.display(cfi: pointCfi(h.cfi));},onLongPress: () => _addNoteToAnnotation(h),@@ -5305,7 +5430,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsdense: true,onTap: () {Navigator.pop(ctx);- _readAlongUserMoved('bookmark');+ _userMoved('bookmark');_epubController?.display(cfi: pointCfi(bm.cfi));},onLongPress: () => _addNoteToAnnotation(bm),@@ -5313,6 +5438,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);},),+ _historyTab(ctx, scrollController),],),),@@ -5348,6 +5474,24 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsSize? _viewerPaddingSize;Widget _buildTopBarContent(Color fg, Color fgDim, Color accent) {+ final bookProgress = _progress.clamp(0.0, 1.0);+ final chapterProgress = _chapterPageTotal > 0+ ? (_chapterPage / _chapterPageTotal).clamp(0.0, 1.0)+ : 0.0;+ final both = _topBarProgress == 'both';+ final chapterOnly = _topBarProgress == 'chapter';+ Widget bar(double value, double height) => ClipRRect(+ borderRadius: BorderRadius.circular(2),+ child: LinearProgressIndicator(+ value: value,+ minHeight: height,+ backgroundColor: fg.withValues(alpha: 0.1),+ valueColor: AlwaysStoppedAnimation(accent),+ ),+ );+ final percent = chapterOnly+ ? (_chapterPageTotal > 0 ? '${(chapterProgress * 100).round()}%' : '')+ : '${(bookProgress * 100).toStringAsFixed(1)}%';return Padding(padding: const EdgeInsets.fromLTRB(20, 8, 20, 12),child: Column(@@ -5364,16 +5508,15 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfontSize: 16,),),- const SizedBox(height: 8),- ClipRRect(- borderRadius: BorderRadius.circular(2),- child: LinearProgressIndicator(- value: _progress.clamp(0.0, 1.0),- minHeight: 3,- backgroundColor: fg.withValues(alpha: 0.1),- valueColor: AlwaysStoppedAnimation(accent),- ),- ),+ // Both bars fit in the height one bar takes, so a pinned page+ // doesn't change size and re-paginate when this is switched.+ SizedBox(height: both ? 4 : 8),+ if (both) ...[+ bar(chapterProgress, 3),+ const SizedBox(height: 2),+ bar(bookProgress, 2),+ ] else+ bar(chapterOnly ? chapterProgress : bookProgress, 3),const SizedBox(height: 4),Row(children: [@@ -5395,7 +5538,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs),),Text(- '${(_progress * 100).toStringAsFixed(1)}%',+ percent,style: TextStyle(color: fgDim, fontSize: 11),),],@@ -5486,6 +5629,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}void _handleClose() {+ unawaited(_narrationCarryReadingSpot());Navigator.pop(context);}@@ -6302,6 +6446,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (mounted && !_readAlongOn) _toggleReadAlong();});}+ unawaited(_narrationOpenAtAudio());if (!_didScheduleCatchUp) {_didScheduleCatchUp = true;// Past the load rescue and settle re-displays.@@ -6372,7 +6517,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// A swipe turns the page on Android, and a drag scrolls it// in scroll mode.if (_scroll ? dy > 0.05 : dx > dy) {- _readAlongUserMoved(_scroll ? 'scroll' : 'swipe');+ _userMoved(_scroll ? 'scroll' : 'swipe');+ // The page can relocate before the finger lifts, while+ // the place was still held, so save where it came to.+ final cfi = _currentCfi;+ if (cfi != null) _syncProgress(cfi, _progress);}return;}@@ -6442,9 +6591,14 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsPadding(padding: const EdgeInsets.only(bottom: 6),child: Center(- child: _readAlongBrowsing+ // Browsing with the lit sentence still in+ // view leaves nothing to go back to.+ child: _readAlongBrowsing && !(_narrationReadAlong && _narrationOnScreen)? _backToNarrationButton(accent)- : _readAlongSyncPill(fg),+ : _narrationReadAlong+ // The book's own timings need no sync tuning.+ ? const SizedBox.shrink()+ : _readAlongSyncPill(fg),),),Padding(@@ -6479,7 +6633,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsonPressed: _openSearchScreen,),),- if (_transcriptionOn)+ if (_transcriptionOn || _useNarration)Expanded(child: IconButton(icon: Icon(Icons.graphic_eq_rounded,@@ -6579,11 +6733,16 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObstooltip: AppLocalizations.of(context)!.readerTooltipDefine,visualDensity: VisualDensity.compact,),- if (_transcriptionOn)+ if (_transcriptionOn || _useNarration)IconButton(- icon: Icon(Icons.headphones_rounded, size: 20, color: cs.onSurfaceVariant),+ icon: Icon(+ _useNarration ? Icons.play_arrow_rounded : Icons.headphones_rounded,+ size: 20,+ color: cs.onSurfaceVariant),onPressed: _findInAudiobookFromSelection,- tooltip: AppLocalizations.of(context)!.findInAudiobook,+ tooltip: _useNarration+ ? AppLocalizations.of(context)!.narrationPlayFromHere+ : AppLocalizations.of(context)!.findInAudiobook,visualDensity: VisualDensity.compact,),_divider(cs),@@ -6854,3 +7013,23 @@ class _HighlightColorButton extends StatelessWidget {);}}++/// The reader's open pages as Find in audiobook's view of the book.+class _ReaderBookText implements BookTextSource {+ _ReaderBookText(this._reader);++ final EbookReaderViewState _reader;++ @override+ Future<List<String>> spineHrefs() => _reader._spineHrefs();++ @override+ String? chapterForHref(String href) => _reader._chapterForHref(href);++ @override+ Future<List<double>> sectionCharCounts(int from, int to) => _reader._sectionCharCounts(from, to);++ @override+ Future<Map<String, dynamic>?> locateTranscriptInSection(int si, String transcript) =>+ _reader._locateTranscriptInSection(si, transcript);+}diff --git a/lib/widgets/ebook_router.dart b/lib/widgets/ebook_router.dartindex 36fa4402..b661e741 100644--- a/lib/widgets/ebook_router.dart+++ b/lib/widgets/ebook_router.dart@@ -6,6 +6,7 @@ import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../services/ebook_cache.dart';import '../services/image_epub.dart';+import '../services/narration_service.dart';import '../services/server_backend.dart';import 'comic_reader_view.dart';import 'ebook_reader_view.dart';@@ -111,7 +112,8 @@ class _EpubGateState extends State<_EpubGate> {try {final api = context.read<AuthProvider>().apiService;if (api != null) {- final file = await fetchEbookToCache(api, widget.itemId, widget.ebookFile, widget.title);+ final file = await NarrationService.instance+ .readerFile(api, widget.itemId, widget.ebookFile, widget.title);final pages = await imageEpubPageCount(file);if (pages > 0) {debugPrint('[EbookRouter] ${widget.itemId} is $pages page pictures - opening as a comic');diff --git a/lib/widgets/listening_session_card.dart b/lib/widgets/listening_session_card.dartindex fcd1159c..2f95639e 100644--- a/lib/widgets/listening_session_card.dart+++ b/lib/widgets/listening_session_card.dart@@ -1,6 +1,7 @@import 'package:flutter/material.dart';import '../l10n/app_localizations.dart';+import '../services/api_service.dart';import 'absorb_wave_icon.dart';class ListeningSessionCard extends StatelessWidget {@@ -47,6 +48,7 @@ class ListeningSessionCard extends StatelessWidget {deviceInfo['deviceName'] as String? ??'';final isAbsorb = clientName.toLowerCase().contains('absorb');+ final isReading = session['mediaPlayer'] == ApiService.readingMediaPlayer;return Padding(padding: const EdgeInsets.only(bottom: 6),@@ -73,7 +75,13 @@ class ListeningSessionCard extends StatelessWidget {borderRadius: BorderRadius.circular(9),),child: Center(- child: isAbsorb+ child: isReading+ ? Icon(+ Icons.menu_book_rounded,+ size: 18,+ color: Colors.tealAccent.withValues(alpha: 0.9),+ )+ : isAbsorb? AbsorbWaveIcon(size: 18,color: Colors.tealAccent.withValues(alpha: 0.9),diff --git a/lib/widgets/narration_download_dialog.dart b/lib/widgets/narration_download_dialog.dartnew file mode 100644index 00000000..f51e1506--- /dev/null+++ b/lib/widgets/narration_download_dialog.dart@@ -0,0 +1,65 @@+import 'package:flutter/material.dart';+import 'package:provider/provider.dart';++import '../l10n/app_localizations.dart';+import '../providers/auth_provider.dart';+import '../services/download_service.dart';+import 'card_buttons.dart' show showErrorToast;+import 'overlay_toast.dart';++/// An Audiobookshelf EPUB that reads itself aloud plays from the phone, so+/// its narration is downloaded first. Says so ([heading] and [message] for+/// a book other than the one tapped), and starts the download on the user's+/// word. True when the download started.+Future<bool> showNarrationDownloadDialog(+ BuildContext context, {+ required String itemId,+ required String title,+ String? author,+ String? coverUrl,+ String? libraryId,+ String? heading,+ String? message,+}) async {+ final l = AppLocalizations.of(context)!;+ debugPrint('[Narration] $itemId is not downloaded - asking to download it');+ final go = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ icon: const Icon(Icons.headphones_rounded),+ title: Text(heading ?? l.narrationDownloadTitle),+ content: Text(message ?? l.narrationDownloadBody),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.download)),+ ],+ ),+ );+ if (go != true || !context.mounted) {+ debugPrint('[Narration] $itemId: download declined');+ return false;+ }+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return false;+ final error = await DownloadService().downloadItem(+ api: api,+ itemId: itemId,+ title: title,+ author: author,+ coverUrl: coverUrl,+ libraryId: libraryId,+ );+ if (!context.mounted) return error == null;+ if (error != null) {+ debugPrint('[Narration] $itemId: download did not start: $error');+ showErrorToast(context, error);+ return false;+ }+ if (!DownloadService().isDownloading(itemId)) {+ debugPrint('[Narration] $itemId: download did not start (queued, or already on the phone)');+ return false;+ }+ debugPrint('[Narration] $itemId: download started from the question');+ showOverlayToast(context, l.narrationDownloadStarted, icon: Icons.download_rounded);+ return true;+}diff --git a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.jsindex 56a815cc..9767b4ef 100644--- a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js+++ b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js@@ -175,6 +175,20 @@ function loadBook(data, cfi, initialXPath, manager, flow, spread, snap, allowScrlastTheme.fontSize = fontSize;rendition = book.renderTo("viewer", lastRenderOpts);+ // Absorb patch: scroll mode only moves up and down, down to each chapter's+ // own page, so a drag that drifts sideways can't nudge the text aside.+ var scrolledNow = String(flow || "").indexOf("scrolled") === 0;+ document.body.classList.toggle("absorb-scrolled", scrolledNow);+ if (scrolledNow) {+ rendition.hooks.content.register(function (contents) {+ try {+ var st = contents.document.createElement("style");+ st.textContent = "html, body { overflow-x: hidden !important; touch-action: pan-y; }";+ contents.document.head.appendChild(st);+ } catch (e) {}+ });+ }+// Apply initial themeupdateTheme(backgroundColor, foregroundColor, customCss);diff --git a/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html b/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.htmlindex 3bc078ee..5f76e50f 100644--- a/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html+++ b/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html@@ -38,6 +38,14 @@overflow-anchor: none;}+ /* Absorb patch: scroll mode only moves up and down. A drag that drifted+ sideways nudged the text to the side. */+ body.absorb-scrolled,+ body.absorb-scrolled .epub-container {+ overflow-x: hidden !important;+ touch-action: pan-y;+ }+#viewerNext {display: none;position: fixed;diff --git a/pubspec.lock b/pubspec.lockindex ef439145..5698c10c 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -618,7 +618,7 @@ packages:source: hostedversion: "2.0.2"html:- dependency: transitive+ dependency: "direct main"description:name: htmlsha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602"@@ -1757,7 +1757,7 @@ packages:source: hostedversion: "1.1.0"xml:- dependency: transitive+ dependency: "direct main"description:name: xmlsha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"diff --git a/pubspec.yaml b/pubspec.yamlindex 837fc04e..1670191f 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -43,6 +43,8 @@ dependencies:# Reading EPUB text without a WebView (transcript ebook cross-reference).archive: ^4.0.9+ html: ^0.15.4+ xml: ^6.5.0# CarPlay - vendored copy of 1.2.11 with a patched image loader (downsampled +# cached list thumbnails) so large browse lists don't run CarPlay out of memory.