SPB Git

Repository Public

OfflineFiles.swift 5.2 KB 95 lines swift

1// SP Music iOS2// File: Core/Sources/SPMusicCore/Offline/OfflineFiles.swift3// Description: File layout of downloaded music, covers and caches; storage accounting.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation910public struct StorageReport: Sendable, Equatable {11    public var audioBytes: Int64 = 012    public var artworkBytes: Int64 = 013    public var cacheBytes: Int64 = 014    public var freeBytes: Int64 = 015    public var tracks = 016    public var albums = 017    public init(audioBytes: Int64 = 0, artworkBytes: Int64 = 0, cacheBytes: Int64 = 0, freeBytes: Int64 = 0, tracks: Int = 0, albums: Int = 0) {18        self.audioBytes = audioBytes; self.artworkBytes = artworkBytes; self.cacheBytes = cacheBytes; self.freeBytes = freeBytes; self.tracks = tracks; self.albums = albums19    }20}2122/// Where the app keeps files.23///   <Application Support>/SPMusic/Media/<track id>.<ext>     downloaded audio — persistent, never purged by iOS24///   <Application Support>/SPMusic/Artwork/<artwork id>.jpg   covers of downloaded music — persistent25///   <Application Support>/SPMusic/Staging/                   transfers being verified, resume data26///   <Caches>/SPMusic/Artwork/                                covers seen while browsing — iOS may purge them27/// Names are built from validated UUIDs only. Files are readable after the first unlock (lock-screen playback) and28/// left out of device backups: they are copies of what MacLustr holds.29public struct OfflineFiles: Sendable {30    public let root: URL31    public let caches: URL3233    public init(root: URL, caches: URL) {34        self.root = root; self.caches = caches35        for d in [media, artwork, staging, artCache] { try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) }36        var r = root37        var v = URLResourceValues(); v.isExcludedFromBackup = true38        try? r.setResourceValues(v)39    }40    public static func standard() -> OfflineFiles {41        let fm = FileManager.default42        let support = (try? fm.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)) ?? fm.temporaryDirectory43        let caches = (try? fm.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)) ?? fm.temporaryDirectory44        return OfflineFiles(root: support.appendingPathComponent("SPMusic", isDirectory: true), caches: caches.appendingPathComponent("SPMusic", isDirectory: true))45    }4647    public var media: URL { root.appendingPathComponent("Media", isDirectory: true) }48    public var artwork: URL { root.appendingPathComponent("Artwork", isDirectory: true) }49    public var staging: URL { root.appendingPathComponent("Staging", isDirectory: true) }50    public var artCache: URL { caches.appendingPathComponent("Artwork", isDirectory: true) }51    public var databaseURL: URL { root.appendingPathComponent("library.sqlite") }5253    private static func safeExt(_ ext: String) -> String {54        let e = ext.lowercased().filter { $0.isASCII && ($0.isLetter || $0.isNumber) }55        return e.isEmpty || e.count > 5 ? "bin" : e56    }57    public func mediaURL(trackId: String, ext: String) throws -> URL { media.appendingPathComponent("\(try SafeID.require(trackId)).\(Self.safeExt(ext))") }58    public func artworkURL(artworkId: String) throws -> URL { artwork.appendingPathComponent("\(try SafeID.require(artworkId)).jpg") }59    public func cachedArtworkURL(artworkId: String, size: Int) throws -> URL { artCache.appendingPathComponent("\(try SafeID.require(artworkId))_\(size).jpg") }60    public func resumeDataURL(trackId: String) throws -> URL { staging.appendingPathComponent("\(try SafeID.require(trackId)).resume") }61    public func newStagingURL() -> URL { staging.appendingPathComponent(UUID().uuidString + ".part") }6263    /// The local file of a finished download, if it is really there.64    public func existingMedia(_ d: DownloadRecord) -> URL? {65        guard d.state == .done, let u = try? mediaURL(trackId: d.trackId, ext: d.ext), FileManager.default.fileExists(atPath: u.path) else { return nil }66        return u67    }6869    public func protect(_ url: URL) {70        #if os(iOS)71        try? FileManager.default.setAttributes([.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: url.path)72        #endif73        var u = url74        var v = URLResourceValues(); v.isExcludedFromBackup = true75        try? u.setResourceValues(v)76    }7778    public static func size(of dir: URL) -> Int64 {79        guard let e = FileManager.default.enumerator(at: dir, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey]) else { return 0 }80        var total: Int64 = 081        for case let f as URL in e {82            let v = try? f.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey])83            if v?.isRegularFile == true { total += Int64(v?.totalFileAllocatedSize ?? 0) }84        }85        return total86    }87    public var freeBytes: Int64 {88        (try? root.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]))?.volumeAvailableCapacityForImportantUsage ?? 089    }90    public func clearCache() {91        try? FileManager.default.removeItem(at: artCache)92        try? FileManager.default.createDirectory(at: artCache, withIntermediateDirectories: true)93    }94}95
Files main
Menu

Theme