SPB Git

Repository Public

ArtworkStore.swift 6.5 KB 144 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music9// File             : App/ArtworkStore.swift10// Description      : Cover loading: memory, persistent copy, cache, server;11//                    decoding off the main thread.12// Module           : App13// Repository       : https://git.spboucher.ai/sp-music-ios14// Created          : 2026-11-1715// Last Modified    : 2026-11-1716//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import ImageIO90import SPMusicCore91import UIKit9293/// Covers. Looked up in this order: memory, the persistent copy kept with downloaded music, the browsing cache,94/// the server. Decoding and resizing happen off the main thread, at the size actually shown.95@MainActor96final class ArtworkStore {97    private let api: APIClient98    private let files: OfflineFiles99    private let network: NetworkMonitor100    private let memory = NSCache<NSString, UIImage>()101    private var inflight: [String: Task<UIImage?, Never>] = [:]102103    init(api: APIClient, files: OfflineFiles, network: NetworkMonitor) {104        self.api = api; self.files = files; self.network = network105        memory.totalCostLimit = 96 << 20106    }107108    func cached(_ id: String, size: Int) -> UIImage? { memory.object(forKey: "\(id)_\(size)" as NSString) }109110    /// `size`: pixel size of the server thumbnail to use (96, 320 or 640).111    func image(_ id: String, size: Int) async -> UIImage? {112        let key = "\(id)_\(size)"113        if let hit = memory.object(forKey: key as NSString) { return hit }114        if let running = inflight[key] { return await running.value }115        guard SafeID.isValid(id) else { return nil }116        let api = api, files = files, online = network.status.online117        let task = Task<UIImage?, Never>.detached(priority: .userInitiated) {118            let persistent = try? files.artworkURL(artworkId: id)119            let cacheURL = try? files.cachedArtworkURL(artworkId: id, size: size)120            for url in [persistent, cacheURL].compactMap({ $0 }) where FileManager.default.fileExists(atPath: url.path) {121                if let img = Self.decode(url: url, maxPixel: size) { return img }122            }123            guard online, api.hasSession, let cacheURL else { return nil }124            guard let (data, http) = try? await api.perform(api.authorized(api.artURL(artworkId: id, size: size))), http.statusCode == 200, !data.isEmpty else { return nil }125            try? data.write(to: cacheURL, options: .atomic)126            return Self.decode(url: cacheURL, maxPixel: size)127        }128        inflight[key] = task129        let image = await task.value130        inflight[key] = nil131        if let image { memory.setObject(image, forKey: key as NSString, cost: Int(image.size.width * image.size.height * image.scale * image.scale * 4)) }132        return image133    }134135    private nonisolated static func decode(url: URL, maxPixel: Int) -> UIImage? {136        guard let src = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil }137        let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxPixel]138        guard let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, options as CFDictionary) else { return nil }139        return UIImage(cgImage: cg)140    }141142    func clearMemory() { memory.removeAllObjects() }143}144
Files main
Menu

Theme