SPB Git

Repository Public

ArtworkStore.swift 3.7 KB 65 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Metadata/ArtworkStore.swift3// Description: Cover art cache on disk, and the naming of streaming-cache files.4import Foundation56/// Cover art on disk. Covers are fetched once (the cluster names each image by an immutable id) and then read7/// locally forever, so they stay visible offline.8public actor ArtworkStore {9    public static let sizes = [96, 320, 640]10    private let api: APIClient11    private let directory: URL12    private var inflight: [String: Task<URL?, Never>] = [:]1314    public init(api: APIClient, directory: URL) { self.api = api; self.directory = directory }1516    public nonisolated func fileURL(_ id: String, size: Int) -> URL { directory.appendingPathComponent("\(id)-\(size).jpg") }1718    /// The best file already on disk for this cover: the requested size, else a larger one, else a smaller one.19    public nonisolated func cached(_ id: String, size: Int) -> URL? {20        let fm = FileManager.default21        let order = [size] + Self.sizes.filter { $0 > size } + Self.sizes.filter { $0 < size }.reversed()22        for s in order { let u = fileURL(id, size: s); if fm.fileExists(atPath: u.path) { return u } }23        return nil24    }2526    /// The cover at this size, fetched from the cluster when it is not on disk yet. Nil when offline and never fetched.27    public func url(_ id: String, size: Int) async -> URL? {28        let target = fileURL(id, size: size)29        if FileManager.default.fileExists(atPath: target.path) { return target }30        let key = "\(id)-\(size)"31        if let t = inflight[key] { return await t.value ?? cached(id, size: size) }32        let api = self.api33        let task = Task<URL?, Never> {34            guard api.connectivity.isOnline, let (data, _) = try? await api.exchange("GET", "art/\(id)", query: ["s": String(size)], timeout: 20), data.count > 100 else { return nil }35            do { try data.write(to: target, options: .atomic); return target } catch { return nil }36        }37        inflight[key] = task38        let result = await task.value39        inflight[key] = nil40        return result ?? cached(id, size: size)41    }4243    /// Fetches the covers that are not on disk yet, a few at a time. Stops quietly when the cluster becomes unreachable.44    public func prefetch(_ ids: [String], size: Int = 320) async {45        let missing = ids.filter { !FileManager.default.fileExists(atPath: fileURL($0, size: size).path) }46        for chunk in stride(from: 0, to: missing.count, by: 6).map({ Array(missing[$0..<min($0 + 6, missing.count)]) }) {47            guard api.connectivity.isOnline, !Task.isCancelled else { return }48            await withTaskGroup(of: Void.self) { g in for id in chunk { g.addTask { _ = await self.url(id, size: size) } } }49        }50    }51}5253/// Files of the streaming cache: `<track>.<asset>.audio` holds the bytes received so far, `.done` marks a complete,54/// verified copy (which a download can then reuse instead of fetching the file again).55public enum StreamCache {56    public static func audioURL(_ dir: URL, trackID: String, assetID: String) -> URL { dir.appendingPathComponent("\(trackID).\(assetID).audio") }57    public static func doneURL(_ dir: URL, trackID: String, assetID: String) -> URL { dir.appendingPathComponent("\(trackID).\(assetID).done") }58    public static func rangesURL(_ dir: URL, trackID: String, assetID: String) -> URL { dir.appendingPathComponent("\(trackID).\(assetID).ranges") }59    public static func completeFile(_ dir: URL, trackID: String, assetID: String) -> URL? {60        let fm = FileManager.default61        let a = audioURL(dir, trackID: trackID, assetID: assetID)62        return fm.fileExists(atPath: doneURL(dir, trackID: trackID, assetID: assetID).path) && fm.fileExists(atPath: a.path) ? a : nil63    }64}65
Files main
Menu

Theme