Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Offline/LibrarySession.swift3// Description: Everything belonging to one signed-in account, wired together; picks each track's audio source.4import Foundation5import AudioToolbox67public enum SourceKind: String, Sendable { case local, cache, stream, file }89public struct ResolvedSource: Sendable {10 public var source: ByteSource11 public var typeHint: AudioFileTypeID12 public var kind: SourceKind13 public var gainDB: Float14 /// True when the cluster's AAC rendition is played instead of the original (codec not decodable on the Mac).15 public var isRendition: Bool16}1718public enum PlaybackError: Error, Sendable, Equatable {19 case notAvailableOffline20 case noFile21 case libraryFolderMissing22}2324/// Everything that belongs to one signed-in account on this Mac, wired together: the local database, the files on25/// disk, the API client, downloads and synchronisation. Opening it needs no network.26public final class LibrarySession: Sendable {27 public let account: Account28 public let api: APIClient29 public let store: LibraryStore30 public let storage: StorageManager31 public let artwork: ArtworkStore32 public let downloads: DownloadManager33 public let sync: SyncEngine34 public let auth: AuthService35 public var connectivity: Connectivity { api.connectivity }3637 public static func accountKey(server: URL, userID: String) -> String {38 PathGuard.safeComponent("\(server.host ?? "server")\(server.port.map { "-\($0)" } ?? "")_\(userID)", fallback: "account")39 }40 public static func defaultLibraryRoot(for account: Account) -> URL {41 let music = FileManager.default.urls(for: .musicDirectory, in: .userDomainMask).first ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Music")42 let who = PathGuard.safeComponent(account.displayName.isEmpty ? account.email : account.displayName, fallback: "Bibliothèque", maxLength: 60)43 return music.appendingPathComponent("SP Music", isDirectory: true).appendingPathComponent(who, isDirectory: true)44 }4546 /// `dataRoot` is the app's Application Support folder; `libraryRoot` overrides the remembered library folder (tests).47 public init(api: APIClient, account: Account, dataRoot: URL, libraryRoot: URL? = nil, maxConcurrentDownloads: Int = 3) async throws {48 self.api = api; self.account = account49 let key = Self.accountKey(server: api.baseURL, userID: account.id)50 let dataDir = dataRoot.appendingPathComponent("Accounts", isDirectory: true).appendingPathComponent(key, isDirectory: true)51 try FileManager.default.createDirectory(at: dataDir, withIntermediateDirectories: true)52 let store = try LibraryStore(path: dataDir.appendingPathComponent("library.sqlite").path)53 self.store = store54 let remembered = await store.value("library.root").map { URL(fileURLWithPath: $0, isDirectory: true) }55 let root = libraryRoot ?? remembered ?? Self.defaultLibraryRoot(for: account)56 storage = StorageManager(dataDirectory: dataDir, libraryRoot: root, accountKey: key)57 // A remembered folder that is absent (external disk unplugged) is left alone; a new one is created and marked.58 if remembered == nil || libraryRoot != nil || FileManager.default.fileExists(atPath: root.path) { try? storage.prepareRoot() }59 await store.setValue("library.root", root.path)60 artwork = ArtworkStore(api: api, directory: storage.artworkDirectory)61 downloads = DownloadManager(store: store, api: api, storage: storage, artwork: artwork, maxConcurrent: maxConcurrentDownloads)62 sync = SyncEngine(store: store, api: api, downloads: downloads, artwork: artwork)63 auth = AuthService(api: api)64 }6566 /// Whether this track can play right now without the cluster.67 public func isAvailableOffline(_ t: Track) -> Bool {68 if let u = t.externalFileURL { return FileManager.default.fileExists(atPath: u.path) }69 if storage.localFile(for: t) != nil { return true }70 if let a = t.assetID, StreamCache.completeFile(storage.streamCacheDirectory, trackID: t.id, assetID: a) != nil { return true }71 return false72 }7374 /// Picks where a track's audio comes from: its downloaded file first, then a complete cached copy, then the cluster.75 /// A downloaded track is resolved without any network request.76 public func resolve(_ t: Track, normalize: Bool) async throws -> ResolvedSource {77 var gain: Float = 078 if normalize, let a = t.assetID, let l = await store.loudness(assetID: a) { gain = LoudnessAnalyzer.gainDB(lufs: l.lufs, peak: l.peak) }79 if let url = t.externalFileURL {80 return ResolvedSource(source: try LocalFileSource(url: url), typeHint: AudioDecoder.typeHint(pathExtension: url.pathExtension), kind: .file, gainDB: 0, isRendition: false)81 }82 let hint = AudioDecoder.typeHint(mime: t.mime, container: t.container, codec: t.codec)83 if let url = storage.localFile(for: t), !t.needsCompatRendition {84 return ResolvedSource(source: try LocalFileSource(url: url), typeHint: hint, kind: .local, gainDB: gain, isRendition: false)85 }86 let dir = storage.streamCacheDirectory87 if t.needsCompatRendition {88 guard let size = t.compatSizeBytes, size > 0 else { throw PlaybackError.noFile }89 let key = "compat-" + (t.assetID ?? "na")90 if let done = StreamCache.completeFile(dir, trackID: t.id, assetID: key) {91 return ResolvedSource(source: try LocalFileSource(url: done), typeHint: kAudioFileM4AType, kind: .cache, gainDB: 0, isRendition: true)92 }93 guard api.connectivity.isOnline else { throw PlaybackError.notAvailableOffline }94 let src = try stream(t, cacheKey: key, length: size, etag: nil, sha: nil, query: ["v": "compat"])95 return ResolvedSource(source: src, typeHint: kAudioFileM4AType, kind: .stream, gainDB: 0, isRendition: true)96 }97 guard let asset = t.assetID, t.sizeBytes > 0 else { throw PlaybackError.noFile }98 if let done = StreamCache.completeFile(dir, trackID: t.id, assetID: asset) {99 return ResolvedSource(source: try LocalFileSource(url: done), typeHint: hint, kind: .cache, gainDB: gain, isRendition: false)100 }101 guard api.connectivity.isOnline else { throw t.isDownloaded ? PlaybackError.libraryFolderMissing : PlaybackError.notAvailableOffline }102 let src = try stream(t, cacheKey: asset, length: t.sizeBytes, etag: "\"\(asset)\"", sha: t.sha256, query: [:])103 return ResolvedSource(source: src, typeHint: hint, kind: .stream, gainDB: gain, isRendition: false)104 }105106 private func stream(_ t: Track, cacheKey: String, length: Int64, etag: String?, sha: String?, query: [String: String]) throws -> ProgressiveHTTPSource {107 let dir = storage.streamCacheDirectory108 let api = self.api109 let id = t.id110 _ = try api.authorizedRequest("stream/\(id)", query: query) // fails now when signed out or forced offline111 return try ProgressiveHTTPSource(length: length, cacheURL: StreamCache.audioURL(dir, trackID: id, assetID: cacheKey), rangesURL: StreamCache.rangesURL(dir, trackID: id, assetID: cacheKey),112 doneURL: StreamCache.doneURL(dir, trackID: id, assetID: cacheKey), etag: etag, sha256: sha,113 onOffline: { api.connectivity.noteFailure() }) { try api.authorizedRequest("stream/\(id)", query: query) }114 }115116 /// Lyrics from the local cache, refreshed from the cluster when it can be reached.117 public func lyrics(for t: Track) async -> Lyrics? {118 let cached = await store.cachedLyrics(t.id)119 guard t.externalFileURL == nil, api.connectivity.isOnline else { return cached }120 if let cached, cached.state == "ready" { return cached }121 guard let fresh: Lyrics = try? await api.get("library/tracks/\(t.id)/lyrics") else { return cached }122 if fresh.state == "ready" || fresh.state == "empty" { await store.cacheLyrics(t.id, fresh) }123 return fresh124 }125126 /// Measures the loudness of downloaded files that have not been measured yet (for the optional normalisation).127 public func analyzeLoudness(limit: Int = 20) async {128 for item in await store.downloadedAssetsWithoutLoudness(limit: limit) {129 let url = storage.fileURL(relativePath: item.relativePath)130 guard FileManager.default.fileExists(atPath: url.path), !Task.isCancelled else { continue }131 let r = await Task.detached(priority: .background) { () -> LoudnessAnalyzer.Result? in132 guard let src = try? LocalFileSource(url: url) else { return nil }133 return try? LoudnessAnalyzer.analyze(src, typeHint: AudioDecoder.typeHint(pathExtension: url.pathExtension))134 }.value135 if let r { await store.setLoudness(assetID: item.assetID, lufs: r.lufs, peak: r.peak) }136 else { await store.setLoudness(assetID: item.assetID, lufs: LoudnessAnalyzer.targetLUFS, peak: 1) } // unreadable here: leave its level alone137 }138 }139140 /// Downloads to add so that the pinned collections are complete, and their size.141 public func downloadTracks(_ ids: [String]) async -> Int { await downloads.enqueue(ids) }142143 public func pinAndDownload(_ kind: PinKind, id: String, trackIDs: [String]) async {144 await store.setPinned(kind, id: id, true)145 _ = await downloads.enqueue(trackIDs)146 }147 public func unpinAndRemove(_ kind: PinKind, id: String, trackIDs: [String]) async {148 await store.setPinned(kind, id: id, false)149 await downloads.remove(trackIDs)150 }151152 /// Moves the library folder (see StorageManager.moveLibrary). Downloads are paused during the move.153 public func moveLibrary(to newRoot: URL, progress: @escaping @Sendable (Int64, Int64) -> Void) async throws {154 await downloads.pauseAll()155 let files = await store.downloadedFiles().map { (relativePath: $0.relativePath, size: $0.size) }156 let storage = self.storage157 do {158 try await Task.detached(priority: .userInitiated) { try storage.moveLibrary(to: newRoot, files: files, progress: progress) }.value159 await store.setValue("library.root", newRoot.path)160 } catch { await downloads.resumeAll(); throw error }161 await downloads.resumeAll()162 }163164 public func shutdown() async {165 await downloads.stop()166 await store.close()167 }168}169