// 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 CottonKit import Foundation protocol CinemasSource: Sendable { func home() async -> CinemasRead /// `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 func title(table: String, id: String, hidden: Bool) async -> CinemasRead func season(_ id: String) async -> CinemasRead func search(_ q: String, hidden: Bool) async -> CinemasRead func groups(hidden: Bool) async -> CinemasRead /// 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 /// `cinemas.hide {id, hidden}`: a category hidden, or brought back; the core's words for it. func hide(_ group: String, hidden: Bool) async -> CinemasRead /// 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 /// `cinemas.hidden {}`: the hidden place. Without the core's unlock it answers locked, with no rows. func hiddenPlace() async -> CinemasRead /// `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 /// `cinemas.lock {}`: Hidden shut, on leaving it and when the app leaves the screen. func lock() async -> CinemasRead /// 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 /// His groups in his order, the rows' order on Home: `cinemas.groupsOrder {order}`. func orderGroups(_ order: [String]) async -> CinemasRead /// 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 /// `groups.create {table: "film", name, records?}`: the new group's id. func makeGroup(_ name: String, with item: CinemasItem?) async -> CinemasRead /// `groups.update {id, move: "earlier" | "later"}`. func moveGroup(_ group: String, earlier: Bool) async -> CinemasRead func renameGroup(_ group: String, to name: String) async -> CinemasRead /// `groups.delete {id}`: the change Undo takes back (the films stay). func deleteGroup(_ group: String) async -> CinemasRead /// `films.mark {table, id, watched}`: the core's own words for it, when it says any. func mark(_ item: CinemasItem, watched: Bool) async -> CinemasRead /// `records.delete {table, id}`: to the Bin; the change Undo takes back. func bin(_ item: CinemasItem) async -> CinemasRead /// `cinemas.you {free_bytes}`: You's sections. func you(free: Int64?) async -> CinemasRead /// 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 /// `cinemas.bin {}`: what waits in the Bin, each with its line ("Moved to the Bin today"). func binned() async -> CinemasRead /// `cinemas.restore {id}`: back out of the Bin; the core's words for it. func restore(_ item: CinemasItem) async -> CinemasRead /// 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 /// `cinemas.bin {hidden: true}`: inside Hidden, the hidden titles' own Bin (core 4). func binned(hidden: Bool) async -> CinemasRead /// `records.undo {change_id}`. func undo(_ change: String) async -> CinemasRead /// `cinemas.onPhone {free_bytes}`. func onPhone(free: Int64?) async -> CinemasRead /// Whether downloads may use mobile data: `films.keeping {}`'s `cellular`. func cellular() async -> CinemasRead /// `films.keeping {cellular}`: the rule as it now stands. func setCellular(_ on: Bool) async -> CinemasRead /// `cinemas.preparing {table, id}`. func preparing(_ item: CinemasItem) async -> CinemasRead /// `cinemas.remote {table, id, at_s, length_s, device}`. func remote(table: String, id: String, at: Double, length: Double?, device: String?) async -> CinemasRead /// `cinemas.toEpisode {id, series: | {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 /// 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 /// `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 /// `send.undo {id}`: a send taken back while it is not yet kept. func unsend(_ id: String) async -> CinemasRead /// `cinemas.subtitles {table, id}`. func subtitles(_ item: CinemasItem) async -> CinemasRead /// 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 } extension CinemasSource { /// The invented library names no such acts, and keeps no Bin inside Hidden. func named(_ act: CinemasNamedAct, id: String?) async -> CinemasRead { .refused(CinemasWords.line("stream.could_not_load")) } func binned(hidden: Bool) async -> CinemasRead { 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 { await row(id, after: after, filter: nil, hidden: false) } func row(_ id: String, after: String?, filter: String?) async -> CinemasRead { await row(id, after: after, filter: filter, hidden: false) } func title(table: String, id: String) async -> CinemasRead { await title(table: table, id: id, hidden: false) } func search(_ q: String) async -> CinemasRead { await search(q, hidden: false) } func groups() async -> CinemasRead { await groups(hidden: false) } } /// The core's calls. struct CinemasCoreSource: CinemasSource { let core: any CottonCalling private func read(_ method: String, _ request: [String: JSONValue] = [:], as type: Answer.Type = Answer.self) async -> CinemasRead { 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(_ method: String, _ request: [String: JSONValue], as type: Answer.Type) async -> CinemasRead { 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 { 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 { 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 { 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 { await read(CottonMethod.cinemasTitle, inside(["table": .string(table), "id": .string(id)], hidden)) } func season(_ id: String) async -> CinemasRead { await read(CottonMethod.cinemasSeason, ["id": .string(id)]) } func search(_ q: String, hidden: Bool) async -> CinemasRead { await read(CottonMethod.cinemasSearch, inside(["q": .string(q)], hidden)) } func groups(hidden: Bool) async -> CinemasRead { await read(CottonMethod.cinemasGroups, inside([:], hidden)) } func groups(holding item: CinemasItem, hidden: Bool) async -> CinemasRead { 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 { await read(CottonMethod.cinemasHide, ["id": .string(group), "hidden": .bool(hidden)]) } func hiddenPlace() async -> CinemasRead { await read(CottonMethod.cinemasHidden) } func undo(_ undo: CinemasHid.Undo) async -> CinemasRead { // 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 { 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 { 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 { 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 { await done(CottonMethod.cinemasGroupsOrder, ["order": .array(order.map(JSONValue.string))]) } func group(_ group: String, item: CinemasItem, in add: Bool) async -> CinemasRead { await done(CottonMethod.groupsUpdate, ["id": .string(group), add ? "add" : "remove": .array([.string(item.id)])]) } func makeGroup(_ name: String, with item: CinemasItem?) async -> CinemasRead { 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 { await done(CottonMethod.groupsUpdate, ["id": .string(group), "move": .string(earlier ? "earlier" : "later")]) } func renameGroup(_ group: String, to name: String) async -> CinemasRead { 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 { 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 { await change(CottonMethod.groupsDelete, ["id": .string(group)]) } func onPhone(free: Int64?) async -> CinemasRead { await read(CottonMethod.cinemasOnPhone, free.map { ["free_bytes": .number(Double($0))] } ?? [:]) } private struct Knobs: Decodable, Sendable { var cellular: Bool } func cellular() async -> CinemasRead { 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 { 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 { 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 { 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 { 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 { await read(CottonMethod.cinemasBin) } func binned(hidden: Bool) async -> CinemasRead { await read(CottonMethod.cinemasBin, hidden ? ["hidden": .bool(true)] : [:]) } func you(free: Int64?) async -> CinemasRead { await read(CottonMethod.cinemasYou, free.map { ["free_bytes": .number(Double($0))] } ?? [:]) } func youAct(_ method: String, _ request: JSONValue?) async -> CinemasRead { 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 { 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 { 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 { 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 { 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 { await done(CottonMethod.sendUndo, ["id": .string(id)]) } func subtitles(_ item: CinemasItem) async -> CinemasRead { await read(CottonMethod.cinemasSubtitles, ["table": .string(item.table), "id": .string(item.id)]) } func subtitlesAct(_ act: String, item: CinemasItem, file: URL?) async -> CinemasRead { 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 { 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 { await change("records.delete", ["table": .string(item.table), "id": .string(item.id)]) } func undo(_ change: String) async -> CinemasRead { await done(CottonMethod.recordsUndo, ["change_id": .string(change)]) } }