Cotton code
521 lines · 24.3 KB · SwiftRaw
// Keeping a film on the phone (Cinemas definition, 5 Nov 2026, section 7):// Keep on phone, Keep season, Keep series and Remove download (the flows// `keepFilm` and `removeFilmDownload`, from a film's, a season's or an// episode's card), and Keep everything.//// A film the Mac made a stream of comes down whole as Apple's bundle on a// background session that outlives the app (`AVAssetDownloadTask`); a film// kept as one file comes down as a book's or a song's does, on its own// background session (`KeptDownloads.films`), and the core moves it into the// media store (`films.here.write { from }`). A series or a season keeps every// episode of it. Downloads use Wi-Fi only unless this phone said mobile data// may carry them (`films.keeping`'s `cellular`), and a keep that would take// this phone past its budget is refused with the budget said. What is kept// here never syncs; On this phone's top line says how much// ("14 films · 2 series · 38 GB · backed up 1 h ago").import CottonKitimport Foundation#if os(iOS)import AVFoundation#endif/// One film's or episode's file this phone may keep: its record, and what/// its size is guessed from.struct FilmKeepable: Equatable, Sendable {    let table: String    let id: String    let key: String    let title: String    /// Its length and its bitrate (kilobits a second), as the phone read    /// them when it came in.    let minutes: Double?    let bitrate: Double?    /// A film's poster or an episode's still.    let poster: String?    init?(table: String, id: String, values: [String: RecordValue]) {        guard let key = values["file"]?.text, !key.isEmpty else { return nil }        self.table = table        self.id = id        self.key = key        title = values["title"]?.text ?? ""        minutes = values["minutes"]?.number        bitrate = values["bitrate"]?.number        poster = values[table == FilmKeeping.film ? "poster" : "still"]?.text    }    /// Bytes it will take, guessed from its length and its bitrate; nil    /// when either is not known.    var bytes: Int64? {        guard let minutes, let bitrate, minutes > 0, bitrate > 0 else { return nil }        return Int64(minutes * 60 * bitrate * 1000 / 8)    }}/// This phone's keeping knobs (`films.keeping`), and the arithmetic of its/// budget and its top line, as plain functions the tests hold.struct FilmKeeping: Decodable, Equatable, Sendable {    static let film = "film"    static let season = "film_season"    static let episode = "film_episode"    var keep_everything: Bool    var cellular: Bool    var budget_gb: Int    /// The budget, in bytes.    var budget: Int64 { Int64(budget_gb) * 1_000_000_000 }    /// Whether `adding` bytes more fit beside `held`.    func fits(_ adding: Int64, beside held: Int64) -> Bool { held + adding <= budget }    /// The budget as the line says it ("64 GB").    var budgetSaid: String { FilmKeeping.size(budget) }    /// Bytes as the top line says them: gigabytes from one, whole from ten    /// and a tenth under; megabytes under one, whole from ten and a tenth    /// under, so a few small files never read as nothing.    static func size(_ bytes: Int64) -> String {        func said(_ n: Double) -> String { n >= 10 || n == n.rounded() ? String(Int(n.rounded())) : String(format: "%.1f", n) }        let gb = Double(bytes) / 1_000_000_000        if gb >= 1 { return ShellLines.line("sync", "sizes.gigabytes", ["n": said(gb)]) }        return ShellLines.line("sync", "sizes.megabytes", ["n": said(Double(bytes) / 1_000_000)])    }    /// On this phone's top line: the films it lists and the episodes kept,    /// their size, and when this phone last backed up, where it has.    static func head(films: Int, episodes: Int, bytes: Int64, backedUp: String?) -> String {        let fills = [            "films": plural(films, one: ShellLines.line("cinemas", "keep.films.one", ["n": String(films)]),                            many: ShellLines.line("cinemas", "keep.films.other", ["n": String(films)])),            "episodes": plural(episodes, one: ShellLines.line("cinemas", "keep.episodes.one", ["n": String(episodes)]),                               many: ShellLines.line("cinemas", "keep.episodes.other", ["n": String(episodes)])),            "size": size(bytes),        ]        guard let backedUp else { return ShellLines.line("cinemas", "keep.head", fills) }        return ShellLines.line("cinemas", "keep.head_backed_up", fills.merging(["ago": backedUp]) { $1 })    }    /// How long ago `at` was, in the dates set's words ("1 h ago").    static func ago(_ at: Date, now: Date) -> String {        let minutes = Int(max(0, now.timeIntervalSince(at)) / 60)        if minutes < 1 { return ShellLines.line("dates", "ago.just_now") }        if minutes < 60 { return ShellLines.line("dates", "ago.minutes", ["n": String(minutes)]) }        if minutes < 24 * 60 { return ShellLines.line("dates", "ago.hours", ["n": String(minutes / 60)]) }        let days = minutes / (24 * 60)        return plural(days, one: ShellLines.line("dates", "ago.days.one", ["n": String(days)]),                      many: ShellLines.line("dates", "ago.days.other", ["n": String(days)]))    }}#if os(iOS)@MainActor @Observablefinal class FilmKeeper {    static let shared = FilmKeeper(downloads: KeptDownloads.films)    /// The background session a stream's bundle comes down on.    static let session = "cotton.films.keep"    struct Keeping: Equatable {        let key: String        let table: String        let title: String        var fraction: Double        private struct Described: Codable { let key, table, title: String }        /// What the task carries across launches (`taskDescription`).        var described: String {            String(decoding: (try? JSONEncoder().encode(Described(key: key, table: table, title: title))) ?? Data(), as: UTF8.self)        }        static func read(_ described: String?) -> Keeping? {            guard let described, let read = try? JSONDecoder().decode(Described.self, from: Data(described.utf8)) else { return nil }            return Keeping(key: read.key, table: read.table, title: read.title, fraction: 0)        }    }    /// The streams coming down now, by their master's key.    private(set) var keeping: [String: Keeping] = [:]    /// Whole files coming down now, by key.    private(set) var fetching: Set<String> = []    @ObservationIgnored private let downloads: any KeptDownloading    @ObservationIgnored private var core: (any CottonCalling)?    @ObservationIgnored private var say: ((String) -> Void)?    @ObservationIgnored private var tell: ((String) -> Void)?    @ObservationIgnored private var session: AVAssetDownloadURLSession?    @ObservationIgnored private let delegate = FilmKeeperDelegate()    @ObservationIgnored private var tasks: [String: AVAssetDownloadTask] = [:]    @ObservationIgnored private var progress: [String: NSKeyValueObservation] = [:]    @ObservationIgnored private var locations: [String: URL] = [:]    /// Bundles and files that landed before the core was here (a launch iOS    /// made to hand the sessions' events over): written once it is.    @ObservationIgnored private var landed: [(key: String, location: URL)] = []    @ObservationIgnored private var early: [(key: String, result: Result<URL, Error>)] = []    @ObservationIgnored private var wakes: [() -> Void] = []    init(downloads: any KeptDownloading) {        self.downloads = downloads        downloads.ended = { [weak self] key, result in self?.ended(key, result) }    }    /// The streams' session, made again at launch so the bundles iOS carried    /// while the app was gone are handed to this process.    func wake(_ events: (() -> Void)? = nil) {        if let events { wakes.append(events) }        downloads.wake()        guard session == nil else { return }        delegate.keeper = self        let configuration = URLSessionConfiguration.background(withIdentifier: Self.session)        configuration.sessionSendsLaunchEvents = true        let session = AVAssetDownloadURLSession(configuration: configuration, assetDownloadDelegate: delegate, delegateQueue: .main)        self.session = session        session.getAllTasks { [weak self] found in            let carried = found.compactMap { $0 as? AVAssetDownloadTask }            Task { @MainActor in                for task in carried { if let coming = Keeping.read(task.taskDescription) { self?.follow(task, coming) } }            }        }    }    /// The core and the toasts for a failure (`say`) and for news (`tell`),    /// from the root once a core is open.    func attach(core: any CottonCalling, say: @escaping (String) -> Void, tell: @escaping (String) -> Void) {        self.core = core        self.say = say        self.tell = tell        wake()        let waiting = landed        landed = []        for (key, location) in waiting { Task { await self.land(key, at: location) } }        let ends = early        early = []        for (key, result) in ends { ended(key, result) }        Task { await sweep() }    }    // MARK: Keep and remove    /// Keep on phone, Keep season, Keep series: every file the record names    /// that this phone keeps nothing of comes down, within the budget.    func keep(table: String, id: String) async -> Bool {        guard let core else { return false }        let films = await Self.keepable(table: table, id: id, core: core)        guard !films.isEmpty else { return false }        do {            let knobs = try await core.call(CottonMethod.filmsKeeping, [String: RecordValue](), as: FilmKeeping.self)            var held = try await heldBytes(core: core)            for film in films {                guard try await FilmHereStore(core: core).read(film.key).state == nil else { continue }                let adding = film.bytes ?? 0                guard knobs.fits(adding, beside: held) else {                    say?(ShellLines.line("cinemas", "keep.over_budget", ["size": knobs.budgetSaid]))                    return false                }                held += adding                try await start(film, cellular: knobs.cellular, core: core)            }            return true        } catch {            say?((error as? CottonCallError)?.message ?? ShellLines.line("cinemas", "keep.could_not_keep"))            return false        }    }    /// Remove download: what is coming down stops, and what is kept goes —    /// a stream's bundle by the platform, a whole file by the core.    func remove(table: String, id: String) async -> Bool {        guard let core else { return false }        let films = await Self.keepable(table: table, id: id, core: core)        guard !films.isEmpty else { return false }        let store = FilmHereStore(core: core)        do {            for film in films {                let here = try await store.read(film.key)                guard here.state != nil else { continue }                if FilmKey.streams(film.key) {                    tasks[film.key]?.cancel()                    stopFollowing(film.key)                    if let bundle = FilmBundle.url(here.bookmark) { try? FileManager.default.removeItem(at: bundle) }                    try await store.forget(film.key)                } else if here.state == .keeping {                    downloads.cancel(film.key)                    fetching.remove(film.key)                    try await store.forget(film.key)                } else {                    try await store.remove(film.key)                }            }            return true        } catch {            say?((error as? CottonCallError)?.message ?? ShellLines.line("cinemas", "keep.could_not_remove"))            return false        }    }    /// Keep everything turned on (`keep_films`): what it says is said, and    /// every film and episode not on this phone comes down.    func keepEverything(said: String?) async {        if let said { tell?(said) }        await sweep(asked: true)    }    /// With Keep everything on, every film and episode this phone keeps    /// nothing of comes down, until the budget is reached.    func sweep(asked: Bool = false) async {        guard let core, let knobs = try? await core.call(CottonMethod.filmsKeeping, [String: RecordValue](), as: FilmKeeping.self),              asked || knobs.keep_everything else { return }        let absent: [String: RecordValue] = ["on_phone": .text("absent")]        var films = await Self.list(Self.film, where: absent.merging(["kind": .text("film")]) { $1 }, core: core)        films += await Self.list(Self.episode, where: absent, core: core)        guard var held = try? await heldBytes(core: core) else { return }        for film in films where !fetching.contains(film.key) && keeping[film.key] == nil {            let adding = film.bytes ?? 0            guard knobs.fits(adding, beside: held) else {                say?(ShellLines.line("cinemas", "keep.over_budget", ["size": knobs.budgetSaid]))                return            }            held += adding            do {                try await start(film, cellular: knobs.cellular, core: core)            } catch {                say?((error as? CottonCallError)?.message ?? ShellLines.line("cinemas", "keep.could_not_keep"))                return            }        }    }    /// One file starts coming down: a stream as its bundle, a whole file    /// to the media store; over mobile data only when `cellular`.    private func start(_ film: FilmKeepable, cellular: Bool, core: any CottonCalling) async throws {        let store = FilmHereStore(core: core)        let url = try await FilmStreamGrant.mint(film.key, core: core)        try await store.keeping(film.key)        guard FilmKey.streams(film.key) else {            fetching.insert(film.key)            KeptDownloads.films.cellular = cellular            downloads.start(url, key: film.key)            return        }        guard let session else { throw CottonCallError(code: "unwritable", message: ShellLines.line("cinemas", "keep.could_not_keep")) }        var artwork: Data?        if let poster = film.poster { artwork = await FilmPlayback.artwork(poster, core: core) }        let asset = AVURLAsset(url: url, options: [AVURLAssetAllowsCellularAccessKey: cellular])        // A film streams as a ladder (owner, 17 Nov 2026); the phone keeps one rung, the top: asked for a bitrate        // no rung reaches, AVFoundation takes the highest.        let options: [String: Any] = [AVAssetDownloadTaskMinimumRequiredMediaBitrateKey: Int(Int32.max)]        guard let task = session.makeAssetDownloadTask(asset: asset, assetTitle: film.title, assetArtworkData: artwork, options: options) else {            try? await store.forget(film.key)            throw CottonCallError(code: "unwritable", message: ShellLines.line("cinemas", "keep.could_not_keep"))        }        let coming = Keeping(key: film.key, table: film.table, title: film.title, fraction: 0)        task.taskDescription = coming.described        follow(task, coming)        task.resume()    }    // MARK: What is kept    /// The bytes this phone keeps of films: the whole files the core holds,    /// and every kept stream's bundle, measured on disk.    private func heldBytes(core: any CottonCalling) async throws -> Int64 {        struct OnPhone: Decodable { let bytes: Int64 }        let wholes = try await core.call(CottonMethod.filmsOnPhone, [String: RecordValue](), as: OnPhone.self).bytes        return wholes + (await bundleBytes(core: core))    }    /// The kept streams' bundles, measured on disk.    private func bundleBytes(core: any CottonCalling) async -> Int64 {        let kept: [String: RecordValue] = ["on_phone": .list([.text("kept")])]        let films = await Self.list(Self.film, where: kept, core: core) + Self.list(Self.episode, where: kept, core: core)        var bytes: Int64 = 0        for film in films where FilmKey.streams(film.key) {            guard let here = try? await FilmHereStore(core: core).read(film.key), let bundle = FilmBundle.url(here.bookmark) else { continue }            bytes += Self.size(of: bundle)        }        return bytes    }    /// On this phone's top line, read now: the films listed and episodes    /// kept, their size, and when this phone last backed up.    func head() async -> String? {        guard let core else { return nil }        struct OnPhone: Decodable { let films: Int; let episodes: Int; let bytes: Int64 }        guard let counted = try? await core.call(CottonMethod.filmsOnPhone, [String: RecordValue](), as: OnPhone.self) else { return nil }        let bytes = counted.bytes + (await bundleBytes(core: core))        let sync = try? await core.call(CottonMethod.readSyncStatus, as: SyncStatusRead.self)        let backedUp = sync?.lastPullAt.flatMap { CottonDate.parse($0) }.map { FilmKeeping.ago($0, now: Date()) }        return FilmKeeping.head(films: counted.films, episodes: counted.episodes, bytes: bytes, backedUp: backedUp)    }    /// The deck's counter while a film of `table` comes down; nil when none.    func line(table: String) -> String? {        guard let coming = keeping.values.filter({ $0.table == table }).sorted(by: { $0.key < $1.key }).first else { return nil }        let percent = Int((coming.fraction * 100).rounded(.down))        return ShellLines.line("cards", "deck.keeping", ["title": coming.title, "percent": String(percent)])    }    private static func size(of folder: URL) -> Int64 {        guard let walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]) else { return 0 }        var bytes: Int64 = 0        for case let url as URL in walk {            bytes += Int64((try? url.resourceValues(forKeys: [.totalFileAllocatedSizeKey]).totalFileAllocatedSize) ?? 0)        }        return bytes    }    // MARK: The records a keep names    static let film = FilmKeeping.film    static let season = FilmKeeping.season    static let episode = FilmKeeping.episode    /// The files a record names: a film's own, a series' every episode's, a    /// season's every episode's, an episode's own.    static func keepable(table: String, id: String, core: any CottonCalling) async -> [FilmKeepable] {        switch table {        case film:            struct Read: Decodable { let data: [String: RecordValue] }            guard let read = try? await core.call(CottonMethod.recordsGet, ["table": RecordValue.text(film), "id": .text(id)], as: Read.self) else { return [] }            if read.data["kind"]?.text == "series" { return await list(episode, where: ["series": .text(id)], core: core) }            return FilmKeepable(table: film, id: id, values: read.data).map { [$0] } ?? []        case season:            return await list(episode, where: ["season": .text(id)], core: core)        case episode:            struct Read: Decodable { let data: [String: RecordValue] }            guard let read = try? await core.call(CottonMethod.recordsGet, ["table": RecordValue.text(episode), "id": .text(id)], as: Read.self) else { return [] }            return FilmKeepable(table: episode, id: id, values: read.data).map { [$0] } ?? []        default:            return []        }    }    /// Every record of `table` the filter keeps that has a file, page after page.    private static func list(_ table: String, where filter: [String: RecordValue], core: any CottonCalling) async -> [FilmKeepable] {        struct Page: Decodable { let records: [CoreRecords.WireRecord]; let next_page: Int? }        var found: [FilmKeepable] = []        var page = 0        while true {            let request: [String: RecordValue] = ["table": .text(table), "where": .object(filter), "page": .number(Double(page)), "limit": .number(200)]            guard let read = try? await core.call(CottonMethod.recordsList, request, as: Page.self) else { return found }            found += read.records.compactMap { FilmKeepable(table: table, id: $0.id, values: $0.data) }            guard let next = read.next_page, next > page, !read.records.isEmpty else { return found }            page = next        }    }    // MARK: The streams' progress    private func follow(_ task: AVAssetDownloadTask, _ coming: Keeping) {        let key = coming.key        tasks[key] = task        var coming = coming        coming.fraction = task.progress.fractionCompleted        keeping[key] = coming        progress[key] = task.progress.observe(\.fractionCompleted) { [weak self] seen, _ in            let fraction = seen.fractionCompleted            Task { @MainActor in self?.keeping[key]?.fraction = fraction }        }    }    private func stopFollowing(_ key: String) {        tasks[key] = nil        progress[key] = nil        keeping[key] = nil        locations[key] = nil    }    // MARK: A whole file's download (`KeptDownloads.films`)    private func ended(_ key: String, _ result: Result<URL, Error>) {        guard let core else { return early.append((key, result)) }        fetching.remove(key)        Task {            let store = FilmHereStore(core: core)            switch result {            case .success(let file):                guard (try? await store.read(key))?.state == .keeping else {                    try? FileManager.default.removeItem(at: file)                    return                }                do {                    try await store.adopt(key, from: file)                } catch {                    try? FileManager.default.removeItem(at: file)                    try? await store.forget(key)                    say?((error as? CottonCallError)?.message ?? ShellLines.line("cinemas", "keep.could_not_keep"))                }            case .failure(let error):                guard (error as NSError).code != NSURLErrorCancelled else { return }                try? await store.forget(key)                say?(ShellLines.line("cinemas", "keep.could_not_keep"))            }        }    }    // MARK: The streams' session's word (`FilmKeeperDelegate`)    fileprivate func willLand(_ key: String, at location: URL) { locations[key] = location }    fileprivate func done(_ key: String, error: Error?) {        let location = locations[key]        stopFollowing(key)        if let error {            // Cancelled is Remove download's own doing.            if (error as NSError).code == NSURLErrorCancelled { return }            if let location { try? FileManager.default.removeItem(at: location) }            say?(ShellLines.line("cinemas", "keep.could_not_keep"))            if let core { Task { try? await FilmHereStore(core: core).forget(key) } }            return        }        guard let location else { return }        guard core != nil else { return landed.append((key, location)) }        Task { await land(key, at: location) }    }    private func land(_ key: String, at location: URL) async {        guard let core else { return }        do {            let bookmark = try location.bookmarkData()            try await FilmHereStore(core: core).kept(key, bookmark: bookmark)        } catch {            say?(ShellLines.line("cinemas", "keep.could_not_keep"))        }    }    fileprivate func eventsDone() {        let waiting = wakes        wakes = []        waiting.forEach { $0() }    }}/// The streams' background session's delegate: it hands every word to the/// keeper on the main actor (the session's queue is main).private final class FilmKeeperDelegate: NSObject, AVAssetDownloadDelegate, @unchecked Sendable {    weak var keeper: FilmKeeper?    func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, willDownloadTo location: URL) {        guard let key = FilmKeeper.Keeping.read(assetDownloadTask.taskDescription)?.key else { return }        MainActor.assumeIsolated { keeper?.willLand(key, at: location) }    }    func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {        guard let key = FilmKeeper.Keeping.read(assetDownloadTask.taskDescription)?.key else { return }        MainActor.assumeIsolated { keeper?.willLand(key, at: location) }    }    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {        guard let key = FilmKeeper.Keeping.read(task.taskDescription)?.key else { return }        MainActor.assumeIsolated { keeper?.done(key, error: error) }    }    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {        MainActor.assumeIsolated { keeper?.eventsDone() }    }}#endif