744 lines · 39.4 KB · SwiftRaw
// ALBUMS' FIXTURE: a stand-in for the core's `albums.*` (ALBUMS CORE 1), answering the SHELL BRIEF's calls with the// same keys from what this phone holds: the library's items and what the pass found (`AlbumsStore`), Photos' albums// (`AlbumsLibrary`), and its own small file of choices (the Bin, kept photos, decided Sets, names, undo tokens). Its// rules are deliberately simple stand-ins (a Set is shots of one moment no more than 3 s apart; picks are the sharpest// first, then only shots that look different, at most 6), so the screens can be built and walked before the core's// rules exist. Its words are the albums line set's, as the core's will be. It goes when `AlbumsBook.live` turns on.#if os(iOS)import CottonKitimport Foundationimport UIKitfinal class AlbumsFixture: CottonCalling, @unchecked Sendable { static let shared = AlbumsFixture() private let lock = NSLock() private var state: Choices private let file: URL /// What it read last, and at which pass revision. private var cache: (revision: Int, items: [AlbumsItem])? /// His choices: what the Bin holds and why, what Albums stops offering, Sets decided, names, undo tokens. struct Choices: Codable { var binned: [String: Binned] = [:] var kept: Set<String> = [] var sets: [String: [String]] = [:] var names: [String: String] = [:] var undo: [String: Undo] = [:] var faces: Bool? } struct Binned: Codable { var at: Date; var why: String; var batch: String } struct Undo: Codable { var binned: [String]; var kept: [String]; var set: String? } init(file: URL? = nil) { self.file = file ?? AlbumsStore.url.deletingLastPathComponent().appendingPathComponent("fixture.json") state = (try? JSONDecoder().decode(Choices.self, from: Data(contentsOf: self.file))) ?? Choices() #if COTTON_DEV if ProcessInfo.processInfo.arguments.contains("-albums-fresh") { state = Choices(); save() } #endif } /// For tests: items given, nothing read from the phone. var given: [AlbumsItem]? var givenAlbums: [LibraryAlbum] = [] var givenMembers: [String: [String]] = [:] var givenLines: AlbumsPassLines? func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {} func callRaw(_ method: String, requestJSON: String) async throws -> String { let body = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8)) as? [String: Any]) ?? [:] let pass = await passNow() let items = await read(pass.revision) do { let answer = try answer(method, body, items: items, pass: pass) let data = try JSONSerialization.data(withJSONObject: ["ok": true, "data": answer], options: [.fragmentsAllowed]) return String(decoding: data, as: UTF8.self) } catch let refused as AlbumsRefusal { return #"{"ok":false,"error":{"code":"\#(refused.code)","message":""}}"# } } // MARK: Reading the phone struct PassNow { var revision = 0 var counts = AlbumsStore.Counts() var running = false var pause = AlbumsPass.Pause.none var minutesLeft: Int? var read = false var charging = false var faces = true /// Seconds the pass has run, all runs together. var seconds: Double = 0 } private func passNow() async -> PassNow { if given != nil { return PassNow(revision: 0, read: true, faces: state.faces ?? true) } return await MainActor.run { let pass = AlbumsPass.shared UIDevice.current.isBatteryMonitoringEnabled = true return PassNow(revision: pass.revision, counts: pass.counts, running: pass.running, pause: pass.pause, minutesLeft: pass.minutesLeft, read: pass.read, charging: [.charging, .full].contains(UIDevice.current.batteryState), faces: pass.faces, seconds: pass.seconds) } } private func read(_ revision: Int) async -> [AlbumsItem] { if let given { return given } if let cache = locked({ cache }), cache.revision == revision, revision != 0 { return cache.items } let items = await Task.detached { AlbumsStore.shared.items() }.value locked { cache = (revision, items) } return items } private func locked<T>(_ work: () throws -> T) rethrows -> T { lock.lock() defer { lock.unlock() } return try work() } private func save() { guard given == nil, let data = try? JSONEncoder().encode(state) else { return } try? data.write(to: file, options: .atomic) } // MARK: Answers private func w(_ path: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("albums", path, fills) } private func n(_ v: Int) -> String { v.formatted() } private func answer(_ method: String, _ body: [String: Any], items: [AlbumsItem], pass: PassNow) throws -> Any { try locked { let found = Found(items: items, choices: state) switch method { case "albums.start": return start(body) case "albums.home": return home(body, found: found, pass: pass) case "albums.pass.lines": return ["progress": (lines(pass) as Any?) ?? NSNull()] case "albums.album": return try album(body["id"] as? String ?? "", items: items) case "albums.all": return all(found) case "albums.tidy": return tidy(found, pass: pass) case "albums.sets": return sets(found, from: body["from"] as? Int ?? 0) case "albums.set": return try set(found, body["set"] as? String ?? "") case "albums.set.keep": return try keepSet(found, body["set"] as? String ?? "", keep: body["keep"] as? [String], body: body) case "albums.list": return try list(found, body["list"] as? String ?? "") case "albums.bin.move": return try binMove(found, body) case "albums.keep": return keep(body["ids"] as? [String] ?? [], body: body) case "albums.undo": return try undo(body["token"] as? String ?? "") case "albums.bin": return bin(found) case "albums.bin.bring_back": return bringBack(body["ids"] as? [String] ?? [], body: body) case "albums.bin.delete": return binDelete(body) case "albums.platform.done": return platformDone(body) case "albums.people": return people(pass) case "albums.faces": return facesSet(body["on"] as? Bool ?? true) case "albums.people.name": // His name stays on this phone, on every face of the group: a must-link for every later grouping. let id = body["group"] as? String ?? "" let name = body["name"] as? String if given == nil, let group = AlbumsStore.shared.personGroups().first(where: { $0.id == id }) { AlbumsStore.shared.name(group.faces, name) Task { @MainActor in AlbumsPass.shared.namesChanged() } } else { state.names[id] = name save() } return ["said": NSNull()] case "albums.you": return you(found, pass: pass) default: throw AlbumsRefusal(code: "bad_request") } } } private func start(_ body: [String: Any]) -> Any { switch body["permission"] as? String ?? "none" { case "denied": return ["screen": "no_permission", "no_permission": ["title": w("first.denied_title"), "line": w("first.denied_line"), "act": w("first.open_settings")]] case "full": return ["screen": "home"] case "limited": return ["screen": "home", "limited": ["line": w("first.limited_line", ["n": n(body["chosen"] as? Int ?? 0)]), "act": w("first.limited_act")]] default: return ["screen": "first_run", "first_run": [ "title": w("first.title"), "lead": w("first.lead"), "promise": w("first.promise"), "next_head": w("first.next_head"), "next_line": w("first.next_line"), "start": w("first.start"), "faces": ["label": w("first.faces"), "line": w("first.faces_line"), "on": state.faces ?? true], ]] } } private func lines(_ pass: PassNow) -> [String: Any]? { if let givenLines { return ["head": givenLines.head as Any, "detail": givenLines.detail as Any, "note": givenLines.note as Any, "cloud": givenLines.cloud as Any, "fraction": givenLines.fraction as Any, "paused": givenLines.paused as Any] } let c = pass.counts let cloud: Any = c.onlyInCloud == 0 ? NSNull() : c.onlyInCloud == 1 ? w("pass.cloud_one") : w("pass.cloud", ["n": n(c.onlyInCloud)]) guard pass.read, c.waiting > 0 || pass.running else { return c.onlyInCloud > 0 ? ["head": NSNull(), "detail": NSNull(), "note": NSNull(), "cloud": cloud, "fraction": NSNull()] : nil } let done = c.photos - c.waiting + c.videos let fraction = c.total > 0 ? Double(done) / Double(c.total) : 0 switch pass.pause { case .battery: return ["head": w("pass.paused_battery"), "detail": w("pass.paused_battery_line", ["done": n(done), "n": n(c.total)]), "note": NSNull(), "cloud": cloud, "fraction": fraction, "paused": true] case .away: return ["head": w("pass.paused_away"), "detail": w("pass.paused_away_line", ["done": n(done), "n": n(c.total)]), "note": NSNull(), "cloud": cloud, "fraction": fraction, "paused": true] case .none: var detail = w("pass.done", ["n": n(done)]) if let left = pass.minutesLeft { let t = left < 1 ? w("pass.under_minute") : left < 90 ? w("pass.minutes", ["n": n(left)]) : w("pass.hours", ["h": n(left / 60), "m": n(left % 60)]) detail += " · " + w(pass.charging ? "pass.left_charging" : "pass.left", ["t": t]) } return ["head": w("pass.head", ["n": n(c.total)]), "detail": detail, "note": w("pass.fill"), "cloud": cloud, "fraction": fraction, "paused": false] } } private func home(_ body: [String: Any], found: Found, pass: PassNow) -> Any { let system = body["system"] as? [[String: Any]] ?? [] var rows: [[String: Any]] = [] for album in system { let kind = album["kind"] as? String ?? "mine" let title = album["title"] as? String ?? "" let count = album["count"] as? Int ?? 0 rows.append(["id": album["id"] as? String ?? "", "title": title, "count": n(count), "kind": kind]) } // Favourites and Screenshots first, then his own albums in Photos, by name. rows.sort { a, b in let ka = a["kind"] as? String ?? "", kb = b["kind"] as? String ?? "" if ka != kb { return ka == "smart" } return (a["title"] as? String ?? "").localizedStandardCompare(b["title"] as? String ?? "") == .orderedAscending } var answer: [String: Any] = [ "title": w("home.title"), "make": w("home.make"), "progress": lines(pass) ?? NSNull(), "rows": [[String: Any]](), "all_photos": ["title": w("home.all"), "count": n(found.items.isEmpty ? (given?.count ?? 0) : unbinned(found).count)], ] if !rows.isEmpty { answer["from_photos"] = ["heading": w("home.from_photos"), "rows": rows] } // Until Albums makes its own albums, where they will stand (the coordinator, 27 Nov). answer["coming"] = ["heading": w("home.coming_heading"), "rows": ["people", "places", "trips"].map { ["id": "coming-\($0)", "title": w("home.coming_\($0)"), "line": w("home.coming_line")] }] return answer } private func album(_ id: String, items: [AlbumsItem]) throws -> Any { let albums = given != nil ? givenAlbums : AlbumsLibrary.shared.albums() guard let album = albums.first(where: { $0.id == id }) else { throw AlbumsRefusal(code: "gone") } let members = Set(given != nil ? givenMembers[id] ?? [] : AlbumsLibrary.shared.members(of: id)) let shown = items.filter { members.contains($0.asset.id) } var answer: [String: Any] = [ "title": album.title, "mine": album.kind == .mine, "line": shown.count == 1 ? w("album.photos_one") : w("album.photos", ["n": n(shown.count)]), "groups": groups(shown, by: "EEE d MMM yyyy"), ] if shown.isEmpty { answer["empty"] = w("album.empty") } if album.kind == .mine { answer["menu"] = ["rename": w("album.rename"), "delete": w("album.delete"), "delete_ask": w("album.delete_ask", ["title": album.title]), "delete_line": w("album.delete_line", ["n": n(album.count)])] } return answer } /// All photos leaves out what waits in the Bin, on home and on its page alike. private func unbinned(_ found: Found) -> [AlbumsItem] { found.items.filter { found.choices.binned[$0.asset.id] == nil } } private func all(_ found: Found) -> Any { let shown = unbinned(found) return ["title": w("home.all"), "mine": false, "line": w("album.photos", ["n": n(shown.count)]), "groups": groups(shown, by: "MMMM yyyy")] } /// Newest first, by day or by month, each heading with its count. private func groups(_ items: [AlbumsItem], by format: String) -> [[String: Any]] { let f = Self.formatter(format) var out: [(String, [String])] = [] for item in items.sorted(by: { ($0.asset.created ?? .distantPast) > ($1.asset.created ?? .distantPast) }) { let heading = item.asset.created.map { f.string(from: $0) } ?? "" if out.last?.0 == heading { out[out.count - 1].1.append(item.asset.id) } else { out.append((heading, [item.asset.id])) } } return out.map { ["heading": $0.0, "count": n($0.1.count), "ids": $0.1] } } // MARK: Tidy private func tidy(_ found: Found, pass: PassNow) -> Any { let looking = pass.read && (pass.counts.waiting > 0 || pass.running) var lists: [[String: Any]] = [] var free: Int64 = 0 var exact = true for key in Found.lists { let (members, bytes, allExact) = found.listMembers(key) free += bytes exact = exact && allExact if members.isEmpty { if looking { lists.append(["list": key, "name": w("lists.\(key)"), "count": w("tidy.still"), "still": true, "bytes": Int64(0)]) } continue } let count = key == "sets" ? found.sets.count : members.count lists.append(["list": key, "name": w("lists.\(key)"), "count": looking ? w("tidy.so_far_count", ["n": n(count)]) : n(count), "size": AlbumsWords.size(bytes, exact: allExact), "bytes": bytes, "cover": members.first ?? NSNull()]) } lists.sort { ($0["bytes"] as? Int64 ?? 0) > ($1["bytes"] as? Int64 ?? 0) } for i in lists.indices { lists[i]["bytes"] = nil } var answer: [String: Any] = ["title": w("tidy.title"), "progress": lines(pass) ?? NSNull(), "lists": lists] let binned = found.binnedItems if !binned.isEmpty { answer["bin"] = ["line": w("tidy.bin", ["n": n(binned.count), "size": AlbumsWords.size(binned.reduce(0) { $0 + $1.bytes })]), "act": w("tidy.bin_act")] } if free > 0 { answer["could_free"] = w(AlbumsBook.lookOnly ? "look_only.could_free" : "tidy.could_free", ["size": AlbumsWords.size(free)]) if looking { answer["heading"] = w("tidy.so_far") } } else if lists.isEmpty { answer["empty"] = ["title": w("tidy.empty_title"), "line": w("tidy.empty_line")] } return answer } private func sets(_ found: Found, from: Int) -> Any { let all = found.sets let page = Array(all.dropFirst(from).prefix(60)) let f = Self.formatter("EEE d MMM, h:mm a") let rows: [[String: Any]] = page.map { set in let picks = found.picks(set) return ["set": set.key, "count": w("sets.count", ["n": n(set.members.count)]), "when": set.members.first?.asset.created.map { Self.lower(f.string(from: $0)) } ?? "", "ask": w(AlbumsBook.lookOnly ? "look_only.ask" : "sets.ask", ["n": n(picks.count)]), "keep": w("sets.keep"), "strip": Array(set.members.prefix(7).map(\.asset.id)), "photos": set.members.count] } let bytes = all.reduce(Int64(0)) { $0 + $1.members.reduce(0) { $0 + $1.bytes } } var answer: [String: Any] = ["title": w("lists.sets"), "back": w("tidy.title"), "head": w("sets.head", ["n": n(all.count), "size": AlbumsWords.size(bytes)]), "rows": rows] if from + 60 < all.count { answer["next_from"] = from + 60 } if all.isEmpty { answer["empty"] = ["title": w("tidy.empty_title"), "line": w("tidy.empty_line")]; answer["head"] = NSNull() } return answer } private func set(_ found: Found, _ key: String) throws -> Any { let all = found.sets guard let at = all.firstIndex(where: { $0.key == key }) else { throw AlbumsRefusal(code: "gone") } let set = all[at] let picks = Set(found.picks(set)) let f = Self.formatter("EEE d MMM yyyy, h:mm a") return [ "set": key, "back": w("lists.sets"), "position": w("set.of", ["at": n(at + 1), "n": n(all.count)]), "title": w("set.title", ["keep": "{keep}", "n": n(set.members.count)]), "when": set.members.first?.asset.created.map { Self.lower(f.string(from: $0)) } ?? NSNull(), "members": set.members.map { ["id": $0.asset.id, "keep": picks.contains($0.asset.id)] }, "line": AlbumsBook.lookOnly ? (picks.count == 1 ? w("look_only.set_line_one") : w("look_only.set_line", ["n": n(picks.count)])) : (picks.count == 1 ? w("set.line_one") : w("set.line", ["n": n(picks.count)])), "button": w("set.button", ["keep": "{keep}", "bin": "{bin}"]), "keep_all": w("set.keep_all", ["n": n(set.members.count)]), ] } /// What every act carries (the core review): the ids on screen and their count. private func shown(_ body: [String: Any]) -> (ids: [String], count: Int) { let ids = body["shown"] as? [String] ?? [] return (ids, body["count"] as? Int ?? -1) } private let changed: [String: Any] = ["changed": true] private func keepSet(_ found: Found, _ key: String, keep: [String]?, body: [String: Any]) throws -> Any { let all = found.sets guard let at = all.firstIndex(where: { $0.key == key }) else { throw AlbumsRefusal(code: "gone") } let set = all[at] let ids = set.members.map(\.asset.id) let seen = shown(body) // From the row: its strip and the Set's count; from the Set: every member. Anything else changed under him. guard seen.count == ids.count, keep == nil ? Set(seen.ids).isSubset(of: ids) : Set(seen.ids) == Set(ids) else { return changed } let keeping = keep.map { Set($0).intersection(ids) } ?? Set(found.picks(set)) let binning = ids.filter { !keeping.contains($0) } let batch = UUID().uuidString for id in binning { state.binned[id] = Binned(at: Date(), why: "set", batch: batch) } state.kept.formUnion(keeping) state.sets[key] = Array(keeping) let token = UUID().uuidString state.undo[token] = Undo(binned: binning, kept: Array(keeping), set: key) save() let left = all.count - 1 let next: String? = all.indices.contains(at + 1) ? all[at + 1].key : (at > 0 ? all[0].key : nil) var nextLine: [String: Any] = ["label": w("set.last")] if left > 0, let next { nextLine = ["label": w("set.next", ["n": n(left)]), "set": next] } let undoLine: [String: Any] = ["label": w("list.undo"), "token": token] let keptIDs: [String] = ids.filter { keeping.contains($0) } var answer: [String: Any] = [:] answer["title"] = w("set.kept_title", ["n": n(keeping.count)]) answer["undo"] = undoLine answer["kept"] = keptIDs answer["stays"] = w("set.undo_stays") answer["next"] = nextLine if binning.isEmpty { answer["after"] = w("set.after_all", ["n": n(keeping.count)]); answer["after_line"] = w("set.after_all_line") } else { answer["after"] = w("set.after", ["keep": n(keeping.count), "bin": n(binning.count)]) answer["after_line"] = w("set.after_line", ["bin": n(binning.count)]) } return answer } private func list(_ found: Found, _ key: String) throws -> Any { guard Found.lists.contains(key), key != "sets" else { throw AlbumsRefusal(code: "bad_request") } let (ids, _, _) = found.listMembers(key) let byID = Dictionary(found.items.map { ($0.asset.id, $0) }, uniquingKeysWith: { a, _ in a }) let f = Self.formatter("d MMM yyyy") func item(_ id: String, original: String? = nil) -> [String: Any] { let it = byID[id] var out: [String: Any] = ["id": id, "size": it.map { AlbumsWords.size($0.bytes, exact: $0.exact) } ?? NSNull(), "when": it?.asset.created.map { f.string(from: $0) } ?? NSNull(), "video": it?.asset.kind == .video] if let d = it?.asset.duration, it?.asset.kind == .video { out["duration"] = String(format: "%d:%02d", Int(d) / 60, Int(d) % 60) } if let original { out["original"] = original } return out } var groups: [[String: Any]] = [] if key == "whatsapp" { let originals = found.whatsappOriginals let copies = ids.filter { originals[$0] != nil } let others = ids.filter { originals[$0] == nil } if !copies.isEmpty { groups.append(["heading": w("list.copies"), "items": copies.map { item($0, original: originals[$0]) }]) } if !others.isEmpty { groups.append(["heading": w("list.others"), "items": others.map { item($0) }]) } } else if !ids.isEmpty { groups.append(["items": ids.map { item($0) }]) } let name = w("lists.\(key)") var answer: [String: Any] = [ "list": key, "title": name, "back": w("tidy.title"), "groups": groups, "select": w("list.select"), "done": w("list.done"), "bin_selected": w("list.bin_selected", ["n": "{n}"]), "keep_selected": w("list.keep_selected", ["n": "{n}"]), ] if !ids.isEmpty { let bytes = ids.reduce(Int64(0)) { $0 + (byID[$1]?.bytes ?? 0) } answer["head"] = "\(n(ids.count)) · \(AlbumsWords.size(bytes))" answer["bin_all"] = ["label": w("list.bin_all"), "confirm": [ "question": w("list.confirm", ["n": n(ids.count), "what": w("lists_what.\(key)")]), "line": w("list.confirm_line"), "yes": w("list.move"), "no": w("list.cancel")]] } else { answer["empty"] = ["title": w("tidy.empty_title"), "line": w("tidy.empty_line")] } return answer } private func binMove(_ found: Found, _ body: [String: Any]) throws -> Any { var ids = body["ids"] as? [String] ?? [] var why = "chosen" let seen = shown(body) guard seen.count == seen.ids.count else { return changed } if let list = body["list"] as? String { guard Found.lists.contains(list) else { throw AlbumsRefusal(code: "bad_request") } ids = found.listMembers(list).0 // Bin all moves exactly what the list showed, or nothing. guard Set(ids) == Set(seen.ids) else { return changed } why = list } else if let first = ids.first, let list = Found.lists.first(where: { found.listMembers($0).0.contains(first) }) { why = list } guard Set(ids).isSubset(of: seen.ids) else { return changed } let batch = UUID().uuidString let fresh = ids.filter { state.binned[$0] == nil } for id in fresh { state.binned[id] = Binned(at: Date(), why: why, batch: batch) } let token = UUID().uuidString state.undo[token] = Undo(binned: fresh, kept: [], set: nil) save() return ["said": fresh.count == 1 ? w("list.moved_one") : w("list.moved", ["n": n(fresh.count)]), "undo": ["label": w("list.undo"), "token": token]] } private func keep(_ ids: [String], body: [String: Any]) -> Any { let seen = shown(body) guard seen.count == seen.ids.count, Set(ids).isSubset(of: seen.ids) else { return changed } state.kept.formUnion(ids) let token = UUID().uuidString state.undo[token] = Undo(binned: [], kept: ids, set: nil) save() return ["said": w("list.kept"), "undo": ["label": w("list.undo"), "token": token]] } private func undo(_ token: String) throws -> Any { guard let undo = state.undo.removeValue(forKey: token) else { throw AlbumsRefusal(code: "gone") } for id in undo.binned { state.binned[id] = nil } state.kept.subtract(undo.kept) if let set = undo.set { state.sets[set] = nil } save() return ["said": NSNull()] } // MARK: The Bin private func bin(_ found: Found) -> Any { let binned = found.binnedItems var answer: [String: Any] = ["title": w("bin.title"), "back": w("tidy.title")] guard !binned.isEmpty else { answer["groups"] = [[String: Any]]() answer["empty"] = ["title": w("bin.empty_title"), "line": w("bin.empty_line")] return answer } let bytes = binned.reduce(Int64(0)) { $0 + $1.bytes } answer["head"] = w("bin.head", ["n": n(binned.count), "size": AlbumsWords.size(bytes)]) answer["note"] = w("bin.note") var batches: [(String, Binned, [String])] = [] for item in binned { guard let b = state.binned[item.asset.id] else { continue } if let i = batches.firstIndex(where: { $0.0 == b.batch }) { batches[i].2.append(item.asset.id) } else { batches.append((b.batch, b, [item.asset.id])) } } batches.sort { $0.1.at > $1.1.at } let f = Self.formatter("d MMM") answer["groups"] = batches.map { batch -> [String: Any] in let day = Calendar.current.isDateInToday(batch.1.at) ? w("bin.today") : Calendar.current.isDateInYesterday(batch.1.at) ? w("bin.yesterday") : f.string(from: batch.1.at) let heading = batch.1.why == "set" ? w("bin.group_set", ["when": day]) : Found.lists.contains(batch.1.why) ? w("bin.group_list", ["when": day, "what": w("lists_what.\(batch.1.why)")]) : day return ["heading": heading, "bring_back": w("bin.bring_back", ["n": n(batch.2.count)]), "ids": batch.2] } answer["act"] = ["label": w("bin.act", ["n": n(binned.count)]), "question": w("bin.question", ["n": n(binned.count)]), "line": w("bin.line", ["n": n(binned.count), "size": AlbumsWords.size(bytes)]), "no_way_back": w("bin.after"), "yes": w("bin.act", ["n": n(binned.count)]), "no": w("bin.not_now")] return answer } private func bringBack(_ ids: [String], body: [String: Any]) -> Any { let seen = shown(body) guard seen.count == seen.ids.count, Set(ids).isSubset(of: seen.ids), ids.allSatisfy({ state.binned[$0] != nil }) else { return changed } for id in ids { state.binned[id] = nil } save() return ["said": w("bin.brought", ["n": n(ids.count)])] } /// The iPhone is asked only for exactly what the Bin showed: anything else answers `changed` and asks nothing. private func binDelete(_ body: [String: Any]) -> Any { let seen = shown(body) guard seen.count == seen.ids.count, Set(seen.ids) == Set(state.binned.keys) else { return changed } let ids = seen.ids return ["platform": ["act": "delete", "parts": stride(from: 0, to: ids.count, by: 10_000).map { Array(ids[$0..<min(ids.count, $0 + 10_000)]) }]] } private func platformDone(_ body: [String: Any]) -> Any { let asked = body["asked"] as? [String] ?? [] let still = Set(body["still_here"] as? [String] ?? []) let gone = asked.filter { !still.contains($0) } for id in gone { state.binned[id] = nil; state.kept.remove(id) } cache = nil save() if gone.isEmpty { return ["said": w("bin.refused")] } if !still.isEmpty { return ["said": w("bin.part", ["gone": n(gone.count), "left": n(still.count)])] } return ["said": w("bin.done", ["n": n(gone.count)])] } // MARK: People and You private func people(_ pass: PassNow) -> Any { let on = state.faces ?? pass.faces guard on else { return ["title": w("people.title"), "named": [[String: Any]](), "off": ["lead": w("people.off_lead"), "points": [w("people.off_1"), w("people.off_2"), w("people.off_3"), w("people.off_4")], "not_now": w("people.not_now"), "turn_on": w("people.turn_on")]] } // The core's GROUPING 1 (cannot-link: two faces of one photo are never one person), kept by the pass; only // groups of 5 photos or more, or named, are shown. let groups = given != nil ? [] : AlbumsStore.shared.personGroups().filter(\.shown).map { (id: $0.id, items: $0.items, person: $0.person) } var named: [[String: Any]] = [] var who: [[String: Any]] = [] for g in groups { if let name = g.person ?? state.names[g.id] { named.append(["id": g.id, "name": name, "count": n(g.items.count), "cover": g.items.first ?? NSNull()]) } else { who.append(["id": g.id, "line": w("people.photos", ["n": n(g.items.count)]), "covers": Array(g.items.prefix(3)), "name": w("people.name")]) } } var answer: [String: Any] = ["title": w("people.title"), "named": named, "head": groups.isEmpty ? w("people.head_none") : w("people.head", ["n": n(groups.count), "named": n(named.count)])] if !who.isEmpty { answer["who"] = ["heading": w("people.who"), "groups": who] } if groups.isEmpty || (pass.read && pass.counts.waiting > 0) { answer["looking"] = w("people.looking") } return answer } private func facesSet(_ on: Bool) -> Any { state.faces = on save() return ["said": on ? w("you.faces_on_said") : w("you.faces_off_said")] } private func you(_ found: Found, pass: PassNow) -> Any { let on = state.faces ?? pass.faces let binned = found.binnedItems let groups = on && given == nil ? AlbumsStore.shared.personGroups().filter(\.shown).count : 0 return [ "first_look": firstLook(pass), "rows": [ ["row": "faces", "label": w("you.faces"), "value": on ? (groups > 0 ? w("you.faces_on", ["n": n(groups)]) : w("you.faces_on_none")) : w("you.faces_off")], ["row": "bin", "label": w("you.bin"), "value": binned.isEmpty ? w("you.bin_empty") : w("you.bin_value", ["n": n(binned.count), "size": AlbumsWords.size(binned.reduce(0) { $0 + $1.bytes })])], ], "privacy": w("you.privacy"), "faces_off": ["question": w("you.faces_off_ask"), "line": w("you.faces_off_line"), "yes": w("you.faces_off_yes"), "no": w("list.cancel")], ] } /// LOOK-ONLY: how the first look is going, in the order the coordinator reads them back from his phone (looked, /// small, owed a closer look, no local picture, failed, elapsed, photos a minute). A row with no count yet says "—". private func firstLook(_ pass: PassNow) -> [String: Any] { let c = pass.counts let looked = c.looked + c.small let none = "—" func count(_ v: Int) -> String { pass.read ? n(v) : none } func filled(_ key: String, _ fills: [String: String], _ fallback: String) -> String { ShellLines.shipped("albums", key) != nil ? w(key, fills) : fallback } let elapsed: String = { guard pass.seconds >= 1 else { return none } let f = DateComponentsFormatter() f.allowedUnits = pass.seconds >= 3600 ? [.hour, .minute] : [.minute, .second] f.unitsStyle = .abbreviated return f.string(from: pass.seconds) ?? none }() let rate = AlbumsPass.perMinute(c, seconds: pass.seconds).map { r in filled("look_only.rate_value", ["n": n(Int(r.rounded()))], n(Int(r.rounded()))) } ?? none let rows: [(String, String)] = [ ("looked", pass.read ? filled("look_only.looked_value", ["n": n(looked), "total": n(c.photos)], "\(n(looked)) / \(n(c.photos))") : none), ("small", count(c.small)), ("owed", count(c.small + c.onlyInCloud)), ("cloud", count(c.onlyInCloud)), ("failed", count(c.failed)), ("elapsed", elapsed), ("rate", rate), ] return ["heading": w("look_only.first_look"), "rows": rows.map { ["row": $0.0, "label": w("look_only.\($0.0)"), "value": $0.1] }] } // MARK: Formatting static func formatter(_ format: String) -> DateFormatter { let f = DateFormatter() f.locale = Locale(identifier: "en_GB") f.setLocalizedDateFormatFromTemplate(format) if format.contains("h:mm") { f.dateFormat = format } return f } static func lower(_ s: String) -> String { s.replacingOccurrences(of: "AM", with: "am").replacingOccurrences(of: "PM", with: "pm") }}// MARK: - What the fixture findsextension AlbumsFixture { struct ShotSet { let key: String let members: [AlbumsItem] } /// One read: the items still offered, the Sets, the lists. struct Found { static let lists = ["sets", "videos", "whatsapp", "screenshots", "documents", "blurry"] let items: [AlbumsItem] let choices: Choices let offered: [AlbumsItem] let sets: [ShotSet] private let inSets: Set<String> private let sharpFloor: Float init(items: [AlbumsItem], choices: Choices) { self.items = items self.choices = choices offered = items.filter { choices.binned[$0.asset.id] == nil && !choices.kept.contains($0.asset.id) } // A Set: photos of one moment, each no more than 3 s after the last; at least 2; biggest first. var sets: [ShotSet] = [] var run: [AlbumsItem] = [] func close() { if run.count >= 2 { sets.append(ShotSet(key: run[0].asset.id, members: run)) } run = [] } let photos = items.filter { $0.asset.kind == .photo && !$0.asset.flags.contains(.screenshot) && !($0.filename ?? "").contains("-WA") } .filter { choices.binned[$0.asset.id] == nil } .sorted { ($0.asset.created ?? .distantPast) < ($1.asset.created ?? .distantPast) } for item in photos { if let last = run.last, let a = last.asset.created, let b = item.asset.created, b.timeIntervalSince(a) <= 3 { run.append(item) } else { close(); run = [item] } } close() self.sets = sets.filter { choices.sets[$0.key] == nil && $0.members.contains { !choices.kept.contains($0.asset.id) } } .sorted { a, b in let sa = a.members.reduce(Int64(0)) { $0 + $1.bytes }, sb = b.members.reduce(Int64(0)) { $0 + $1.bytes } return sa != sb ? sa > sb : a.key < b.key } inSets = Set(self.sets.flatMap { $0.members.map(\.asset.id) }) let sharp = items.compactMap { $0.look?.sharpness }.sorted() sharpFloor = sharp.isEmpty ? 0 : sharp[sharp.count / 2] * 0.3 } var binnedItems: [AlbumsItem] { items.filter { choices.binned[$0.asset.id] != nil } } /// The best first (sharpest, well lit), then only shots that look different from every pick, at most 6. func picks(_ set: ShotSet) -> [String] { func score(_ i: AlbumsItem) -> Float { guard let l = i.look else { return 0 } return l.sharpness * (l.light < 0.12 ? 0.3 : 1) * (1 - min(0.8, l.clipped)) } let ranked = set.members.sorted { score($0) > score($1) } var picks: [AlbumsItem] = [] for item in ranked where picks.count < 6 { if picks.isEmpty { picks.append(item); continue } guard let h = item.look?.dhash else { continue } let differs = picks.allSatisfy { p in (p.look?.dhash).map { ($0 ^ h).nonzeroBitCount >= 12 } ?? true } if differs, score(item) >= score(picks[0]) * 0.5 { picks.append(item) } } return picks.map(\.asset.id) } /// A WhatsApp copy's camera original, when one looks the same. var whatsappOriginals: [String: String] { let camera = offered.filter { !($0.filename ?? "").contains("-WA") && $0.asset.kind == .photo }.compactMap { i in i.look.map { (i.asset.id, $0.dhash) } } var out: [String: String] = [:] for copy in offered where (copy.filename ?? "").contains("-WA") { guard let h = copy.look?.dhash else { continue } if let match = camera.first(where: { ($0.1 ^ h).nonzeroBitCount <= 6 }) { out[copy.asset.id] = match.0 } } return out } /// A list's members (biggest first; videos longest first), their bytes, and whether every size is exact. func listMembers(_ key: String) -> ([String], Int64, Bool) { var members: [AlbumsItem] switch key { case "sets": let binning = sets.flatMap { set -> [AlbumsItem] in let picks = Set(picks(set)) return set.members.filter { !picks.contains($0.asset.id) } } return (sets.map(\.key), binning.reduce(0) { $0 + $1.bytes }, binning.allSatisfy(\.exact)) case "videos": members = offered.filter { $0.asset.kind == .video && ($0.asset.duration >= 30 || $0.bytes >= 20_000_000) } .sorted { $0.asset.duration > $1.asset.duration } case "whatsapp": members = offered.filter { ($0.filename ?? "").contains("-WA") }.sorted { $0.bytes > $1.bytes } case "screenshots": members = offered.filter { $0.asset.flags.contains(.screenshot) }.sorted { $0.bytes > $1.bytes } case "documents": members = offered.filter { i in guard let l = i.look, !i.asset.flags.contains(.screenshot) else { return false } return l.document || (l.utility && l.text > 0.08) }.sorted { $0.bytes > $1.bytes } case "blurry": members = offered.filter { i in guard let l = i.look, i.asset.kind == .photo, !inSets.contains(i.asset.id), !i.asset.flags.contains(.screenshot), !l.document else { return false } return l.sharpness < sharpFloor || l.light < 0.1 }.sorted { $0.bytes > $1.bytes } default: members = [] } return (members.map(\.asset.id), members.reduce(0) { $0 + $1.bytes }, members.allSatisfy(\.exact)) } }}#endif