Cotton code
744 lines · 47.0 KB · SwiftRaw
// AN INVENTED LIBRARY, Dev builds only: made-up titles with drawn posters, answered in CONTRACT-2's shapes, so every// screen can be walked before the core's `cinemas.*` calls land and with nothing of the owner's. Asked for with the// launch argument `-cinemas-invent` (or `COTTON_CINEMAS_INVENT=1`); `-cinemas-invent-empty` gives an empty library, and// `-cinemas-invent-hard` a library as a real one can be: 400 more films, a title of 90 characters, and one named from a// bare MKV file, with no picture, year or length.// Its words stand in for the core's answers and go when the calls land; it is compiled out of every real build.#if COTTON_DEVimport Foundationactor CinemasInvented: CinemasSource {    /// You's switches and subtitle language, as `cinemas.setting` keeps them.    private var settings: [String: Bool] = ["autoplay_next": true, "subtitles_on": false, "cellular": false]    private var language: String?    /// What he moved to the Bin, newest first.    private var inBin: [Entry] = []    /// What the Mac was asked about a title's subtitles: find, make or give.    private var subtitleWork: [String: String] = [:]    static var asked: Bool {        let arguments = ProcessInfo.processInfo.arguments        return arguments.contains("-cinemas-invent") || arguments.contains("-cinemas-invent-empty") || arguments.contains("-cinemas-invent-hard")            || ProcessInfo.processInfo.environment["COTTON_CINEMAS_INVENT"] == "1"    }    static var empty: Bool { ProcessInfo.processInfo.arguments.contains("-cinemas-invent-empty") }    static var hard: Bool { ProcessInfo.processInfo.arguments.contains("-cinemas-invent-hard") }    private struct Entry {        var item: CinemasItem        var added: Int        var watchedAt: Int?        var synopsis: String        var facts: [String]        var seasons: [(id: String, number: Int, episodes: [(title: String, minutes: Int, progress: Double?)])] = []        var source: CinemasTitle.Source?    }    private var entries: [Entry]    private var groupList: [(id: String, name: String, members: [String])]    /// His hidden categories (CONTRACT-2 HIDDEN): a title in any of them is hidden.    private var hiddenGroups: Set<String> = []    private var made = 0    init(empty: Bool = CinemasInvented.empty) {        entries = empty ? [] : Self.library() + (Self.hard ? Self.hardLibrary() : [])        groupList = empty ? [] : [            ("g-sundays", "Rainy Sundays", ["f-ferry", "f-lantern", "f-orchard", "s-lowmarsh", "f-tidewater"]),            ("g-kids", "With the children", ["f-kite", "f-paper", "f-moonbus", "f-lantern"]),            ("g-again", "Watch again", ["f-salt", "f-ferry", "f-glass", "f-copper"]),        ]    }    // ── the library ────────────────────────────────────────────────────    private static func library() -> [Entry] {        func film(_ id: String, _ title: String, _ year: String, _ minutes: Int, added: Int, progress: Double? = nil,                  watchedAt: Int? = nil, onPhone: CinemasItem.OnPhone? = nil, preparing: Bool = false, from: String? = nil,                  kind: CinemasItem.Kind = .film, facts: [String] = [], synopsis: String) -> Entry {            Entry(item: CinemasItem(table: "film", id: id, title: title, year: year, kind: kind, poster: "drawn:\(id)",                                    backdrop: "drawn:\(id):wide", progress: progress, onPhone: onPhone, preparing: preparing,                                    from: from, minutes: minutes),                  added: added, watchedAt: watchedAt, synopsis: synopsis,                  facts: [year] + (kind == .series ? [] : [minutes < 60 ? "\(minutes)m" : "\(minutes / 60)h \(minutes % 60)m"]) + facts,                  source: kind == .clip ? CinemasTitle.Source(url: "https://example.com/watch/\(id)", by: "Harbour Films") : nil)        }        var all: [Entry] = [            film("f-ferry", "Night Ferry", "2019", 124, added: 40, progress: 0.58, watchedAt: 1, onPhone: .kept, facts: ["4K HDR", "Malayalam"],                 synopsis: "A ferry pilot on the last crossing of the year finds a stowaway who knows the river better than she does."),            film("f-salt", "The Salt Road", "2016", 108, added: 60, facts: ["HD", "English"],                 synopsis: "Two brothers drive a truck of salt across a country that has stopped wanting it."),            film("f-lantern", "Lantern Street", "2021", 97, added: 3, facts: ["4K", "Hindi"],                 synopsis: "A lamp-maker's daughter keeps her father's shop open for one more monsoon."),            film("f-orchard", "The Quiet Orchard", "2014", 131, added: 90, progress: 0.21, watchedAt: 4, facts: ["HD", "French"],                 synopsis: "An old gardener teaches a runaway how to wait for fruit."),            film("f-kite", "Kite Season", "2022", 88, added: 5, onPhone: .keeping, facts: ["4K", "Tamil"],                 synopsis: "A village's children build the biggest kite anyone has seen, and the wind has opinions."),            film("f-glass", "Glasshouse", "2018", 115, added: 120, facts: ["HD", "Korean"],                 synopsis: "A botanist's greenhouse becomes the only warm place in a city that has lost its power."),            film("f-copper", "Copper Bells", "2012", 102, added: 200, facts: ["HD", "English"],                 synopsis: "A bell-founder's apprentice casts one bell too many."),            film("f-paper", "Paper Boats", "2020", 79, added: 14, from: "Priya", facts: ["HD", "Bengali"],                 synopsis: "After the floods, a boy sends paper boats downstream with letters to his sister."),            film("f-moonbus", "The Moon Bus", "2023", 92, added: 1, preparing: true, facts: ["4K"],                 synopsis: "The night bus to the coast stops at a station that is not on any map."),            film("f-tidewater", "Tidewater", "2017", 119, added: 75, progress: 0.82, watchedAt: 9, facts: ["HD", "English"],                 synopsis: "A lighthouse keeper's last week, told by the lighthouse."),            film("f-marble", "Marble Hours", "2011", 126, added: 300, facts: ["HD", "Italian"],                 synopsis: "A sculptor has one summer to finish a statue the town has already paid for."),            film("f-ember", "Ember & Ash", "2015", 111, added: 150, facts: ["HD", "Spanish"],                 synopsis: "A forest firefighter and the arsonist she is sure she has met before."),            film("f-northline", "Northline", "2024", 134, added: 2, from: "Arjun", facts: ["4K HDR", "Norwegian"],                 synopsis: "A train crew snowed in for nine days at the top of the world."),            film("f-velvet", "Velvet Matinee", "2010", 96, added: 400, facts: ["HD", "English"],                 synopsis: "The last projectionist of a grand old cinema runs one final show for an audience of three."),            film("f-cedar", "Under the Cedar", "2019", 101, added: 25, facts: ["HD", "Japanese"],                 synopsis: "Three generations, one tree, and a wedding nobody planned."),            film("f-harbour", "Harbour of Small Lights", "2013", 93, added: 33, onPhone: .kept, facts: ["HD"],                 synopsis: "Fishing boats come home at dusk; one does not."),            film("c-bread", "How a loaf of rye is made", "2025", 14, added: 6, kind: .clip,                 synopsis: "A baker's morning, start to finish."),            film("c-tram", "The last tram through the old town", "2024", 22, added: 11, progress: 0.4, watchedAt: 6, kind: .clip,                 synopsis: "A ride from depot to depot on the line's final night."),            film("c-loom", "Weaving on a hand loom", "2023", 9, added: 45, kind: .clip,                 synopsis: "A short film about a craft that takes a lifetime."),        ]        var lowmarsh = film("s-lowmarsh", "Lowmarsh", "2021", 52, added: 8, progress: 0.35, watchedAt: 2, kind: .series,                            facts: ["2 seasons", "English"],                            synopsis: "A small-town constable and the marsh that keeps giving back what it took.")        lowmarsh.item.caption = "S1 E4"        lowmarsh.seasons = [            ("s-lowmarsh-1", 1, [("The Reed Cutter", 52, 1), ("High Water", 49, 1), ("The Ferryman's Coat", 55, 1),                                 ("What the Fog Said", 51, 0.35), ("Eel Night", 50, nil), ("The Long Causeway", 58, nil)]),            ("s-lowmarsh-2", 2, [("Spring Tide", 54, nil), ("The Second Bell", 50, nil), ("Peat", 47, nil), ("Salt in the Wound", 56, nil)]),        ]        var orbit = film("s-orbit", "Small Orbit", "2023", 28, added: 18, kind: .series, facts: ["1 season", "English"],                         synopsis: "Six friends share a flat above a planetarium.")        orbit.seasons = [("s-orbit-1", 1, [("Pilot Light", 27, nil), ("Retrograde", 29, nil), ("Perigee", 26, nil)])]        var hollow = film("s-hollow", "The Hollow Atlas", "2020", 61, added: 210, onPhone: .kept, kind: .series,                          facts: ["1 season", "German"], synopsis: "A cartographer maps a valley that changes every night.")        hollow.seasons = [("s-hollow-1", 1, [("Contour", 60, nil), ("Legend", 63, nil), ("Scale", 58, nil), ("North", 66, nil)])]        all += [lowmarsh, orbit, hollow]        return all    }    /// What a real library holds that a tidy one does not: a film named from a bare MKV (no picture, year, length or    /// art), a 90-character title, and 400 more films, so a row opened pages through all of them.    private static func hardLibrary() -> [Entry] {        var hard = [            Entry(item: CinemasItem(table: "film", id: "f-mkv", title: "glass harbour 1080p bluray x264", kind: .film),                  added: 0, watchedAt: nil, synopsis: "", facts: []),            Entry(item: CinemasItem(table: "film", id: "f-long",                                    title: "The Extraordinarily Long and Winding Night Journey of the Lighthouse Keeper's Daughter",                                    year: "2018", kind: .film, poster: "drawn:f-long", backdrop: "drawn:f-long:wide", progress: 0.3, minutes: 151),                  added: 1, watchedAt: 3, synopsis: "A title as long as some real ones are, to see where it wraps.", facts: ["2018", "2h 31m"]),        ]        // Titles as his are named: in Telugu and Hindi (both invented here), from a dotted file, and a series the        // importer made before any episode came.        hard += [            Entry(item: CinemasItem(table: "film", id: "f-telugu", title: "వెన్నెల దారి", year: "2021", kind: .film, poster: "drawn:f-telugu", minutes: 142),                  added: 2, watchedAt: nil, synopsis: "An invented Telugu title.", facts: ["2021", "2h 22m", "Telugu"]),            Entry(item: CinemasItem(table: "film", id: "f-hindi", title: "चाँदनी की सड़क", year: "2017", kind: .film, poster: "drawn:f-hindi", minutes: 128),                  added: 3, watchedAt: nil, synopsis: "An invented Hindi title.", facts: ["2017", "2h 8m", "Hindi"]),            Entry(item: CinemasItem(table: "film", id: "f-dots", title: "the.paper.orchard.2019.720p.web", kind: .film, poster: "drawn:f-dots"),                  added: 4, watchedAt: nil, synopsis: "", facts: []),            Entry(item: CinemasItem(table: "film", id: "s-empty", title: "Harbour Lights", year: "2024", kind: .series, poster: "drawn:s-empty"),                  added: 5, watchedAt: nil, synopsis: "A series whose episodes have not come in yet.", facts: ["2024"]),        ]        let first = ["Amber", "Quiet", "Northern", "Salt", "Paper", "Hollow", "Copper", "Glass", "Winter", "Velvet"]        let second = ["Harbour", "Lanterns", "Orchard", "Crossing", "Station", "Tides", "Road", "Fields", "Bridge", "Signal"]        for n in 0..<400 {            let title = "\(first[n % 10]) \(second[(n / 10) % 10]) \(n / 100 + 1)"            let year = "\(1970 + n % 55)"            let minutes = 80 + n % 70            hard.append(Entry(item: CinemasItem(table: "film", id: "f-gen-\(n)", title: title, year: year, kind: .film,                                                poster: "drawn:f-gen-\(n)", backdrop: "drawn:f-gen-\(n):wide", minutes: minutes),                              added: 300 + n, watchedAt: nil, synopsis: "One of four hundred invented films.",                              facts: [year, "\(minutes / 60)h \(minutes % 60)m"]))        }        return hard    }    private func entry(_ id: String) -> Entry? { entries.first { $0.item.id == id } }    // ── hidden, as the core filters it ─────────────────────────────────    /// Titles in any hidden category; an episode is hidden with its series.    private var hiddenTitles: Set<String> {        Set(groupList.filter { hiddenGroups.contains($0.id) }.flatMap(\.members))    }    private func isHidden(_ id: String) -> Bool {        let hidden = hiddenTitles        if hidden.contains(id) { return true }        // An episode ("<season>-e<n>") or a season of a hidden series.        return entries.contains { entry in hidden.contains(entry.item.id) && entry.seasons.contains { id.hasPrefix($0.id) } }    }    /// The categories that show here: open ones outside Hidden, every one inside it.    private func shownGroups(_ hidden: Bool) -> [(id: String, name: String, members: [String])] {        hidden ? groupList : groupList.filter { !hiddenGroups.contains($0.id) }    }    private func items(_ filter: (Entry) -> Bool, by order: (Entry, Entry) -> Bool = { $0.added < $1.added }) -> [CinemasItem] {        entries.filter(filter).sorted(by: order).map(\.item)    }    /// A row's titles: outside Hidden without hidden titles (and no hidden category's row at all); inside it, hidden    /// titles alone, and any category's row.    private func rowItems(_ id: String, hidden: Bool = false) -> (String, [CinemasItem])? {        guard let found = allRowItems(id), hidden || !id.hasPrefix("group:") || !hiddenGroups.contains(String(id.dropFirst(6))) else { return nil }        let secret = hiddenTitles        if id.hasPrefix("group:") && hidden { return found }        return (found.0, found.1.filter { hidden == secret.contains($0.id) })    }    private func allRowItems(_ id: String) -> (String, [CinemasItem])? {        switch id {        case "carry_on":            return ("Carry on", items({ $0.item.progress != nil }, by: { ($0.watchedAt ?? 0) < ($1.watchedAt ?? 0) }))        case "recent": return ("Recently added", items({ $0.added <= 30 }))        case "films": return ("Films", items({ $0.item.kind == .film }))        case "series": return ("Series", items({ $0.item.kind == .series }))        case "videos": return ("Videos", items({ $0.item.kind == .clip }))        case "on_phone": return ("On this phone", items({ $0.item.onPhone != nil }))        case "getting_ready": return ("Getting ready on your Mac", items({ $0.item.preparing }))        case "from_friends": return ("From friends", items({ $0.item.from != nil }))        default:            guard id.hasPrefix("group:"), let group = groupList.first(where: { "group:\($0.id)" == id }) else { return nil }            return (group.name, group.members.compactMap { entry($0)?.item })        }    }    // ── the calls ──────────────────────────────────────────────────────    func home() async -> CinemasRead<CinemasHome> {        try? await Task.sleep(for: .milliseconds(450))        guard !entries.isEmpty else {            return .read(CinemasHome(featured: nil, rows: [], empty: CinemasHome.Empty(                title: "Your films will live here.", line: "Add films from Files, a folder, or by name.", add: "Add films")))        }        let secret = hiddenTitles        let open = entries.filter { !secret.contains($0.item.id) }        let featured = open.filter { $0.watchedAt != nil }.min { ($0.watchedAt ?? 0) < ($1.watchedAt ?? 0) }            ?? open.min { $0.added < $1.added }        var rows: [CinemasHome.Row] = []        for id in ["carry_on", "recent", "films", "series", "videos", "on_phone", "getting_ready", "from_friends"]            + shownGroups(false).map({ "group:\($0.id)" }) {            guard let found = rowItems(id) else { continue }            let (title, items) = found            let group = id.hasPrefix("group:") ? String(id.dropFirst(6)) : nil            if items.isEmpty && group == nil { continue }            rows.append(CinemasHome.Row(id: id, title: title, group: group, count: items.count,                                        items: Array(items.prefix(20)), more: items.count > 20))        }        return .read(CinemasHome(            featured: featured.map { entry in                CinemasHome.Featured(item: entry.item, line: line(entry), play: entry.item.progress == nil ? "Play" : "Resume", tv: "Play on TV")            },            rows: rows, empty: nil))    }    private func line(_ entry: Entry) -> String {        let item = entry.item        if let progress = item.progress, let minutes = item.minutes {            let at = Int(Double(minutes) * progress)            return "\(item.caption.map { "\($0) · " } ?? "")\(at / 60):\(String(format: "%02d", at % 60)) of \(minutes / 60):\(String(format: "%02d", minutes % 60))"        }        return entry.facts.prefix(3).joined(separator: " · ")    }    /// A row opened, 60 at a time as the core pages it: `next` names the last title of the page.    func row(_ id: String, after: String?, filter: String?, hidden: Bool) async -> CinemasRead<CinemasRowPage> {        if hidden && !unlocked { return .refused(Self.shut) }        guard let found = rowItems(id, hidden: hidden) else { return .refused("That row is gone.") }        let filter = filter ?? "all"        var titles = found.1        switch filter {        case "unwatched": titles = titles.filter { ($0.progress ?? 0) < 0.95 }        case "on_phone": titles = titles.filter { $0.onPhone != nil }        case "az": titles.sort { $0.title.lowercased() < $1.title.lowercased() }        case "newest":            let added = Dictionary(entries.map { ($0.item.id, $0.added) }, uniquingKeysWith: { a, _ in a })            titles.sort { (added[$0.id] ?? 0) < (added[$1.id] ?? 0) }        default: break        }        let start = after.flatMap { last in titles.firstIndex { $0.id == last }.map { $0 + 1 } } ?? 0        let page = Array(titles.dropFirst(start).prefix(60))        let more = start + page.count < titles.count        let chips = [("all", "All"), ("unwatched", "Not watched"), ("on_phone", "On this phone"), ("az", "A–Z"), ("newest", "Newest")]            .map { CinemasRowPage.Chip(id: $0.0, label: $0.1, on: $0.0 == filter) }        return .read(CinemasRowPage(title: found.0, items: page, next: more ? page.last?.id : nil, count: titles.count, chips: chips, filter: filter))    }    func title(table: String, id: String, hidden: Bool) async -> CinemasRead<CinemasTitle> {        try? await Task.sleep(for: .milliseconds(120))        if hidden && !unlocked { return .refused(Self.shut) }        // Outside Hidden a hidden title is not there at all, as the core's `not_found` says.        if !hidden && isHidden(id) { return .refused("That title is no longer here.") }        if table == "film_episode" { return episodeTitle(id, hidden: hidden) }        guard let entry = entry(id) else { return .refused("That title is no longer here.") }        let item = entry.item        let play: CinemasTitle.Play        if item.preparing {            play = .init(label: "Plays once your Mac is done", fromStart: nil)        } else if let progress = item.progress, let minutes = item.minutes {            let at = Int(Double(minutes) * progress)            play = .init(label: item.kind == .series ? "Resume \(item.caption ?? "")" : "Resume \(at / 60):\(String(format: "%02d", at % 60))",                         fromStart: "Play from the start")        } else {            play = .init(label: item.kind == .series ? "Play S1 E1" : "Play", fromStart: nil)        }        // As the core places them (67ab8967cd): keeping, the page, a group, sending and subtitles in the row; what it is,        // watched and the Bin under More.        var acts: [CinemasTitle.Act] = [            item.onPhone == nil ? .init(id: "keep", label: "Keep on this phone", short: "Keep", place: "row", second: "2.3 GB")                : .init(id: "remove_download", label: "Remove download", short: "Remove", place: "row", second: "2.3 GB"),        ]        if entry.source != nil { acts.append(.init(id: "open_page", label: "Open the page", short: "Open the page", place: "row")) }        acts += [.init(id: "group", label: "Add to a category", short: "Add to category", place: "row"),                 .init(id: "send", label: "Send to a friend", short: "Send", place: "row")]        if item.kind != .clip { acts.append(.init(id: "subtitles", label: "Subtitles", short: "Subtitles", place: "row", second: "English")) }        acts += [.init(id: "kind", label: "What it is", place: "more"), .init(id: "mark_watched", label: "Mark watched", place: "more"),                 .init(id: "bin", label: "Move to the Bin", place: "more")]        return .read(CinemasTitle(            item: item, synopsis: entry.synopsis, facts: entry.facts, play: play, tv: "Play on TV", acts: acts,            groups: titleGroups(id, hidden: hidden),            subtitles: item.kind == .clip ? nil : .init(line: item.preparing ? "Waiting for your Mac" : "English · Ready", work: nil),            preparing: item.preparing ? .init(line: "Your Mac is getting it ready") : nil,            seasons: entry.seasons.isEmpty ? nil : entry.seasons.map { season in                let watched = season.episodes.filter { $0.progress == 1 }.count                return .init(id: season.id, number: season.number, title: nil, episodes: season.episodes.count, watched: watched)            },            source: entry.source))    }    private func titleGroups(_ id: String, hidden: Bool) -> [CinemasTitle.Group] {        shownGroups(hidden).map { .init(id: $0.id, name: $0.name, in: $0.members.contains(id), hidden: hidden ? hiddenGroups.contains($0.id) : nil) }    }    private func episodeTitle(_ id: String, hidden: Bool) -> CinemasRead<CinemasTitle> {        for entry in entries {            for season in entry.seasons {                for (index, episode) in season.episodes.enumerated() where "\(season.id)-e\(index + 1)" == id {                    let item = episodeItem(entry, season.id, season.number, index, episode)                    return .read(CinemasTitle(                        item: item, synopsis: entry.synopsis, facts: ["S\(season.number) E\(index + 1)", "\(episode.minutes)m"],                        play: .init(label: "Play S\(season.number) E\(index + 1)", fromStart: nil), tv: "Play on TV",                        acts: [.init(id: "keep", label: "Keep on this phone"), .init(id: "group", label: "Add to a category"),                               .init(id: "mark_watched", label: "Mark watched")],                        groups: titleGroups(id, hidden: hidden),                        subtitles: .init(line: "English · Ready", work: nil), preparing: nil, seasons: nil, source: nil))                }            }        }        return .refused("That episode is no longer here.")    }    private func episodeItem(_ entry: Entry, _ seasonID: String, _ number: Int, _ index: Int,                             _ episode: (title: String, minutes: Int, progress: Double?)) -> CinemasItem {        CinemasItem(table: "film_episode", id: "\(seasonID)-e\(index + 1)", title: episode.title, year: entry.item.year, kind: .episode,                    poster: "drawn:\(entry.item.id)", backdrop: "drawn:\(seasonID)-e\(index + 1):wide", caption: "S\(number) E\(index + 1)",                    progress: episode.progress.flatMap { $0 >= 1 ? nil : $0 }, onPhone: entry.item.onPhone, minutes: episode.minutes)    }    func season(_ id: String) async -> CinemasRead<CinemasSeason> {        try? await Task.sleep(for: .milliseconds(150))        for entry in entries {            guard let season = entry.seasons.first(where: { $0.id == id }) else { continue }            return .read(CinemasSeason(                season: .init(id: season.id, number: season.number, title: nil),                episodes: season.episodes.enumerated().map { index, episode in                    {                        var shown = CinemasSeason.Episode(item: episodeItem(entry, season.id, season.number, index, episode), number: index + 1,                                                          title: episode.title, minutes: episode.minutes, still: "drawn:\(season.id)-e\(index + 1):wide",                                                          synopsis: entry.synopsis)                        // The core's words for where he is in it.                        switch episode.progress {                        case let done? where done >= 1: shown.stateLine = "watched"                        case let part? where part > 0: shown.stateLine = "\(Int(Double(episode.minutes) * (1 - part))) min left"                        default: break                        }                        return shown                    }()                }))        }        return .refused("That season is no longer here.")    }    /// Outside Hidden, never a hidden title or a hidden category's name; inside it, those alone.    func search(_ q: String, hidden: Bool) async -> CinemasRead<CinemasFound> {        if hidden && !unlocked { return .refused(Self.shut) }        let words = q.lowercased().split(separator: " ")        guard !words.isEmpty else { return .read(CinemasFound(items: [], groups: [])) }        let secret = hiddenTitles        let found = entries.filter { entry in secret.contains(entry.item.id) == hidden && words.allSatisfy { entry.item.title.lowercased().contains($0) } }.map(\.item)        let groups = groupList.filter { group in hiddenGroups.contains(group.id) == hidden && words.allSatisfy { group.name.lowercased().contains($0) } }        let top = found.first.map { [$0.kind == .series ? "Series" : $0.kind == .clip ? "Video" : "Film", $0.year].compactMap { $0 }.joined(separator: " · ") }        return .read(CinemasFound(items: found, groups: groups.map { .init(id: $0.id, name: $0.name) }, topLine: top))    }    /// Outside Hidden the open categories; inside it, the hidden ones.    func groups(hidden: Bool) async -> CinemasRead<CinemasGroups> {        let secret = hiddenTitles        // An open category's count leaves its hidden titles out, as every count outside Hidden does.        return .read(CinemasGroups(groups: groupList.filter { hiddenGroups.contains($0.id) == hidden }            .map { .init(id: $0.id, name: $0.name, count: hidden ? $0.members.count : $0.members.filter { !secret.contains($0) }.count,                         hidden: hidden ? true : nil) }))    }    /// As `cinemas.title`'s groups: open ones outside Hidden, every one inside it.    func groups(holding item: CinemasItem, hidden: Bool) async -> CinemasRead<CinemasGroups> {        .read(CinemasGroups(groups: titleGroups(item.id, hidden: hidden).map { .init(id: $0.id, name: $0.name, holds: $0.in, hidden: $0.hidden) }))    }    func hide(_ group: String, hidden: Bool) async -> CinemasRead<CinemasHid> { hide(group, hidden: hidden, token: nil) }    /// As the core: hiding is done anywhere; Stop hiding only with Hidden open, or once by the token a Hide handed back.    private func hide(_ group: String, hidden: Bool, token: String?) -> CinemasRead<CinemasHid> {        guard let found = groupList.first(where: { $0.id == group }) else { return .refused("That category is gone.") }        if !hidden {            let spent = token != nil && undoTokens.removeValue(forKey: group) == token            guard spent || unlocked else { return .refused(Self.shut) }        }        if hidden { hiddenGroups.insert(group) } else { hiddenGroups.remove(group) }        var args: [String: JSONValue] = ["id": .string(group), "hidden": .bool(!hidden)]        if hidden {            let made = UUID().uuidString            undoTokens[group] = made            args["undo"] = .string(made)        }        return .read(CinemasHid(id: group, hidden: hidden,                                line: CinemasWords.line(hidden ? "stream.hidden_done" : "stream.shown_done", ["group": found.name]),                                undo: .init(method: "cinemas.hide", args: .object(args))))    }    /// One-use tokens a Hide handed back, by category.    private var undoTokens: [String: String] = [:]    func undo(_ undo: CinemasHid.Undo) async -> CinemasRead<CinemasHid> {        guard undo.method == "cinemas.hide", case .object(let args) = undo.args, case .string(let id)? = args["id"],              case .bool(let hidden)? = args["hidden"] else { return .refused("That cannot be undone.") }        let token: String? = if case .string(let made)? = args["undo"] { made } else { nil }        return hide(id, hidden: hidden, token: token)    }    /// The core's unlock, as it keeps it: given only after the phone's lock passed, shut by `lock`.    private var unlocked = false    private var noLock = false    /// The core's refusal of `hidden: true` without its unlock.    private static let shut = "Hidden is locked."    func unlock(noLock: Bool) async -> CinemasRead<Bool> {        unlocked = true        self.noLock = noLock        return .read(true)    }    func lock() async -> CinemasRead<Bool> {        unlocked = false        return .read(true)    }    func hiddenPlace() async -> CinemasRead<CinemasHiddenPlace> {        let title = CinemasWords.line("stream.hidden_place")        guard unlocked else { return .read(CinemasHiddenPlace(title: title, locked: true, rows: [], unlock: CinemasWords.line("stream.hidden_unlock"))) }        var rows: [CinemasHome.Row] = []        if let carry = rowItems("carry_on", hidden: true), !carry.1.isEmpty {            rows.append(.init(id: "carry_on", title: CinemasWords.line("stream.hidden_carry_on"), group: nil, count: carry.1.count,                              items: Array(carry.1.prefix(20)), more: carry.1.count > 20))        }        for group in groupList where hiddenGroups.contains(group.id) {            let items = group.members.compactMap { entry($0)?.item }            rows.append(.init(id: "group:\(group.id)", title: group.name, group: group.id, count: items.count,                              items: Array(items.prefix(20)), more: items.count > 20))        }        return .read(CinemasHiddenPlace(            title: title, locked: false, rows: rows, searchHint: CinemasWords.line("stream.hidden_search_hint"),            empty: hiddenGroups.isEmpty ? CinemasWords.line("stream.hidden_empty") : nil,            noLock: noLock ? CinemasWords.line("stream.hidden_no_lock") : nil,            setLock: noLock ? CinemasWords.line("stream.hidden_set_lock") : nil))    }    func kind(_ item: CinemasItem, to kind: CinemasItem.Kind) async -> CinemasRead<String?> {        guard let index = entries.firstIndex(where: { $0.item.id == item.id }) else { return .refused("That title is no longer here.") }        entries[index].item.kind = kind        return .read(nil)    }    func orderGroups(_ order: [String]) async -> CinemasRead<Bool> {        groupList.sort { (order.firstIndex(of: $0.id) ?? .max) < (order.firstIndex(of: $1.id) ?? .max) }        return .read(true)    }    func group(_ group: String, item: CinemasItem, in add: Bool) async -> CinemasRead<Bool> {        guard let index = groupList.firstIndex(where: { $0.id == group }) else { return .refused("That category is gone.") }        groupList[index].members.removeAll { $0 == item.id }        if add { groupList[index].members.insert(item.id, at: 0) }        return .read(true)    }    func makeGroup(_ name: String, with item: CinemasItem?) async -> CinemasRead<String> {        made += 1        let id = "g-made-\(made)"        groupList.append((id, name, item.map { [$0.id] } ?? []))        return .read(id)    }    func moveGroup(_ group: String, earlier: Bool) async -> CinemasRead<Bool> {        guard let index = groupList.firstIndex(where: { $0.id == group }) else { return .refused("That category is gone.") }        let to = earlier ? index - 1 : index + 1        guard groupList.indices.contains(to) else { return .read(false) }        groupList.swapAt(index, to)        return .read(true)    }    func renameGroup(_ group: String, to name: String) async -> CinemasRead<Bool> {        guard let index = groupList.firstIndex(where: { $0.id == group }) else { return .refused("That category is gone.") }        groupList[index].name = name        return .read(true)    }    /// What Undo can put back, by change.    private var taken: [String: () -> Void] = [:]    func deleteGroup(_ group: String) async -> CinemasRead<String?> {        guard let index = groupList.firstIndex(where: { $0.id == group }) else { return .read(nil) }        let gone = groupList.remove(at: index)        made += 1        let change = "c-\(made)"        taken[change] = { [weak self] in Task { await self?.putBack(group: gone, at: index) } }        return .read(change)    }    private func putBack(group: (id: String, name: String, members: [String]), at index: Int) {        groupList.insert(group, at: min(index, groupList.count))    }    private func putBack(entry: Entry, at index: Int) {        inBin.removeAll { $0.item.id == entry.item.id }        entries.insert(entry, at: min(index, entries.count))    }    /// A play on the walk's player stopped at `seconds`: the title carries on from there, first in Carry on.    func played(_ id: String, at seconds: Double, of length: Double) {        guard let index = entries.firstIndex(where: { $0.item.id == id }), length > 0 else { return }        entries[index].item.progress = min(max(seconds / length, 0.01), 0.99)        for other in entries.indices where entries[other].watchedAt != nil { entries[other].watchedAt! += 1 }        entries[index].watchedAt = 1    }    private var mobileData = false    func onPhone(free: Int64?) async -> CinemasRead<CinemasOnPhone> {        let secret = hiddenTitles        let kept = entries.filter { $0.item.onPhone != nil && !secret.contains($0.item.id) }.map(\.item)        guard !kept.isEmpty else {            return .read(.init(title: "On this phone", space: nil, flight: nil, items: [],                               empty: "Nothing kept on this phone yet. Keep a film from its page to watch it without a connection."))        }        let minutes = kept.compactMap(\.minutes).reduce(0, +)        return .read(.init(title: "On this phone", space: "Cinemas 6.2 GB · 48 GB free",                           flight: .init(line: "Ready for a flight: \(minutes / 60)h \(minutes % 60)m",                                         what: "\(kept.count) films. They play with no internet."),                           items: kept.map { .init(item: $0, line: $0.onPhone == .keeping ? "Keeping" : "2.1 GB") }, empty: nil))    }    func cellular() async -> CinemasRead<Bool> { .read(mobileData) }    func setCellular(_ on: Bool) async -> CinemasRead<Bool> {        mobileData = on        return .read(on)    }    func preparing(_ item: CinemasItem) async -> CinemasRead<CinemasPreparing> {        .read(.init(head: "Your Mac at home is preparing this film",                    steps: [.init(label: "Received from your Mac", state: "done"), .init(label: "Making a copy that streams", state: "now"),                            .init(label: "Making subtitles", state: "next")],                    queue: "Nothing ahead of it",                    note: "If your Mac goes to sleep this pauses. You can still add it to a category or send it now.", ready: false))    }    func remote(table: String, id: String, at: Double, length: Double?, device: String?) async -> CinemasRead<CinemasRemoteWords> {        func clock(_ s: Double) -> String { let s = Int(s); return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s / 60 % 60, s % 60) : String(format: "%d:%02d", s / 60, s % 60) }        let playing = device.map { "Playing on \($0)" } ?? "Playing on your TV"        let volume = "The phone's volume buttons change the TV's volume."        // An episode: its own name, its series' place, and the next episode with a file.        for entry in entries {            let all = entry.seasons.flatMap { season in season.episodes.indices.map { (season, $0) } }            guard let place = all.firstIndex(where: { "\($0.0.id)-e\($0.1 + 1)" == id }) else { continue }            let (season, index) = all[place]            let episode = season.episodes[index]            let whole = length ?? Double(episode.minutes * 60)            let next = all.indices.contains(place + 1) ? all[place + 1] : nil            return .read(.init(playing: playing, title: episode.title,                               caption: "\(entry.item.title) · Season \(season.number), Episode \(index + 1)",                               at: clock(at), left: "−" + clock(max(0, whole - at)),                               next: next.map { .init(table: "film_episode", id: "\($0.0.id)-e\($0.1 + 1)", label: "Next episode") },                               volume: volume))        }        guard let entry = entry(id) else { return .refused("That title is gone.") }        let whole = length ?? Double(entry.item.minutes ?? 0) * 60        return .read(.init(playing: playing, title: entry.item.title, caption: entry.item.year,                           at: clock(at), left: whole > 0 ? "−" + clock(max(0, whole - at)) : nil, next: nil, volume: volume))    }    /// What plays on the invented TV, as the player would know it.    func onTV(_ item: CinemasItem) -> (id: String, title: String, caption: String?, cover: String?, length: Double, at: Double)? {        for entry in entries {            for season in entry.seasons {                for (index, episode) in season.episodes.enumerated() where "\(season.id)-e\(index + 1)" == item.id {                    let length = Double(episode.minutes * 60)                    return ("\(season.id)-e\(index + 1)", episode.title, "S\(season.number) E\(index + 1)", "drawn:\(season.id)-e\(index + 1):wide", length, length * (episode.progress ?? 0))                }            }        }        guard let entry = entry(item.id) else { return nil }        // A series plays the episode it stands at: the first not yet watched.        for season in entry.seasons {            for (index, episode) in season.episodes.enumerated() where (episode.progress ?? 0) < 1 {                let length = Double(episode.minutes * 60)                return ("\(season.id)-e\(index + 1)", episode.title, "S\(season.number) E\(index + 1)", "drawn:\(season.id)-e\(index + 1):wide", length, length * (episode.progress ?? 0))            }        }        let length = Double((entry.item.minutes ?? 100) * 60)        return (entry.item.id, entry.item.title, entry.item.year, entry.item.backdrop ?? "drawn:\(entry.item.id):wide", length, length * (entry.item.progress ?? 0))    }    func toEpisode(_ item: CinemasItem, series: String?, newSeries: String?, season: Int, episode: Int) async -> CinemasRead<Bool> {        guard let index = entries.firstIndex(where: { $0.item.id == item.id }) else { return .refused("That title is no longer here.") }        let film = entries.remove(at: index)        let minutes = film.item.minutes ?? 50        let into: Int        if let series, let found = entries.firstIndex(where: { $0.item.id == series }) {            into = found        } else {            let id = "s-made-\(entries.count)"            let name = newSeries ?? film.item.title            entries.append(Entry(item: CinemasItem(table: "film", id: id, title: name, year: film.item.year, kind: .series, poster: "drawn:\(id)",                                                   backdrop: "drawn:\(id):wide", minutes: minutes),                                 added: 0, watchedAt: nil, synopsis: film.synopsis, facts: [film.item.year ?? ""]))            into = entries.count - 1        }        if let at = entries[into].seasons.firstIndex(where: { $0.number == season }) {            var episodes = entries[into].seasons[at].episodes            episodes.insert((film.item.title, minutes, film.item.progress), at: min(max(0, episode - 1), episodes.count))            entries[into].seasons[at].episodes = episodes        } else {            entries[into].seasons.append(("\(entries[into].item.id)-\(season)", season, [(film.item.title, minutes, film.item.progress)]))            entries[into].seasons.sort { $0.number < $1.number }        }        for group in groupList.indices { groupList[group].members.removeAll { $0 == item.id } }        return .read(true)    }    func sendStep(_ item: CinemasItem) async -> CinemasRead<SendStep> {        // Two invented friends on +1555 numbers, one not yet added back.        let json = #"""        {"says":"1 film · 2.1 GB goes","rows":[         {"value":"thread-arjun","words":"Arjun","number":"+15550100001","initials":"A","detail":"2.1 GB"},         {"value":"thread-priya","words":"Priya","number":"+15550100002","initials":"P","detail":"They have not added you yet","waiting":true}]}        """#        guard let step = try? JSONDecoder().decode(SendStep.self, from: Data(json.utf8)) else { return .refused("Nobody to send to yet.") }        return .read(step)    }    func send(_ item: CinemasItem, to person: SendPerson) async -> CinemasRead<CinemasSent> {        .read(CinemasSent(id: "send-\(item.id)", words: "Sent \(item.title) to \(person.words)", undo: "Undo", undone: "Taken back"))    }    func unsend(_ id: String) async -> CinemasRead<Bool> { .read(true) }    func subtitles(_ item: CinemasItem) async -> CinemasRead<CinemasSubtitles> {        let asked = subtitleWork[item.id]        let tracks: [CinemasSubtitles.Track] = item.preparing ? [] : [            .init(language: "en", name: "English", from: "in the file", chosen: true),            .init(language: "hi", name: "Hindi", from: "made by your Mac", chosen: false),        ]        return .read(.init(title: "Subtitles", line: tracks.first?.name ?? "None yet", tracks: tracks,                           working: asked.map { $0 == "find" ? "Your Mac will look for subtitles" : $0 == "make" ? "Your Mac will make subtitles" : "Waiting for your Mac to add your subtitles" },                           acts: asked != nil ? [] : (item.preparing ? [] : [.init(id: "find", label: "Find subtitles"), .init(id: "make", label: "Make them on your Mac")])                               + [.init(id: "give", label: "Give a subtitle file")]))    }    func subtitlesAct(_ act: String, item: CinemasItem, file: URL?) async -> CinemasRead<String?> {        subtitleWork[item.id] = act        return .read(nil)    }    func mark(_ item: CinemasItem, watched: Bool) async -> CinemasRead<String?> {        if let index = entries.firstIndex(where: { $0.item.id == item.id }) {            entries[index].item.progress = watched ? nil : entries[index].item.progress        }        return .read(nil)    }    func you(free: Int64?) async -> CinemasRead<CinemasYou> {        func row(_ id: String, _ label: String, value: String? = nil, sub: String? = nil, on: Bool? = nil, method: String? = nil,                 request: JSONValue? = nil, open: String? = nil) -> CinemasYou.Row {            .init(id: id, label: label, value: value, sub: sub, switch: on, act: .init(method: method, request: request, open: open))        }        func setting(_ key: String) -> JSONValue { .object(["key": .string(key), "value": .bool(!(settings[key] ?? false))]) }        let waiting = entries.filter(\.item.preparing).count        let names = ["en": "English", "hi": "Hindi", "te": "Telugu", "ta": "Tamil", "ml": "Malayalam", "fr": "French"]        return .read(CinemasYou(sections: [            .init(id: "watching", title: "Watching", rows: [                row("tv", "The TV", open: "tv"),                row("mac", "The Mac at home", value: waiting == 0 ? "Nothing waiting" : "\(waiting) waiting", method: "cinemas.row", request: .object(["id": .string("getting_ready")])),                row("groups", "Categories", value: "\(shownGroups(false).count)", method: "cinemas.groups"),                row("autoplay_next", "Play the next episode by itself", on: settings["autoplay_next"], method: "cinemas.setting", request: setting("autoplay_next")),            ]),            .init(id: "on_phone", title: "On this phone", rows: [                row("downloads", "Downloads", value: "2.3 GB used", method: "cinemas.onPhone"),                row("mobile_data", "Use mobile data", sub: "Off, films come down on Wi-Fi only", on: settings["cellular"], method: "films.keeping",                    request: .object(["cellular": .bool(!(settings["cellular"] ?? false))])),            ]),            .init(id: "subtitles", title: "Subtitles", rows: [                row("subtitles_on", "Show subtitles", on: settings["subtitles_on"], method: "cinemas.setting", request: setting("subtitles_on")),                row("subtitle_language", "Language", value: language.flatMap { names[$0] ?? $0 } ?? "This phone's", method: "cinemas.setting",                    request: .object(["key": .string("subtitle_language")])),            ]),            .init(id: "more", title: "More", rows: [                row("bin", "Bin", value: "\(inBin.count)", method: "cinemas.bin"),                row("help_ready", "Help", value: "Why isn't it ready?",                    sub: "A film your phone can't play as it is goes to the Mac at home, which makes a copy it can play.", open: "help_ready"),            ]),        ]))    }    func youAct(_ method: String, _ request: JSONValue?) async -> CinemasRead<Bool> {        if method == "films.keeping", case .bool(let on)? = request?["cellular"] { settings["cellular"] = on }        if method == "cinemas.setting", let key = request?["key"]?.string {            if key == "subtitle_language" { language = request?["value"]?.string } else if case .bool(let on)? = request?["value"] { settings[key] = on }        }        return .read(true)    }    func binned() async -> CinemasRead<CinemasBin> {        .read(CinemasBin(title: "Bin", items: inBin.map { .init(item: $0.item, line: "Moved to the Bin today") },                         empty: inBin.isEmpty ? "Nothing in the Bin. A film you move there waits here until you empty it." : nil))    }    func restore(_ item: CinemasItem) async -> CinemasRead<String?> {        guard let at = inBin.firstIndex(where: { $0.item.id == item.id }) else { return .refused("That title is no longer in the Bin.") }        entries.append(inBin.remove(at: at))        return .read("Back in Cinemas")    }    func bin(_ item: CinemasItem) async -> CinemasRead<String?> {        guard let index = entries.firstIndex(where: { $0.item.id == item.id }) else { return .read(nil) }        let gone = entries.remove(at: index)        inBin.insert(gone, at: 0)        made += 1        let change = "c-\(made)"        taken[change] = { [weak self] in Task { await self?.putBack(entry: gone, at: index) } }        return .read(change)    }    func undo(_ change: String) async -> CinemasRead<Bool> {        taken.removeValue(forKey: change)?()        try? await Task.sleep(for: .milliseconds(20))        return .read(true)    }}#endif