Cotton code
401 lines · 21.7 KB · SwiftRaw
// WHERE CINEMAS' ANSWERS COME FROM: the core's streaming calls (CONTRACT-2), or, on a Dev build asked for it by a// launch argument, an invented library (`CinemasInvented`) so the screens can be walked before the calls land and with// nothing of the owner's. The screens never know which; neither source decides anything the core would not.import CottonKitimport Foundationprotocol CinemasSource: Sendable {    func home() async -> CinemasRead<CinemasHome>    /// `cinemas.row {id, after, filter, hidden?}`: a page of a row, under one of its chips' filters.    ///    /// `hidden` (here and on `title`, `search` and `groups`) is said only inside Hidden, once the phone's lock has    /// passed (CONTRACT-2 HIDDEN): the core then answers hidden titles and categories too. Everywhere else it leaves    /// them out; the screens never filter.    func row(_ id: String, after: String?, filter: String?, hidden: Bool) async -> CinemasRead<CinemasRowPage>    func title(table: String, id: String, hidden: Bool) async -> CinemasRead<CinemasTitle>    func season(_ id: String) async -> CinemasRead<CinemasSeason>    func search(_ q: String, hidden: Bool) async -> CinemasRead<CinemasFound>    func groups(hidden: Bool) async -> CinemasRead<CinemasGroups>    /// His categories, each saying whether it holds this title: `cinemas.title`'s own `groups` (never `groups.list`,    /// which knows nothing of hidden).    func groups(holding item: CinemasItem, hidden: Bool) async -> CinemasRead<CinemasGroups>    /// `cinemas.hide {id, hidden}`: a category hidden, or brought back; the core's words for it.    func hide(_ group: String, hidden: Bool) async -> CinemasRead<CinemasHid>    /// The Undo a Hide or Stop hiding handed back, run exactly as handed: its method with its args.    func undo(_ undo: CinemasHid.Undo) async -> CinemasRead<CinemasHid>    /// `cinemas.hidden {}`: the hidden place. Without the core's unlock it answers locked, with no rows.    func hiddenPlace() async -> CinemasRead<CinemasHiddenPlace>    /// `cinemas.unlock {no_lock?}`: asked only after the phone's own lock passed (or the phone has none, said so).    func unlock(noLock: Bool) async -> CinemasRead<Bool>    /// `cinemas.lock {}`: Hidden shut, on leaving it and when the app leaves the screen.    func lock() async -> CinemasRead<Bool>    /// What a title is: `cinemas.kind {id, to}`; the core's own words for it.    func kind(_ item: CinemasItem, to kind: CinemasItem.Kind) async -> CinemasRead<String?>    /// His groups in his order, the rows' order on Home: `cinemas.groupsOrder {order}`.    func orderGroups(_ order: [String]) async -> CinemasRead<Bool>    /// Adds the title to the group, or takes it out: `groups.update {id, add|remove}`.    func group(_ group: String, item: CinemasItem, in: Bool) async -> CinemasRead<Bool>    /// `groups.create {table: "film", name, records?}`: the new group's id.    func makeGroup(_ name: String, with item: CinemasItem?) async -> CinemasRead<String>    /// `groups.update {id, move: "earlier" | "later"}`.    func moveGroup(_ group: String, earlier: Bool) async -> CinemasRead<Bool>    func renameGroup(_ group: String, to name: String) async -> CinemasRead<Bool>    /// `groups.delete {id}`: the change Undo takes back (the films stay).    func deleteGroup(_ group: String) async -> CinemasRead<String?>    /// `films.mark {table, id, watched}`: the core's own words for it, when it says any.    func mark(_ item: CinemasItem, watched: Bool) async -> CinemasRead<String?>    /// `records.delete {table, id}`: to the Bin; the change Undo takes back.    func bin(_ item: CinemasItem) async -> CinemasRead<String?>    /// `cinemas.you {free_bytes}`: You's sections.    func you(free: Int64?) async -> CinemasRead<CinemasYou>    /// A row of You's act, as the core wrote it (`cinemas.setting`, `films.keeping`): done or refused.    func youAct(_ method: String, _ request: JSONValue?) async -> CinemasRead<Bool>    /// `cinemas.bin {}`: what waits in the Bin, each with its line ("Moved to the Bin today").    func binned() async -> CinemasRead<CinemasBin>    /// `cinemas.restore {id}`: back out of the Bin; the core's words for it.    func restore(_ item: CinemasItem) async -> CinemasRead<String?>    /// An act the core named with its method and arguments (a hidden category's Restore; the Bin's Restore and Delete    /// forever, with `id` for one title); the core's words for it.    func named(_ act: CinemasNamedAct, id: String?) async -> CinemasRead<String?>    /// `cinemas.bin {hidden: true}`: inside Hidden, the hidden titles' own Bin (core 4).    func binned(hidden: Bool) async -> CinemasRead<CinemasBin>    /// `records.undo {change_id}`.    func undo(_ change: String) async -> CinemasRead<Bool>    /// `cinemas.onPhone {free_bytes}`.    func onPhone(free: Int64?) async -> CinemasRead<CinemasOnPhone>    /// Whether downloads may use mobile data: `films.keeping {}`'s `cellular`.    func cellular() async -> CinemasRead<Bool>    /// `films.keeping {cellular}`: the rule as it now stands.    func setCellular(_ on: Bool) async -> CinemasRead<Bool>    /// `cinemas.preparing {table, id}`.    func preparing(_ item: CinemasItem) async -> CinemasRead<CinemasPreparing>    /// `cinemas.remote {table, id, at_s, length_s, device}`.    func remote(table: String, id: String, at: Double, length: Double?, device: String?) async -> CinemasRead<CinemasRemoteWords>    /// `cinemas.toEpisode {id, series: <id> | {new: name}, season, episode}`: a film row that is really an episode moves    /// into its series, its files with it (the lead's 5bbd70c137: the binned film row no longer names them).    func toEpisode(_ item: CinemasItem, series: String?, newSeries: String?, season: Int, episode: Int) async -> CinemasRead<Bool>    /// Send to a friend, the Send step every app has: `shell.opened {table, id, step: "send"}` — his people, what goes,    /// or why nobody can be sent to.    func sendStep(_ item: CinemasItem) async -> CinemasRead<SendStep>    /// `send.make {table, id, to, name}`: the send's id (for Undo) and the receipt's words.    func send(_ item: CinemasItem, to person: SendPerson) async -> CinemasRead<CinemasSent>    /// `send.undo {id}`: a send taken back while it is not yet kept.    func unsend(_ id: String) async -> CinemasRead<Bool>    /// `cinemas.subtitles {table, id}`.    func subtitles(_ item: CinemasItem) async -> CinemasRead<CinemasSubtitles>    /// One of the Subtitles sheet's acts: find → `records.command find_subtitles`, make → `generate_subtitles`, give →    /// `films.subtitleFile {path}` (his own .srt or .vtt). The core's words, when it says any.    func subtitlesAct(_ act: String, item: CinemasItem, file: URL?) async -> CinemasRead<String?>}extension CinemasSource {    /// The invented library names no such acts, and keeps no Bin inside Hidden.    func named(_ act: CinemasNamedAct, id: String?) async -> CinemasRead<String?> { .refused(CinemasWords.line("stream.could_not_load")) }    func binned(hidden: Bool) async -> CinemasRead<CinemasBin> {        hidden ? .refused(CinemasWords.line("stream.could_not_load")) : await binned()    }    /// A row's page with no filter chosen (All).    func row(_ id: String, after: String?) async -> CinemasRead<CinemasRowPage> { await row(id, after: after, filter: nil, hidden: false) }    func row(_ id: String, after: String?, filter: String?) async -> CinemasRead<CinemasRowPage> {        await row(id, after: after, filter: filter, hidden: false)    }    func title(table: String, id: String) async -> CinemasRead<CinemasTitle> { await title(table: table, id: id, hidden: false) }    func search(_ q: String) async -> CinemasRead<CinemasFound> { await search(q, hidden: false) }    func groups() async -> CinemasRead<CinemasGroups> { await groups(hidden: false) }}/// The core's calls.struct CinemasCoreSource: CinemasSource {    let core: any CottonCalling    private func read<Answer: Decodable & Sendable>(_ method: String, _ request: [String: JSONValue] = [:], as type: Answer.Type = Answer.self) async -> CinemasRead<Answer> {        do {            return .read(try await core.call(method, JSONValue.object(request), as: type))        } catch let error as CottonCallError {            Log.write("cinemas: \(method) refused — \(error.code)")            return .refused(error.message)        } catch {            Log.write("cinemas: \(method) did not read — \(error)")            return .refused(CinemasWords.line("stream.could_not_load"))        }    }    /// Send's calls: signed out (the core's `not_connected`) Send says so in Cinemas' words, as Android does.    private func readSend<Answer: Decodable & Sendable>(_ method: String, _ request: [String: JSONValue], as type: Answer.Type) async -> CinemasRead<Answer> {        do {            return .read(try await core.call(method, JSONValue.object(request), as: type))        } catch let error as CottonCallError {            Log.write("cinemas: \(method) refused — \(error.code)")            return .refused(error.code == "not_connected" ? CinemasWords.line("stream.send_sign_in") : error.message)        } catch {            Log.write("cinemas: \(method) did not read — \(error)")            return .refused(CinemasWords.line("stream.could_not_load"))        }    }    private func done(_ method: String, _ request: [String: JSONValue]) async -> CinemasRead<Bool> {        switch await read(method, request, as: JSONValue.self) {        case .read: .read(true)        case .refused(let line): .refused(line)        }    }    /// Home, with this phone's network: the core fetches Home's first pictures ahead only on Wi-Fi (or on mobile data    /// when films may use it), and never in Low Data Mode.    func home() async -> CinemasRead<CinemasHome> {        await read(CottonMethod.cinemasHome, ["network": .string(FilmNetwork.kind), "constrained": .bool(FilmNetwork.constrained)])    }    /// `request` with `hidden: true` when asked from inside Hidden; nothing added otherwise.    private func inside(_ request: [String: JSONValue], _ hidden: Bool) -> [String: JSONValue] {        var request = request        if hidden { request["hidden"] = .bool(true) }        return request    }    func row(_ id: String, after: String?, filter: String?, hidden: Bool) async -> CinemasRead<CinemasRowPage> {        var request: [String: JSONValue] = ["id": .string(id)]        if let after { request["after"] = .string(after) }        if let filter { request["filter"] = .string(filter) }        return await read(CottonMethod.cinemasRow, inside(request, hidden))    }    func title(table: String, id: String, hidden: Bool) async -> CinemasRead<CinemasTitle> {        await read(CottonMethod.cinemasTitle, inside(["table": .string(table), "id": .string(id)], hidden))    }    func season(_ id: String) async -> CinemasRead<CinemasSeason> { await read(CottonMethod.cinemasSeason, ["id": .string(id)]) }    func search(_ q: String, hidden: Bool) async -> CinemasRead<CinemasFound> {        await read(CottonMethod.cinemasSearch, inside(["q": .string(q)], hidden))    }    func groups(hidden: Bool) async -> CinemasRead<CinemasGroups> { await read(CottonMethod.cinemasGroups, inside([:], hidden)) }    func groups(holding item: CinemasItem, hidden: Bool) async -> CinemasRead<CinemasGroups> {        switch await title(table: item.table, id: item.id, hidden: hidden) {        case .read(let title):            return .read(CinemasGroups(groups: title.groups.map { .init(id: $0.id, name: $0.name, holds: $0.in, hidden: $0.hidden) }))        case .refused(let line): return .refused(line)        }    }    func hide(_ group: String, hidden: Bool) async -> CinemasRead<CinemasHid> {        await read(CottonMethod.cinemasHide, ["id": .string(group), "hidden": .bool(hidden)])    }    func hiddenPlace() async -> CinemasRead<CinemasHiddenPlace> { await read(CottonMethod.cinemasHidden) }    func undo(_ undo: CinemasHid.Undo) async -> CinemasRead<CinemasHid> {        // Exactly as handed back: the core named the method (today always cinemas.hide) and its args.        guard case .object(let args) = undo.args else { return .refused(CinemasWords.line("stream.could_not_load")) }        return await read(undo.method, args)    }    private struct Unlocked: Decodable, Sendable { var unlocked: Bool }    func unlock(noLock: Bool) async -> CinemasRead<Bool> {        switch await read(CottonMethod.cinemasUnlock, noLock ? ["no_lock": .bool(true)] : [:], as: Unlocked.self) {        case .read(let answer): return .read(answer.unlocked)        case .refused(let line): return .refused(line)        }    }    func lock() async -> CinemasRead<Bool> {        switch await read(CottonMethod.cinemasLock, as: Unlocked.self) {        case .read(let answer): return .read(!answer.unlocked)        case .refused(let line): return .refused(line)        }    }    func kind(_ item: CinemasItem, to kind: CinemasItem.Kind) async -> CinemasRead<String?> {        struct Said: Decodable, Sendable { var said: String? }        switch await read(CottonMethod.cinemasKind, ["id": .string(item.id), "to": .string(kind.rawValue)], as: Said.self) {        case .read(let answer): return .read(answer.said)        case .refused(let line): return .refused(line)        }    }    func orderGroups(_ order: [String]) async -> CinemasRead<Bool> {        await done(CottonMethod.cinemasGroupsOrder, ["order": .array(order.map(JSONValue.string))])    }    func group(_ group: String, item: CinemasItem, in add: Bool) async -> CinemasRead<Bool> {        await done(CottonMethod.groupsUpdate, ["id": .string(group), add ? "add" : "remove": .array([.string(item.id)])])    }    func makeGroup(_ name: String, with item: CinemasItem?) async -> CinemasRead<String> {        var request: [String: JSONValue] = ["table": .string("film"), "name": .string(name)]        if let item { request["records"] = .array([.string(item.id)]) }        struct Made: Decodable, Sendable {            struct Group: Decodable, Sendable { var id: String }            var group: Group?            var id: String?        }        switch await read(CottonMethod.groupsCreate, request, as: Made.self) {        case .read(let made): return .read(made.group?.id ?? made.id ?? "")        case .refused(let line): return .refused(line)        }    }    func moveGroup(_ group: String, earlier: Bool) async -> CinemasRead<Bool> {        await done(CottonMethod.groupsUpdate, ["id": .string(group), "move": .string(earlier ? "earlier" : "later")])    }    func renameGroup(_ group: String, to name: String) async -> CinemasRead<Bool> {        await done(CottonMethod.groupsUpdate, ["id": .string(group), "name": .string(name)])    }    /// A write whose answer carries `change.id`, for Undo.    private func change(_ method: String, _ request: [String: JSONValue]) async -> CinemasRead<String?> {        struct Changed: Decodable, Sendable {            struct Change: Decodable, Sendable { var id: String? }            var change: Change?        }        switch await read(method, request, as: Changed.self) {        case .read(let answer): return .read(answer.change?.id)        case .refused(let line): return .refused(line)        }    }    func deleteGroup(_ group: String) async -> CinemasRead<String?> {        await change(CottonMethod.groupsDelete, ["id": .string(group)])    }    func onPhone(free: Int64?) async -> CinemasRead<CinemasOnPhone> {        await read(CottonMethod.cinemasOnPhone, free.map { ["free_bytes": .number(Double($0))] } ?? [:])    }    private struct Knobs: Decodable, Sendable { var cellular: Bool }    func cellular() async -> CinemasRead<Bool> {        switch await read(CottonMethod.filmsKeeping, as: Knobs.self) {        case .read(let knobs): return .read(knobs.cellular)        case .refused(let line): return .refused(line)        }    }    func setCellular(_ on: Bool) async -> CinemasRead<Bool> {        switch await read(CottonMethod.filmsKeeping, ["cellular": .bool(on)], as: Knobs.self) {        case .read(let knobs): return .read(knobs.cellular)        case .refused(let line): return .refused(line)        }    }    func preparing(_ item: CinemasItem) async -> CinemasRead<CinemasPreparing> {        await read(CottonMethod.cinemasPreparing, ["table": .string(item.table), "id": .string(item.id)])    }    func remote(table: String, id: String, at: Double, length: Double?, device: String?) async -> CinemasRead<CinemasRemoteWords> {        var ask: [String: JSONValue] = ["table": .string(table), "id": .string(id), "at_s": .number(at)]        if let length, length.isFinite, length > 0 { ask["length_s"] = .number(length) }        if let device, !device.isEmpty { ask["device"] = .string(device) }        return await read(CottonMethod.cinemasRemote, ask)    }    func toEpisode(_ item: CinemasItem, series: String?, newSeries: String?, season: Int, episode: Int) async -> CinemasRead<Bool> {        var ask: [String: JSONValue] = ["id": .string(item.id), "season": .number(Double(season)), "episode": .number(Double(episode))]        if let series { ask["series"] = .string(series) } else if let newSeries { ask["series"] = .object(["new": .string(newSeries)]) }        return await done(CottonMethod.cinemasToEpisode, ask)    }    func binned() async -> CinemasRead<CinemasBin> { await read(CottonMethod.cinemasBin) }    func binned(hidden: Bool) async -> CinemasRead<CinemasBin> {        await read(CottonMethod.cinemasBin, hidden ? ["hidden": .bool(true)] : [:])    }    func you(free: Int64?) async -> CinemasRead<CinemasYou> {        await read(CottonMethod.cinemasYou, free.map { ["free_bytes": .number(Double($0))] } ?? [:])    }    func youAct(_ method: String, _ request: JSONValue?) async -> CinemasRead<Bool> {        guard case .object(let ask)? = request ?? .object([:]) else { return .refused(CinemasWords.line("stream.could_not_load")) }        return await done(method, ask)    }    func named(_ act: CinemasNamedAct, id: String?) async -> CinemasRead<String?> {        struct Said: Decodable, Sendable { var said: String? }        var request = act.args        if let id { request["id"] = .string(id) }        switch await read(act.method, request, as: Said.self) {        case .read(let answer): return .read(answer.said)        case .refused(let line): return .refused(line)        }    }    func restore(_ item: CinemasItem) async -> CinemasRead<String?> {        struct Said: Decodable, Sendable { var said: String? }        switch await read(CottonMethod.cinemasRestore, ["id": .string(item.id)], as: Said.self) {        case .read(let answer): return .read(answer.said)        case .refused(let line): return .refused(line)        }    }    func sendStep(_ item: CinemasItem) async -> CinemasRead<SendStep> {        struct Answer: Decodable, Sendable { var step: SendStep }        switch await readSend(CottonMethod.shellOpened, ["table": .string(item.table), "id": .string(item.id), "step": .string("send")], as: Answer.self) {        case .read(let answer): return .read(answer.step)        case .refused(let line): return .refused(line)        }    }    func send(_ item: CinemasItem, to person: SendPerson) async -> CinemasRead<CinemasSent> {        struct Made: Decodable, Sendable {            var id: String            var receipt: Receipt?            struct Receipt: Decodable, Sendable { var words: String; var undo: String?; var undone: String? }        }        let ask: [String: JSONValue] = ["table": .string(item.table), "id": .string(item.id), "to": .string(person.value), "name": .string(person.words)]        switch await readSend(CottonMethod.sendMake, ask, as: Made.self) {        case .read(let made): return .read(CinemasSent(id: made.id, words: made.receipt?.words, undo: made.receipt?.undo, undone: made.receipt?.undone))        case .refused(let line): return .refused(line)        }    }    func unsend(_ id: String) async -> CinemasRead<Bool> {        await done(CottonMethod.sendUndo, ["id": .string(id)])    }    func subtitles(_ item: CinemasItem) async -> CinemasRead<CinemasSubtitles> {        await read(CottonMethod.cinemasSubtitles, ["table": .string(item.table), "id": .string(item.id)])    }    func subtitlesAct(_ act: String, item: CinemasItem, file: URL?) async -> CinemasRead<String?> {        struct Said: Decodable, Sendable { var said: String? }        let named: [String: JSONValue] = ["table": .string(item.table), "id": .string(item.id)]        switch act {        case "find", "make":            let command = act == "find" ? "find_subtitles" : "generate_subtitles"            switch await read("records.command", named.merging(["command": .string(command)]) { $1 }, as: JSONValue.self) {            case .read: return .read(nil)            case .refused(let line): return .refused(line)            }        case "give":            guard let file else { return .read(nil) }            switch await read(CottonMethod.filmsSubtitleFile, named.merging(["path": .string(file.path)]) { $1 }, as: Said.self) {            case .read(let said): return .read(said.said)            case .refused(let line): return .refused(line)            }        default:            return .read(nil)        }    }    func mark(_ item: CinemasItem, watched: Bool) async -> CinemasRead<String?> {        struct Said: Decodable, Sendable { var said: String? }        switch await read("films.mark", ["table": .string(item.table), "id": .string(item.id), "watched": .bool(watched)], as: Said.self) {        case .read(let answer): return .read(answer.said)        case .refused(let line): return .refused(line)        }    }    func bin(_ item: CinemasItem) async -> CinemasRead<String?> {        await change("records.delete", ["table": .string(item.table), "id": .string(item.id)])    }    func undo(_ change: String) async -> CinemasRead<Bool> {        await done(CottonMethod.recordsUndo, ["change_id": .string(change)])    }}