Cotton code
205 lines · 8.8 KB · SwiftRaw
// A song's file on this phone: kept, coming down, or not here (Cotton Music,// 4 Nov 2026).//// As a book's (`BookKeeper`): the bytes live once in the phone's// content-addressed media store; what this phone keeps of each song is// `songs.here` in the core (`phone::songs`), never synced, keyed by the song's// file key; `kept` pins the bytes, and Remove download (`songs.remove`) lets// this copy go — never the last one, which the object's bucket holds. An// album keeps and lets go of its songs together. With Keep everything on, every// song not here comes down (`sweep`).//// The bytes come down from the address the object signs for the song's one// key (`media.stream`), on the music's own background session// (`KeptDownloads.songs`); what lands is handed to the core// (`songs.here.write { from }`).import CottonKitimport Foundationimport os/// The core's device-local store of songs (`phone::songs`).struct SongHereStore: Sendable {    let core: any CottonCalling    private struct Wire: Decodable { let state: String? }    func read(_ key: String) async throws -> BookHere {        let wire = try await core.call(CottonMethod.songsHereRead, ["key": RecordValue.text(key)], as: Wire.self)        return wire.state.flatMap(BookHere.init(rawValue:)) ?? .absent    }    func write(_ key: String, _ state: BookHere) async throws {        let value: RecordValue = state == .absent ? .null : .text(state.rawValue)        _ = try await core.callJSON(CottonMethod.songsHereWrite, ["key": .text(key), "state": value])    }    func adopt(_ key: String, from file: URL) async throws {        let request: [String: RecordValue] = ["key": .text(key), "state": .text(BookHere.kept.rawValue), "from": .text(file.path)]        _ = try await core.callJSON(CottonMethod.songsHereWrite, request)    }    func remove(_ key: String) async throws {        _ = try await core.callJSON(CottonMethod.songsRemove, ["key": RecordValue.text(key)])    }}@MainActorfinal class SongKeeper {    static let shared = SongKeeper(downloads: KeptDownloads.songs)    private static let log = Logger(subsystem: "com.cottondb.music", category: "keep")    static let song = "song"    static let album = "music_album"    private let downloads: any KeptDownloading    private var core: (any CottonCalling)?    private var say: ((String) -> Void)?    private var tell: ((String) -> Void)?    /// The songs coming down now, by file key.    private var fetching: Set<String> = []    private var early: [(key: String, result: Result<URL, Error>)] = []    init(downloads: any KeptDownloading) {        self.downloads = downloads        downloads.ended = { [weak self] key, result in self?.ended(key, result) }    }    /// The core, and the toasts for a failure (`say`) and for news (`tell`).    func attach(core: any CottonCalling, say: @escaping (String) -> Void, tell: @escaping (String) -> Void) {        self.core = core        self.say = say        self.tell = tell        downloads.wake()        let waiting = early        early = []        for (key, result) in waiting { ended(key, result) }        Task { await sweep() }    }    /// Keep on phone: a song's (`keepSong`) or an album's (`keepAlbum`), every    /// song of it.    func keep(table: String, id: String) async -> Bool {        guard let core else { return false }        let keys = await Self.files(table: table, id: id, core: core)        guard !keys.isEmpty else { return false }        var all = true        for key in keys {            do {                if try await SongHereStore(core: core).read(key) != .absent { continue }            } catch {                say?((error as? CottonCallError)?.message ?? ShellLines.line("music", "keep.could_not_keep"))                return false            }            if fetching.insert(key).inserted { all = await fetch(key, core: core) && all }        }        return all    }    /// Remove download: a song's (`removeSongDownload`) or an album's    /// (`removeAlbumDownload`).    func remove(table: String, id: String) async -> Bool {        guard let core else { return false }        let keys = await Self.files(table: table, id: id, core: core)        guard !keys.isEmpty else { return false }        for key in keys {            downloads.cancel(key)            fetching.remove(key)            guard (try? await SongHereStore(core: core).read(key)) != .absent else { continue }            do {                try await SongHereStore(core: core).remove(key)            } catch {                say?((error as? CottonCallError)?.message ?? ShellLines.line("music", "keep.could_not_remove"))                return false            }        }        return true    }    /// Keep everything turned on (`keep_songs`): what it says is said, and    /// every song not here comes down.    func keepEverything(said: String?) async {        if let said { tell?(said) }        await sweep(asked: true)    }    /// With Keep everything on, every song not on this phone comes down.    func sweep(asked: Bool = false) async {        guard let core else { return }        if !asked {            struct On: Decodable { let on: Bool }            guard let on = try? await core.call(CottonMethod.songsKeepEverything, [String: RecordValue](), as: On.self), on.on else { return }        }        let request: [String: RecordValue] = ["table": .text(Self.song), "where": .object(["on_phone": .text(BookHere.absent.rawValue)])]        for key in await Self.files(request, core: core) where fetching.insert(key).inserted {            await fetch(key, core: core)        }    }    @discardableResult    private func fetch(_ key: String, core: any CottonCalling) async -> Bool {        let store = SongHereStore(core: core)        do {            try await store.write(key, BookHere.absent.after(.keep).state)            let grant = try await core.call(CottonMethod.mediaStream, ["key": RecordValue.text(key)], as: BookStreamGrant.self)            guard let address = URL(string: grant.url) else { throw CocoaError(.fileReadCorruptFile) }            Self.log.info("song \(key.suffix(12), privacy: .public) comes down through its signed stream")            downloads.start(address, key: key)            return true        } catch {            fetching.remove(key)            try? await store.write(key, BookHere.keeping.after(.failed).state)            say?((error as? CottonCallError)?.message ?? ShellLines.line("music", "keep.could_not_keep"))            return false        }    }    private func ended(_ key: String, _ result: Result<URL, Error>) {        guard let core else { return early.append((key, result)) }        fetching.remove(key)        Task {            let store = SongHereStore(core: core)            switch result {            case .success(let file):                guard try await store.read(key) == .keeping else {                    try? FileManager.default.removeItem(at: file)                    return                }                do {                    try await store.adopt(key, from: file)                    Self.log.info("song \(key.suffix(12), privacy: .public) kept")                } catch {                    try? FileManager.default.removeItem(at: file)                    try? await store.write(key, BookHere.keeping.after(.failed).state)                    say?((error as? CottonCallError)?.message ?? ShellLines.line("music", "keep.could_not_keep"))                }            case .failure(let error):                guard (error as NSError).code != NSURLErrorCancelled else { return }                try? await store.write(key, BookHere.keeping.after(.failed).state)                say?(ShellLines.line("music", "keep.could_not_keep"))            }        }    }    /// The file keys a song or an album names: the song's own, or every song    /// of the album.    private static func files(table: String, id: String, core: any CottonCalling) async -> [String] {        switch table {        case song:            struct Read: Decodable { let data: [String: RecordValue] }            guard let read = try? await core.call(CottonMethod.recordsGet, ["table": RecordValue.text(table), "id": .text(id)], as: Read.self),                  let file = read.data["file"]?.text, !file.isEmpty else { return [] }            return [file]        case album:            return await files(["table": .text(song), "where": .object(["album": .text(id)])], core: core)        default:            return []        }    }    private static func files(_ request: [String: RecordValue], core: any CottonCalling) async -> [String] {        struct Page: Decodable { let records: [CoreRecords.WireRecord] }        guard let page = try? await core.call(CottonMethod.recordsList, request, as: Page.self) else { return [] }        return page.records.compactMap { $0.record.values["file"]?.text }.filter { !$0.isEmpty }    }}