// WHAT ONLY THIS PHONE KEEPS (assets/design/albums/DECISIONS.md "What syncs", first row): each asset's metadata as the// library said it, and what looking at it found: the feature print, the quality scores, the grey picture's numbers,// the faces and their vectors. It is device-specific (Vision's prints differ by revision and from Android's), large// (about 200 MB for 64,000) and cheap to make again, so it never syncs and never enters the person's database: one// SQLite file in the app's own Application Support, excluded from the phone's backup. Deleting it costs one pass.// What syncs (decisions, Sets, albums, named people) is the core's, through its tables.#if os(iOS)importFoundationimport SQLite3/// One asset's row: the library's metadata and, once looked at, what was found.structAlbumsItem: Sendable, Equatable {/// `small`: looked at, but from a picture short of enough (AlbumsPicture): owed a closer look when a bigger picture/// can be had (the Wi-Fi pass), and counted on its own.enumState: Int, Sendable { case waiting = 0, looked = 1, onlyInCloud = 2, failed = 3, video = 4, small = 5 }var asset: LibraryAssetvar bytes: Int64var exact: Boolvar filename: String?var state: Statevar look: AlbumsLook?}/// The file. All calls on one serial queue: SQLite's own connection is not shared.finalclassAlbumsStore: @unchecked Sendable {staticlet shared = AlbumsStore()privatevar db: OpaquePointer?privatelet queue = DispatchQueue(label: "albums.store")staticvar url: URL {let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Albums", isDirectory: true)try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)var values = URLResourceValues() values.isExcludedFromBackup = truevar excluded = dirtry? excluded.setResourceValues(values)return dir.appendingPathComponent("looked.sqlite") }init(url: URL = AlbumsStore.url) { queue.sync { sqlite3_open_v2(url.path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil) exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") exec(""" CREATE TABLE IF NOT EXISTS item( id TEXT PRIMARY KEY, kind INTEGER, flags INTEGER, created REAL, modified REAL, w INTEGER, h INTEGER, duration REAL, burst TEXT, lat REAL, lon REAL, bytes INTEGER, exact INTEGER, filename TEXT, state INTEGER NOT NULL DEFAULT 0, side INTEGER, degraded INTEGER, print BLOB, print_rev INTEGER, print_len INTEGER, aesthetic REAL, utility INTEGER, sharpness REAL, light REAL, clipped REAL, dhash INTEGER, document INTEGER, text REAL, faces INTEGER, millis REAL); CREATE INDEX IF NOT EXISTS item_state ON item(state); CREATE INDEX IF NOT EXISTS item_created ON item(created); CREATE TABLE IF NOT EXISTS face( item TEXT NOT NULL, n INTEGER NOT NULL, x REAL, y REAL, w REAL, h REAL, quality REAL, yaw REAL, roll REAL, pitch REAL, points BLOB, pixels REAL, original REAL, vector BLOB, model TEXT, PRIMARY KEY(item, n)); CREATE TABLE IF NOT EXISTS person_group(face TEXT PRIMARY KEY, item TEXT NOT NULL, grp INTEGER NOT NULL, shown INTEGER NOT NULL, person TEXT); CREATE TABLE IF NOT EXISTS person_name(face TEXT PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT); CREATE TABLE IF NOT EXISTS rate(at REAL, done INTEGER); CREATE TABLE IF NOT EXISTS kept_album( album TEXT PRIMARY KEY, title TEXT NOT NULL, raw INTEGER NOT NULL, cellular INTEGER NOT NULL, since REAL NOT NULL, keeping INTEGER NOT NULL DEFAULT 1); CREATE TABLE IF NOT EXISTS kept_item( album TEXT NOT NULL, asset TEXT NOT NULL, state INTEGER NOT NULL DEFAULT 0, records TEXT, bytes INTEGER, tries INTEGER NOT NULL DEFAULT 0, why TEXT, at REAL, keys TEXT, code TEXT, away INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(album, asset)); CREATE INDEX IF NOT EXISTS kept_item_state ON kept_item(state); """)// KEEP 1e's three columns on a store an earlier dev build made (an ADD COLUMN that is there already fails and// changes nothing). exec("ALTER TABLE kept_item ADD COLUMN keys TEXT") exec("ALTER TABLE kept_item ADD COLUMN code TEXT") exec("ALTER TABLE kept_item ADD COLUMN away INTEGER NOT NULL DEFAULT 0")// Handed over by an earlier build, which kept no keys to ask the object about: kept again (the same file is// the same file in Cotton), never assumed kept. exec("UPDATE kept_item SET state = 0 WHERE state = 1 AND keys IS NULL") } }// MARK: Keep (KEEP slice 1, KEEP 1e): which albums he keeps in Cotton and where each of their photos is/// Where one photo of a kept album is. Nothing here is ever deleted from Cotton or from Photos: a photo that left/// the album or the library keeps its copy (look-only: no delete). A row is only ever dropped from this phone's/// own queue, for a photo that never reached Cotton and is no longer in the album.enumKeptState: Int, Sendable {/// Not yet in Cotton.case waiting = 0/// Handed to Cotton (`capture.media`): sealed on this phone, its originals in Cotton's upload queue.case sending = 1/// In Cotton: the object answered that it holds every original of it (`media.uploads`, per file).case kept = 2/// Could not be read or handed over; tried again on the next run while `tries` is under five.case failed = 3/// In Cotton, then taken out of the album in Photos (a change the library reported). Its copy stays.case left = 4/// In Cotton, then deleted from the library (a change the library reported). Its copy stays.case gone = 5/// Cotton will not take it, for a reason that is his to act on (`code`: too_big, cotton_full, file_gone,/// refused). Never tried again on its own.case refused = 6 }/// Where an item still in Cotton's queue was reported to have gone, for when the object confirms it.enumKeptAway: Int, Sendable { case here = 0, leftAlbum = 1, deleted = 2 }structKeptAlbum: Sendable, Equatable {let album: String, title: String, raw: Bool, cellular: Bool, since: Double, keeping: Bool }structKeptCounts: Sendable, Equatable {var total = 0, waiting = 0, sending = 0, kept = 0, failed = 0, left = 0, gone = 0, refused = 0/// Failed ones with tries left: Albums tries them again.var retrying = 0/// Bytes handed to Cotton (sending and kept, and copies of photos that left).var bytes: Int64 = 0 }/// One photo handed over and not yet confirmed: its originals' object keys.structKeptSending: Sendable, Equatable {let asset: String, keys: [String] }privatestaticfunc json(_ list: [String]) -> String {String(decoding: (try? JSONSerialization.data(withJSONObject: list)) ?? Data("[]".utf8), as: UTF8.self) }/// How many tries a photo that would not read or hand over gets.staticlet keepTries = 5func keep(_ album: String, title: String, cellular: Bool) { queue.sync { run(""" INSERT INTO kept_album(album, title, raw, cellular, since, keeping) VALUES(?,?,0,?,?,1) ON CONFLICT(album) DO UPDATE SET title = excluded.title, raw = 0, cellular = excluded.cellular, keeping = 1 """, [.text(album), .text(title), .int(cellular ? 1 : 0), .double(Date().timeIntervalSince1970)]) } }/// Stop keeping: new photos are no longer kept; every copy already in Cotton stays.func stopKeeping(_ album: String) { queue.sync { run("UPDATE kept_album SET keeping = 0 WHERE album = ?", [.text(album)]) } }func keptAlbums() -> [KeptAlbum] { queue.sync {var out: [KeptAlbum] = [] query("SELECT album, title, raw, cellular, since, keeping FROM kept_album ORDER BY since", []) { r in out.append(KeptAlbum(album: r.text(0) ?? "", title: r.text(1) ?? "", raw: r.int(2) != 0, cellular: r.int(3) != 0, since: r.double(4), keeping: r.int(5) != 0)) }return out } }/// Whether `album` is kept and still keeping.func keeping(_ album: String) -> Bool { queue.sync {var out = false query("SELECT keeping FROM kept_album WHERE album = ?", [.text(album)]) { out = $0.int(0) != 0 }return out } }/// The album's members as Photos has them now, from a READ THAT RAN WHOLE (full access, the album found, at least/// one member): NEVER DECIDED BY ABSENCE (review M1). New ones wait to be kept (while it is kept). One back in the/// album after it left is checked against Cotton again, never assumed kept. One that never reached Cotton and is/// no longer in the album is simply no longer queued. One that reached Cotton is left as it is: only a change the/// library reports (`keptRemoved`, `keptDeleted`) marks it left or gone. A read that is not whole changes nothing.func setKeptMembers(_ album: String, _ members: [String], keeping: Bool, whole: Bool) {guard whole, !members.isEmpty else { return } queue.sync { exec("BEGIN")let list = Self.json(members)if keeping { run("INSERT OR IGNORE INTO kept_item(album, asset, state) SELECT ?, value, 0 FROM json_each(?)", [.text(album), .text(list)]) } run("DELETE FROM kept_item WHERE album = ? AND state IN (0, 3, 6) AND asset NOT IN (SELECT value FROM json_each(?))", [.text(album), .text(list)]) run(""" UPDATE kept_item SET state = CASE WHEN keys IS NULL THEN 0 ELSE 1 END, away = 0 WHERE album = ? AND state = 4 AND asset IN (SELECT value FROM json_each(?)) """, [.text(album), .text(list)]) run("UPDATE kept_item SET away = 0 WHERE album = ? AND state = 1 AND away = 1 AND asset IN (SELECT value FROM json_each(?))", [.text(album), .text(list)]) exec("COMMIT") } }/// The library REPORTED these taken out of `album` (a change observer's removed objects). One in Cotton is marked/// left (its copy stays); one still in Cotton's queue is marked so for when the object confirms it; one that never/// reached Cotton is no longer queued.func keptRemoved(_ album: String, _ assets: [String]) {guard !assets.isEmpty else { return } queue.sync { exec("BEGIN")let list = Self.json(assets) run("DELETE FROM kept_item WHERE album = ? AND state IN (0, 3, 6) AND asset IN (SELECT value FROM json_each(?))", [.text(album), .text(list)]) run("UPDATE kept_item SET away = 1 WHERE album = ? AND state = 1 AND away = 0 AND asset IN (SELECT value FROM json_each(?))", [.text(album), .text(list)]) run("UPDATE kept_item SET state = 4 WHERE album = ? AND state = 2 AND asset IN (SELECT value FROM json_each(?))", [.text(album), .text(list)]) exec("COMMIT") } }/// The library REPORTED these deleted (a change observer's removed objects for the kept photos themselves): as/// `keptRemoved`, in every album, marked gone.func keptDeleted(_ assets: [String]) {guard !assets.isEmpty else { return } queue.sync { exec("BEGIN")let list = Self.json(assets) run("DELETE FROM kept_item WHERE state IN (0, 3, 6) AND asset IN (SELECT value FROM json_each(?))", [.text(list)]) run("UPDATE kept_item SET away = 2 WHERE state = 1 AND asset IN (SELECT value FROM json_each(?))", [.text(list)]) run("UPDATE kept_item SET state = 5 WHERE state IN (2, 4) AND asset IN (SELECT value FROM json_each(?))", [.text(list)]) exec("COMMIT") } }/// Every photo a kept album holds on this phone's record, for the change observer to watch.func keptAssets() -> [String] { queue.sync {var out: [String] = [] query("SELECT DISTINCT asset FROM kept_item WHERE state <> 5", []) { out.append($0.text(0) ?? "") }return out } }/// The next photos to keep, oldest-added album first: waiting ones, then failed ones with tries left.func toKeep(_ limit: Int, tries: Int = AlbumsStore.keepTries) -> [(album: String, asset: String, raw: Bool, cellular: Bool)] { queue.sync {var out: [(album: String, asset: String, raw: Bool, cellular: Bool)] = [] query(""" SELECT i.album, i.asset, 0, a.cellular FROM kept_item i JOIN kept_album a USING (album) WHERE a.keeping = 1 AND (i.state = 0 OR (i.state = 3 AND i.tries < ?)) ORDER BY i.state, a.since LIMIT ? """, [.int(Int64(tries)), .int(Int64(limit))]) { r in out.append((album: r.text(0) ?? "", asset: r.text(1) ?? "", raw: false, cellular: r.int(3) != 0)) }return out } }/// One photo handed to Cotton: the object keys of its originals and the record ids `capture.media` answered, and/// the bytes of its parts. The same photo in a second kept album is the same file in Cotton (one/// `photo:<sha256>`), so it is not sent again.func keptSending(_ asset: String, keys: [String], records: [String], bytes: Int64) { queue.sync { run("UPDATE kept_item SET state = 1, keys = ?, records = ?, bytes = ?, why = NULL, code = NULL, at = ? WHERE asset = ? AND state IN (0, 3)", [.text(Self.json(keys)), .text(Self.json(records)), .int(bytes), .double(Date().timeIntervalSince1970), .text(asset)]) } }/// The photos handed over and not yet confirmed, oldest first, each once.func keptSendingKeys(limit: Int = 10_000) -> [KeptSending] { queue.sync {var out: [KeptSending] = []var seen = Set<String>() query("SELECT asset, keys FROM kept_item WHERE state = 1 AND keys IS NOT NULL ORDER BY at LIMIT ?", [.int(Int64(limit))]) { r inlet asset = r.text(0) ?? ""guard seen.insert(asset).inserted else { return }let keys = (try? JSONSerialization.jsonObject(with: Data((r.text(1) ?? "[]").utf8))) as? [String] ?? [] out.append(KeptSending(asset: asset, keys: keys)) }return out } }/// The object holds every original of these: kept (or left or gone, where the library reported so meanwhile).func keptConfirmed(_ assets: [String]) {guard !assets.isEmpty else { return } queue.sync { run("UPDATE kept_item SET state = CASE away WHEN 1 THEN 4 WHEN 2 THEN 5 ELSE 2 END WHERE state = 1 AND asset IN (SELECT value FROM json_each(?))", [.text(Self.json(assets))]) } }/// Cotton will not take this photo (`code`), or this phone cannot send it: never tried again on its own.func keptRefused(_ asset: String, code: String, why: String) { queue.sync { run("UPDATE kept_item SET state = 6, code = ?, why = ?, at = ? WHERE asset = ? AND state IN (0, 1, 3)", [.text(code), .text(why), .double(Date().timeIntervalSince1970), .text(asset)]) } }/// Handed over, and Cotton's queue no longer has it (the app was reinstalled, the queue was made again): it waits/// to be kept again, and the same file is the same file in Cotton.func keptAgain(_ assets: [String]) {guard !assets.isEmpty else { return } queue.sync { run("UPDATE kept_item SET state = 0, keys = NULL, away = 0 WHERE state = 1 AND asset IN (SELECT value FROM json_each(?))", [.text(Self.json(assets))]) } }func keptFailed(_ album: String, _ asset: String, why: String) { queue.sync { run("UPDATE kept_item SET state = 3, tries = tries + 1, why = ?, at = ? WHERE album = ? AND asset = ?", [.text(why), .double(Date().timeIntervalSince1970), .text(album), .text(asset)]) } }/// The words a refusal was filed under, most first, for the band ("2 too large").func keptRefusals(_ album: String) -> [(code: String, n: Int)] { queue.sync {var out: [(code: String, n: Int)] = [] query("SELECT COALESCE(code, 'refused'), COUNT(*) FROM kept_item WHERE album = ? AND state = 6 GROUP BY 1 ORDER BY 2 DESC", [.text(album)]) { r in out.append((code: r.text(0) ?? "refused", n: Int(r.int(1)))) }return out } }func keptCounts(_ album: String? = nil) -> KeptCounts { queue.sync {var c = KeptCounts()let filter = album == nil ? "" : " WHERE album = ?" query("SELECT state, COUNT(*), COALESCE(SUM(bytes), 0), SUM(CASE WHEN state = 3 AND tries < \(Self.keepTries) THEN 1 ELSE 0 END) FROM kept_item\(filter) GROUP BY state", album.map { [.text($0)] } ?? []) { r inlet n = Int(r.int(1)) c.total += nswitchKeptState(rawValue: Int(r.int(0))) {case .waiting: c.waiting += ncase .sending: c.sending += ncase .kept: c.kept += ncase .failed: c.failed += ncase .left: c.left += ncase .gone: c.gone += ncase .refused: c.refused += ncasenil: break } c.retrying += Int(r.int(3)) c.bytes += r.int(2) }return c } } #if COTTON_DEV/// Dev `-albums-keep-fresh`: forgets what Keep did on this phone (never anything in Cotton).func forgetKept() { queue.sync { exec("DELETE FROM kept_item; DELETE FROM kept_album;") } } #endif// MARK: Metafunc meta(_ key: String) -> String? { queue.sync {var out: String? query("SELECT value FROM meta WHERE key = ?", [.text(key)]) { out = $0.text(0) }return out } }func setMeta(_ key: String, _ value: String?) { queue.sync {iflet value { run("INSERT OR REPLACE INTO meta(key, value) VALUES(?, ?)", [.text(key), .text(value)]) }else { run("DELETE FROM meta WHERE key = ?", [.text(key)]) } } }// MARK: The library's side/// Brings the rows to what the library holds: new assets wait to be looked at, gone ones go, a changed one/// (edited since) waits again. Answers how many are new and how many went. @discardableResult////// Rows absent from the list go only when `complete` (full access, an enumeration run to its end), and never a/// hidden one (it vanishes from every list while the Hidden album is locked): absence never removes a choice.func reconcile(_ assets: [LibraryAsset], sizes: [String: LibrarySize], complete: Bool) -> (added: Int, removed: Int) { queue.sync {var known: [String: Double] = [:] query("SELECT id, modified FROM item", []) { known[$0.text(0) ?? ""] = $0.double(1) }var added = 0 exec("BEGIN")for asset in assets {let modified = asset.modified?.timeIntervalSince1970 ?? 0iflet was = known.removeValue(forKey: asset.id) {if abs(was - modified) > 1 { upsert(asset, sizes[asset.id], resetting: true) }continue } upsert(asset, sizes[asset.id], resetting: true) added += 1 }var removed = 0if complete {var hidden = Set<String>() query("SELECT id FROM item WHERE flags & ? <> 0", [.int(Int64(LibraryAsset.Flags.hidden.rawValue))]) { hidden.insert($0.text(0) ?? "") }for gone in known.keys where !hidden.contains(gone) { run("DELETE FROM item WHERE id = ?", [.text(gone)]) run("DELETE FROM face WHERE item = ?", [.text(gone)]) removed += 1 } } exec("COMMIT")return (added, removed) } }/// Ids whose size is still "about" (the library's metadata was taken in before the sizes were asked).func unsized(_ limit: Int) -> [String] { queue.sync {var out: [String] = [] query("SELECT id FROM item WHERE exact = 0 AND filename IS NULL LIMIT ?", [.int(Int64(limit))]) { out.append($0.text(0) ?? "") }return out } }func setSizes(_ sizes: [String: LibrarySize]) { queue.sync { exec("BEGIN")for (id, size) in sizes { run("UPDATE item SET bytes = ?, exact = ?, filename = ? WHERE id = ?", [.int(size.bytes), .int(size.exact ? 1 : 0), size.filename.map { .text($0) } ?? .text(""), .text(id)]) #if COTTON_DEV// The synthetic library's screenshots: `simctl addmedia` cannot give a PNG PhotoKit's screenshot// subtype, so in the Dev build a file the generator named Screenshot_… counts as one.if size.filename?.hasPrefix("Screenshot_") == true { run("UPDATE item SET flags = flags | ? WHERE id = ?", [.int(Int64(LibraryAsset.Flags.screenshot.rawValue)), .text(id)]) } #endif } exec("COMMIT") } }/// Only what changed, from the library's persistent changes.func apply(inserted: [LibraryAsset], removed: [String], sizes: [String: LibrarySize]) { queue.sync { exec("BEGIN")for asset in inserted { upsert(asset, sizes[asset.id], resetting: true) }for gone in removed { run("DELETE FROM item WHERE id = ?", [.text(gone)]) run("DELETE FROM face WHERE item = ?", [.text(gone)]) } exec("COMMIT") } }privatefunc upsert(_ a: LibraryAsset, _ size: LibrarySize?, resetting: Bool) {let size = size ?? LibrarySize(bytes: AlbumsLibrary.about(a), exact: false, filename: nil)let state = a.kind == .video ? AlbumsItem.State.video : .waiting run(""" INSERT INTO item(id, kind, flags, created, modified, w, h, duration, burst, lat, lon, bytes, exact, filename, state) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, flags=excluded.flags, created=excluded.created, modified=excluded.modified, w=excluded.w, h=excluded.h, duration=excluded.duration, burst=excluded.burst, lat=excluded.lat, lon=excluded.lon, bytes=excluded.bytes, exact=excluded.exact, filename=excluded.filename, state=excluded.state, print=NULL, faces=NULL """, [ .text(a.id), .int(Self.kindCode(a.kind)), .int(Int64(a.flags.rawValue)), a.created.map { .double($0.timeIntervalSince1970) } ?? .null, a.modified.map { .double($0.timeIntervalSince1970) } ?? .null, .int(Int64(a.width)), .int(Int64(a.height)), .double(a.duration), a.burst.map { .text($0) } ?? .null, a.latitude.map { .double($0) } ?? .null, a.longitude.map { .double($0) } ?? .null, .int(size.bytes), .int(size.exact ? 1 : 0), size.filename.map { .text($0) } ?? .null, .int(Int64(state.rawValue)), ])if resetting { run("DELETE FROM face WHERE item = ?", [.text(a.id)]) } }// MARK: Looking/// The next photos waiting to be looked at, newest first (what he took lately matters first).func waiting(_ limit: Int) -> [LibraryAsset] { queue.sync {var out: [LibraryAsset] = [] query("SELECT \(Self.assetColumns) FROM item WHERE state = 0 ORDER BY created DESC LIMIT ?", [.int(Int64(limit))]) { out.append(Self.asset($0)) }return out } }/// Photos only in iCloud, to look at later on Wi-Fi.func onlyInCloud(_ limit: Int) -> [LibraryAsset] { queue.sync {var out: [LibraryAsset] = [] query("SELECT \(Self.assetColumns) FROM item WHERE state = 2 ORDER BY created DESC LIMIT ?", [.int(Int64(limit))]) { out.append(Self.asset($0)) }return out } }func state(_ id: String) -> AlbumsItem.State? { queue.sync {var out: AlbumsItem.State? query("SELECT state FROM item WHERE id = ?", [.text(id)]) { out = AlbumsItem.State(rawValue: Int($0.int(0))) }return out } }/// What is owed a closer look: only in iCloud, or looked at from a picture short of enough. Newest first.func owed(_ limit: Int, after: Double = .infinity) -> [LibraryAsset] { queue.sync {var out: [LibraryAsset] = [] query("SELECT \(Self.assetColumns) FROM item WHERE state IN (2, 5) AND IFNULL(created, 0) < ? ORDER BY created DESC LIMIT ?", [.double(after), .int(Int64(limit))]) { out.append(Self.asset($0)) }return out } }/// Writes what looking found, for a batch at once (the checkpoint), with the rate's sample.func record(_ batch: [(id: String, state: AlbumsItem.State, look: AlbumsLook?)]) { queue.sync { exec("BEGIN")for one in batch {guardlet l = one.look else { run("UPDATE item SET state = ? WHERE id = ?", [.int(Int64(one.state.rawValue)), .text(one.id)])continue } run(""" UPDATE item SET state=?, side=?, degraded=?, print=?, print_rev=?, print_len=?, aesthetic=?, utility=?, sharpness=?, light=?, clipped=?, dhash=?, document=?, text=?, faces=?, millis=? WHERE id=? """, [ .int(Int64(one.state.rawValue)), .int(Int64(l.side)), .int(l.degraded ? 1 : 0), l.print.map { .blob($0) } ?? .null, .int(Int64(l.printRevision)), .int(Int64(l.printLength)), l.aesthetic.map { .double(Double($0)) } ?? .null, .int(l.utility ? 1 : 0), .double(Double(l.sharpness)), .double(Double(l.light)), .double(Double(l.clipped)), .int(Int64(bitPattern: l.dhash)), .int(l.document ? 1 : 0), .double(Double(l.text)), .int(Int64(l.faces.count)), .double(l.millis), .text(one.id), ]) run("DELETE FROM face WHERE item = ?", [.text(one.id)])for (n, f) in l.faces.enumerated() { run(""" INSERT INTO face(item, n, x, y, w, h, quality, yaw, roll, pitch, points, pixels, original, vector, model) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) """, [ .text(one.id), .int(Int64(n)), .double(Double(f.x)), .double(Double(f.y)), .double(Double(f.w)), .double(Double(f.h)), f.quality.map { .double(Double($0)) } ?? .null, .double(Double(f.yaw)), .double(Double(f.roll)), .double(Double(f.pitch)), .blob(Self.floats(f.points)), .double(Double(f.pixels)), .double(Double(f.originalPixels)), f.vector.map { .blob(Self.floats($0)) } ?? .null, f.model.map { .text($0) } ?? .null, ]) } }let done = Self.count(db, "SELECT COUNT(*) FROM item WHERE state <> 0") run("INSERT INTO rate(at, done) VALUES(?, ?)", [.double(Date().timeIntervalSince1970), .int(Int64(done))]) run("DELETE FROM rate WHERE rowid NOT IN (SELECT rowid FROM rate ORDER BY at DESC LIMIT 64)", []) exec("COMMIT") } }// MARK: Reading backstructCounts: Sendable, Equatable {var total = 0var photos = 0var videos = 0var looked = 0var waiting = 0var onlyInCloud = 0var failed = 0/// Looked at from a picture short of enough, owed a closer look.var small = 0var faces = 0var vectors = 0var bytes: Int64 = 0var exactBytes = 0/// Photos looked at per minute over the last samples, when there are enough.var perMinute: Double? }func counts() -> Counts { queue.sync {var c = Counts() query("SELECT state, COUNT(*), SUM(bytes), SUM(exact) FROM item GROUP BY state", []) { row inlet n = Int(row.int(1)) c.total += n c.bytes += row.int(2) c.exactBytes += Int(row.int(3))switchAlbumsItem.State(rawValue: Int(row.int(0))) {case .waiting: c.waiting += n; c.photos += ncase .looked: c.looked += n; c.photos += ncase .onlyInCloud: c.onlyInCloud += n; c.photos += ncase .failed: c.failed += n; c.photos += ncase .small: c.small += n; c.photos += ncase .video: c.videos += ncasenil: break } } c.faces = Self.count(db, "SELECT COUNT(*) FROM face") c.vectors = Self.count(db, "SELECT COUNT(*) FROM face WHERE vector IS NOT NULL")// Measured from the last samples spanning about 500 photos, never guessed.var samples: [(Double, Int64)] = [] query("SELECT at, done FROM rate ORDER BY at DESC LIMIT 64", []) { samples.append(($0.double(0), $0.int(1))) }iflet newest = samples.first, let oldest = samples.last(where: { newest.1 - $0.1 <= 500 }) ?? samples.last, newest.0 - oldest.0 > 5, newest.1 > oldest.1 { c.perMinute = Double(newest.1 - oldest.1) / (newest.0 - oldest.0) * 60 }return c } }/// Photos that gave no picture last time wait again (once a launch: the phone may have made it since).func retryFailed() { queue.sync { run("UPDATE item SET state = 0 WHERE state = 3", []) } }/// Clears the rate samples: a new run measures its own speed (time asleep or in the background never counts).func restartRate() { queue.sync { run("DELETE FROM rate", []) } }/// Every item, oldest first, with what was found: what the core's rules take (Sets, picks, Tidy lists)./// Every item, oldest first. A look's feature print and each face's vector stay in the file unless asked for: the/// screens never use them, and at 64,000 items they were most of what a screen's copy held (about 4 KB a photo,/// 2 KB a face; the footprint climbed past 500 MB on the simulator).func items(prints: Bool = false, vectors: Bool = false) -> [AlbumsItem] { queue.sync {var faces: [String: [AlbumsFace]] = [:] query("SELECT item, x, y, w, h, quality, yaw, roll, pitch, points, pixels, original, \(vectors ? "vector" : "NULL"), model FROM face ORDER BY item, n", []) { r in faces[r.text(0) ?? "", default: []].append(Self.face(r, from: 1)) }var out: [AlbumsItem] = [] query("SELECT \(Self.assetColumns), bytes, exact, filename, state, side, degraded, \(prints ? "print" : "NULL"), print_rev, print_len, aesthetic, utility, sharpness, light, clipped, dhash, document, text, millis FROM item ORDER BY created", []) { r inlet asset = Self.asset(r)let state = AlbumsItem.State(rawValue: Int(r.int(14))) ?? .waitingvar look: AlbumsLook?if state == .looked { look = AlbumsLook( side: Int(r.int(15)), degraded: r.int(16) != 0, print: r.blob(17), printRevision: Int(r.int(18)), printLength: Int(r.int(19)), aesthetic: r.isNull(20) ? nil : Float(r.double(20)), utility: r.int(21) != 0, sharpness: Float(r.double(22)), light: Float(r.double(23)), clipped: Float(r.double(24)), dhash: UInt64(bitPattern: r.int(25)), document: r.int(26) != 0, text: Float(r.double(27)), faces: faces[asset.id] ?? [], millis: r.double(28)) } out.append(AlbumsItem(asset: asset, bytes: r.int(11), exact: r.int(12) != 0, filename: r.text(13), state: state, look: look)) }return out } }/// Every face that has a vector, for grouping.func vectors() -> [(item: String, n: Int, vector: [Float], quality: Float)] { queue.sync {var out: [(String, Int, [Float], Float)] = [] query("SELECT item, n, vector, quality FROM face WHERE vector IS NOT NULL", []) { r in out.append((r.text(0) ?? "", Int(r.int(1)), Self.floats(r.blob(2) ?? Data()), Float(r.double(3)))) }return out.map { (item: $0.0, n: $0.1, vector: $0.2, quality: $0.3) } } } #if COTTON_DEV/// Dev only, for the owner's sheet on a simulator: face rows (and each photo's document, utility, aesthetic and text/// values) the Mac harness measured with real Vision over the SAME/// synthetic library (scripts/albums-vision-mac.sh), matched by file name. A simulator's Vision returns impossible/// landmarks, so on its own it gives almost no face a vector. Each row: box [x, y, w, h] (normalised), quality,/// vector. Answers how many items took faces.func setFacesFromMac(_ byFile: [String: [[String: Any]]], looks: [String: [String: Any]] = [:], model: String) -> Int { queue.sync {var ids: [(String, String)] = [] query("SELECT id, filename FROM item WHERE filename IS NOT NULL AND filename != ''", []) { r iniflet id = r.text(0), let f = r.text(1) { ids.append((id, f)) } }var took = 0 exec("BEGIN")// The simulator's Vision also answers garbage for its other neural requests (a confident document outline on// nearly every photo; no utility): the Mac's values for the same file stand in, so the sheet's lists match a phone.for (id, file) in ids {guardlet l = looks[file] else { continue } run("UPDATE item SET document = ?, utility = ?, aesthetic = ?, text = ? WHERE id = ?", [ .int((l["document"] as? Bool ?? false) ? 1 : 0), .int((l["utility"] as? Bool ?? false) ? 1 : 0), (l["aesthetic"] as? Double).map { .double($0) } ?? .null, .double(l["text"] as? Double ?? 0), .text(id), ]) }for (id, file) in ids {guardlet faces = byFile[file] else { continue } run("DELETE FROM face WHERE item = ?", [.text(id)])for (n, f) in faces.enumerated() {let box = (f["box"] as? [Double]) ?? [0, 0, 0, 0]let vector = (f["vector"] as? [Double])?.map(Float.init) run("INSERT INTO face(item, n, x, y, w, h, quality, vector, model) VALUES(?,?,?,?,?,?,?,?,?)", [ .text(id), .int(Int64(n)), .double(box[0]), .double(box[1]), .double(box[2]), .double(box[3]), (f["quality"] as? Double).map { .double($0) } ?? .null, vector.map { .blob(Self.floats($0)) } ?? .null, vector == nil ? .null : .text(model), ]) } run("UPDATE item SET faces = ? WHERE id = ?", [.int(Int64(faces.count)), .text(id)]) took += 1 } exec("COMMIT")return took } } #endif// MARK: People (the core's GROUPING 1 over this phone's faces; his names stay on this phone)/// Every face with a vector, as `albums.faces.group` takes it: key `item#n`, its photo, its vector's bytes.func faceInputs() -> [(key: String, photo: String, vector: Data)] { queue.sync {var out: [(String, String, Data)] = [] query("SELECT item, n, vector FROM face WHERE vector IS NOT NULL", []) { r inlet item = r.text(0) ?? "" out.append(("\(item)#\(r.int(1))", item, r.blob(2) ?? Data())) }return out.map { (key: $0.0, photo: $0.1, vector: $0.2) } } }func faceCount() -> Int { queue.sync { Self.count(db, "SELECT COUNT(*) FROM face WHERE vector IS NOT NULL") } }/// The grouping as the core answered it, replacing the last.func setGroups(_ groups: [(faces: [String], shown: Bool, person: String?)]) { queue.sync { exec("BEGIN") run("DELETE FROM person_group", [])for (n, g) in groups.enumerated() {for face in g.faces {let item = face.split(separator: "#", omittingEmptySubsequences: false).dropLast().joined(separator: "#") run("INSERT OR REPLACE INTO person_group(face, item, grp, shown, person) VALUES(?,?,?,?,?)", [.text(face), .text(item), .int(Int64(n)), .int(g.shown ? 1 : 0), g.person.map { .text($0) } ?? .null]) } } exec("COMMIT") } }/// The groups, in the core's order (biggest first): an id (the group's first face key, steady while it lives), its/// photos (each once, newest first), its name, and whether it is shown (5 photos or more, or named).func personGroups() -> [(id: String, faces: [String], items: [String], person: String?, shown: Bool)] { queue.sync {var byGroup: [Int64: (faces: [String], items: [String], person: String?, shown: Bool)] = [:]var order: [Int64] = [] query(""" SELECT g.grp, g.face, g.shown, g.person, g.item FROM person_group g JOIN item i ON i.id = g.item ORDER BY g.grp, i.created DESC """, []) { r inlet grp = r.int(0)if byGroup[grp] == nil { order.append(grp); byGroup[grp] = ([], [], r.text(3), r.int(2) == 1) } byGroup[grp]!.faces.append(r.text(1) ?? "")let item = r.text(4) ?? ""if !byGroup[grp]!.items.contains(item) { byGroup[grp]!.items.append(item) } }return order.compactMap { grp in byGroup[grp].map { (id: $0.faces.min() ?? "", faces: $0.faces, items: $0.items, person: $0.person, shown: $0.shown) } } } }/// His names, by face key: naming a group names every face in it (a must-link for every later grouping).func names() -> [String: String] { queue.sync {var out: [String: String] = [:] query("SELECT face, name FROM person_name", []) { out[$0.text(0) ?? ""] = $0.text(1) ?? "" }return out } }func name(_ faces: [String], _ name: String?) { queue.sync { exec("BEGIN")for face in faces {iflet name, !name.isEmpty { run("INSERT OR REPLACE INTO person_name(face, name) VALUES(?,?)", [.text(face), .text(name)]) } else { run("DELETE FROM person_name WHERE face = ?", [.text(face)]) } } run("UPDATE person_group SET person = ? WHERE face IN (SELECT value FROM json_each(?))", [name.map { .text($0) } ?? .null, .text(String(decoding: (try? JSONSerialization.data(withJSONObject: faces)) ?? Data(), as: UTF8.self))]) exec("COMMIT") } }/// Turning faces off: every face row and vector goes from this phone, with the groups and his names.func forgetFaces() { queue.sync { run("DELETE FROM face", []) run("DELETE FROM person_group", []) run("DELETE FROM person_name", []) run("UPDATE item SET faces = NULL", []) } }/// Everything, for a pass made again from nothing.func forgetAll() { queue.sync { exec("DELETE FROM item; DELETE FROM face; DELETE FROM rate; DELETE FROM meta;") } }// MARK: SQLiteenumValue { casenull, int(Int64), double(Double), text(String), blob(Data) }structRow {let statement: OpaquePointerfunc int(_ i: Int32) -> Int64 { sqlite3_column_int64(statement, i) }func double(_ i: Int32) -> Double { sqlite3_column_double(statement, i) }func isNull(_ i: Int32) -> Bool { sqlite3_column_type(statement, i) == SQLITE_NULL }func text(_ i: Int32) -> String? { sqlite3_column_text(statement, i).map { String(cString: $0) } }func blob(_ i: Int32) -> Data? {guardlet bytes = sqlite3_column_blob(statement, i) else { returnnil }returnData(bytes: bytes, count: Int(sqlite3_column_bytes(statement, i))) } }privatestaticlet assetColumns = "id, kind, flags, created, modified, w, h, duration, burst, lat, lon"privatestaticfunc asset(_ r: Row) -> LibraryAsset {LibraryAsset( id: r.text(0) ?? "", kind: kind(Int(r.int(1))), flags: LibraryAsset.Flags(rawValue: UInt32(r.int(2))), created: r.isNull(3) ? nil : Date(timeIntervalSince1970: r.double(3)), modified: r.isNull(4) ? nil : Date(timeIntervalSince1970: r.double(4)), width: Int(r.int(5)), height: Int(r.int(6)), duration: r.double(7), burst: r.text(8), latitude: r.isNull(9) ? nil : r.double(9), longitude: r.isNull(10) ? nil : r.double(10)) }privatestaticfunc face(_ r: Row, from i: Int32) -> AlbumsFace {AlbumsFace( x: Float(r.double(i)), y: Float(r.double(i + 1)), w: Float(r.double(i + 2)), h: Float(r.double(i + 3)), quality: r.isNull(i + 4) ? nil : Float(r.double(i + 4)), yaw: Float(r.double(i + 5)), roll: Float(r.double(i + 6)), pitch: Float(r.double(i + 7)), points: floats(r.blob(i + 8) ?? Data()), pixels: Float(r.double(i + 9)), originalPixels: Float(r.double(i + 10)), vector: r.blob(i + 11).map(floats), model: r.text(i + 12)) }privatestaticfunc kindCode(_ k: LibraryAsset.Kind) -> Int64 {switch k { case .photo: 1; case .video: 2; case .audio: 3; case .other: 0 } }privatestaticfunc kind(_ c: Int) -> LibraryAsset.Kind {switch c { case1: .photo; case2: .video; case3: .audio; default: .other } }staticfunc floats(_ values: [Float]) -> Data { values.withUnsafeBufferPointer { Data(buffer: $0) } }staticfunc floats(_ data: Data) -> [Float] { data.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) } }privatestaticfunc count(_ db: OpaquePointer?, _ sql: String) -> Int {var statement: OpaquePointer?defer { sqlite3_finalize(statement) }guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK, sqlite3_step(statement) == SQLITE_ROW else { return0 }returnInt(sqlite3_column_int64(statement, 0)) }privatefunc exec(_ sql: String) { sqlite3_exec(db, sql, nil, nil, nil) }privatefunc run(_ sql: String, _ values: [Value]) { query(sql, values) { _ in } }privatestaticlet transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)privatefunc query(_ sql: String, _ values: [Value], _ each: (Row) -> Void) {var statement: OpaquePointer?guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK, let statement else { return }defer { sqlite3_finalize(statement) }for (n, value) in values.enumerated() {let i = Int32(n + 1)switch value {case .null: sqlite3_bind_null(statement, i)case .int(let v): sqlite3_bind_int64(statement, i, v)case .double(let v): sqlite3_bind_double(statement, i, v)case .text(let v): sqlite3_bind_text(statement, i, v, -1, Self.transient)case .blob(let v): _ = v.withUnsafeBytes { sqlite3_bind_blob(statement, i, $0.baseAddress, Int32(v.count), Self.transient) } } }while sqlite3_step(statement) == SQLITE_ROW { each(Row(statement: statement)) } }}/// The stop Keep's PhotoKit reads ask from PhotoKit's own queues: Stop, or the end of the background time.finalclassKeepStop: @unchecked Sendable {privatelet lock = NSLock()privatevar stopped = falsevar value: Bool { lock.lock(); defer { lock.unlock() }; return stopped }func set(_ value: Bool) { lock.lock(); stopped = value; lock.unlock() }}/// Keep's rules that need no phone, tested on their own (AlbumsKeepStoreTests).enumKeepRule {/// How Keep's files go up: Wi-Fi only unless he turned on mobile data (the drain holds `wifi` off Wi-Fi).staticfunc network(cellular: Bool) -> String { cellular ? "any" : "wifi" }/// Whether a read in flight may go on: not stopped (Stop, the end of the background time), on a network Keep may/// use, and the album still kept. Asked as each piece arrives; false cancels the read.staticfunc mayGo(stopped: Bool, cellular: Bool, onWiFi: Bool, keeping: Bool) -> Bool { !stopped && (cellular || onWiFi) && keeping }/// One original as `media.uploads` answered.structFile: Sendable, Equatable {let key: String, phase: Stringvar sent: Int64? = nil, total: Int64? = nil, code: String? = nil, line: String? = nil }structVerdict: Sendable, Equatable {/// Every original uploaded, by the object's answer.var confirmed: [String] = []/// An original Cotton will not take: the photo could not be kept, with the reason.var refused: [Refusal] = []/// Cotton's queue no longer knows an original: kept again (the same file is the same file in Cotton).var lost: [String] = []/// Originals still on their way, and their bytes not yet sent.var files = 0var bytes: Int64 = 0 }structRefusal: Sendable, Equatable { let asset: String, code: String, why: String }/// Per photo, from its own originals only (review H1): never "the queue emptied".staticfunc verdict(_ sending: [AlbumsStore.KeptSending], _ files: [String: File]) -> Verdict {var out = Verdict()for one in sending {let mine = one.keys.map { files[$0] ?? File(key: $0, phase: "unknown") }iflet refused = mine.first(where: { $0.phase == "failed" }) { out.refused.append(Refusal(asset: one.asset, code: refused.code ?? "refused", why: String((refused.line ?? "").prefix(200)))) } elseif mine.isEmpty || mine.contains(where: { $0.phase == "unknown" }) { out.lost.append(one.asset) } elseif mine.allSatisfy({ $0.phase == "uploaded" }) { out.confirmed.append(one.asset) } else {for file in mine where file.phase != "uploaded" { out.files += 1 out.bytes += max(0, (file.total ?? 0) - (file.sent ?? 0)) } } }return out }}#endif