// KEEP THIS ALBUM IN COTTON (KEEP slice 1, NEXT-ALBUM-KEEP.md; KEEP 1e, NEXT-KEEP-1E.md): a copy of each photo of an // album he chooses goes to his Cotton space, sealed on this phone, through the media path every app already uses // (`capture.media` → the `_media` ledger → the drain). What is kept is the photo as he sees it now (its edit, else its // original; a RAW photo's rendered picture) and a Live photo's film; a video as it is now (`AlbumsPhotos.keepParts`). // // The rules this file holds: // - "Kept" is the object's own answer, per file (`media.uploads`): a photo is kept when every original it put in the // queue is uploaded; one Cotton refused is "could not be kept", with the reason (review H1). // - A copy of a Photos original is not his for good on this phone: it is queued with `source: photos`, and once the // object holds it the local copy leaves (the core's release); the scratch read goes the moment it is handed over, // and any left by a kill is swept at launch (review H2). // - Never decided by absence: a read of the album that is not whole changes nothing; a photo is left or gone only // when the library REPORTS it so (a change observer), and only once it is in Cotton; one that never reached Cotton // and leaves the album is simply no longer queued (review M1). // - Wi-Fi only unless he turns on mobile data: the read from iCloud is cancelled the moment the path is not one Keep // may use, and every file is queued `network: wifi`, which the drain holds off Wi-Fi (review M4). At most ten // photos or 50 MB of Keep's own wait in the queue, counted from the store, so the bound holds from the first file // after a kill. // - Stop, Stop keeping and the end of the background time stop at once, cancel the read in flight, and nothing starts // again until the app is in front or a new background task is granted (review M3). // - Nothing is ever deleted from Photos or from Cotton. #if os(iOS) import BackgroundTasks import CottonKit import Foundation import Observation import SwiftUI @MainActor @Observable final class AlbumsKeeper { static let shared = AlbumsKeeper() private let store = AlbumsStore.shared @ObservationIgnored private var core: (any CottonCalling)? private(set) var running = false /// Kept albums, and their counts as last read (the screens draw these). private(set) var albums: [AlbumsStore.KeptAlbum] = [] private(set) var counts: [String: AlbumsStore.KeptCounts] = [:] private(set) var refusals: [String: [(code: String, n: Int)]] = [:] /// Keep's own originals handed over and not yet in Cotton, and their bytes, as the object last said. private(set) var onTheirWay: (files: Int, bytes: Int64) = (0, 0) /// Waiting for Wi-Fi: something is to be kept, and the network it may use is not here. private(set) var waitingForWiFi = false /// Changes whenever the counts do. private(set) var revision = 0 /// Stop, Stop keeping's run, or the end of the background time: cleared only by a deliberate start. @ObservationIgnored private let stopFlag = KeepStop() @ObservationIgnored private var continued: BGTask? @ObservationIgnored private var continuedProgress: Progress? @ObservationIgnored private var watching = false @ObservationIgnored private var uploadsUnanswered = false @ObservationIgnored private var saidNetwork: String? private var stopAsked: Bool { stopFlag.value } func use(_ core: any CottonCalling) { guard self.core == nil else { return } self.core = core // The network path is read by a monitor that answers a moment after it starts: start it now, so the first // Keep does not wait for Wi-Fi it is on. _ = AlbumsPass.onWiFi Self.sweepScratch() #if COTTON_DEV if ProcessInfo.processInfo.arguments.contains("-albums-keep-fresh") { store.forgetKept() } #endif refresh() } func refresh() { albums = store.keptAlbums() var out: [String: AlbumsStore.KeptCounts] = [:] var said: [String: [(code: String, n: Int)]] = [:] for album in albums { out[album.album] = store.keptCounts(album.album) said[album.album] = store.keptRefusals(album.album) } counts = out refusals = said revision += 1 } func kept(_ album: String) -> AlbumsStore.KeptAlbum? { albums.first { $0.album == album } } // MARK: His acts /// THE ONE CONSTANT that shows Keep in the real app (the coordinator's, for the cut: owner, 28 Nov, "photo backup /// into Cotton is the real direction"). True since the owner's decision (28 Nov): Keep is in his real Albums build. /// Keep only ever reads a photo (no photo-changing call exists in this package; the flavour test holds that). static let realFlavourKeeps = true /// Whether this build may keep at all: a Dev build always; the real app once `realFlavourKeeps` says so. /// scripts/__tests__/business-flavour.test.ts holds every way in to it. static var allowed: Bool { #if COTTON_DEV return true #else return realFlavourKeeps #endif } /// Keep: from now on every photo in this album has a copy in Cotton, and photos added later too. func keep(_ album: String, title: String, cellular: Bool) { guard Self.allowed else { return } store.keep(album, title: title, cellular: cellular) members() refresh() submitContinued() start() } /// Stop keeping: new photos are no longer kept, from this photo on (the loop asks before each one). Every copy /// already in Cotton stays, and the ones on their way go on. func stopKeeping(_ album: String) { store.stopKeeping(album) refresh() } // MARK: The album, as Photos has it now /// Every kept album's members, from a whole read only (`keptMembers` answers nil otherwise, which changes /// nothing), and the watch moved on to them. func members() { let library = AlbumsLibrary.shared for album in store.keptAlbums() { guard let now = library.keptMembers(of: album.album) else { continue } store.setKeptMembers(album.album, now, keeping: album.keeping, whole: true) } watch() } /// The library's word on kept albums and photos: taken out, deleted, added to. private func watch() { let kept = store.keptAlbums().map(\.album) guard !kept.isEmpty else { return } AlbumsLibrary.shared.watchKept(albums: kept, assets: store.keptAssets()) { change in Task { @MainActor in AlbumsKeeper.shared.reported(change) } } watching = true } func reported(_ change: KeptChange) { for (album, assets) in change.left { store.keptRemoved(album, assets) } store.keptDeleted(change.deleted) if !change.grew.isEmpty { members() } else { watch() } refresh() resume() } // MARK: Running /// A deliberate start (his Keep): clears a stop and runs. func start() { guard Self.allowed else { return } stopFlag.set(false) run() } /// The app is in front again (a launch, coming back, a library change while open): a stop left by the end of /// the background time is cleared then, and only then. func resume() { guard Self.allowed else { return } // At launch the app is still inactive: only the background is refused. guard UIApplication.shared.applicationState != .background else { return } start() } /// Runs while nothing has stopped it. func run() { guard !running, core != nil, !stopAsked else { return } Task { await loop() } } func stop() { stopFlag.set(true) } private func loop() async { guard !running, let core, !stopAsked else { return } running = true defer { running = false; refresh() } let started = ContinuousClock.now var handed = 0 var handedBytes: Int64 = 0 let capture = CoreMediaCapture(core: core) let stop = stopFlag while true { while !stopAsked { let next = store.toKeep(8) if next.isEmpty { break } var moved = false for one in next where !stopAsked { // Stop keeping stops at once: asked before every photo. guard store.keeping(one.album) else { continue } await keepPace() if stopAsked { break } let cellular = one.cellular guard Self.network(cellular: cellular) else { waitingForWiFi = true; break } waitingForWiFi = false // Over Cotton's limit for one file: said once, never read (a video is at most 500 MB). let size = await Task.detached { AlbumsLibrary.shared.keepBytes([one.asset]) }.value if size.exact, size.bytes > Self.mostBytes { store.keptRefused(one.asset, code: "too_big", why: "\(size.bytes) bytes") moved = true continue } let album = one.album let dir = Self.scratch() let parts = await AlbumsLibrary.shared.keepParts(one.asset, into: dir) { KeepRule.mayGo(stopped: stop.value, cellular: cellular, onWiFi: Self.onWiFi, keeping: AlbumsStore.shared.keeping(album)) } defer { try? FileManager.default.removeItem(at: dir) } switch parts { case .parts(let parts): var keys: [String] = [] var records: [String] = [] var bytes: Int64 = 0 var refused: (code: String, why: String)? var failed: String? let upload = CaptureUpload(network: KeepRule.network(cellular: cellular), askedBy: "albums.keep", source: "photos") for part in parts where refused == nil && failed == nil { do { let captured = try await capture.capture(file: part.url, mime: part.mime, kind: part.isVideo ? .video : .photo, filename: part.filename, upload: upload) keys.append(captured.key) records.append(captured.recordId) bytes += part.bytes } catch let error as CottonCallError where error.code == "too_large" { refused = ("too_big", error.message) } catch let error as CottonCallError where error.code == "bad_request" { refused = ("refused", error.message) } catch { failed = String("\(error)".prefix(200)) } // The scratch copy goes the moment it is handed over: the store holds its own. try? FileManager.default.removeItem(at: part.url) } if let refused { store.keptRefused(one.asset, code: refused.code, why: String(refused.why.prefix(200))) } else if let failed { // Tried again on the next run; what went over already is the same file again (one sha256). store.keptFailed(one.album, one.asset, why: failed) } else { store.keptSending(one.asset, keys: keys, records: records, bytes: bytes) handed += 1 handedBytes += bytes } moved = true case .stopped: // Not a failure: the network went, Stop, Stop keeping or the end of the background time. It waits. if !Self.network(cellular: cellular) { waitingForWiFi = true } case .hidden: // Hidden in Photos: never read, no longer queued. store.keptRemoved(one.album, [one.asset]) moved = true case .needsNetwork: store.keptFailed(one.album, one.asset, why: "needs network") moved = true case .gone: // Not found by this read: tried again, never taken as a deletion (only the library's word is). store.keptFailed(one.album, one.asset, why: "not found") moved = true case .failed(let why) where why == "no part": store.keptRefused(one.asset, code: "no_part", why: why) moved = true case .failed(let why): store.keptFailed(one.album, one.asset, why: why) moved = true } if waitingForWiFi { break } } refresh() setProgress() if handed > 0, handed % 50 < 8 { say(handed, handedBytes, started) } await checkUploads() if waitingForWiFi { // The continued task is for work that is going, not for waiting. if continued != nil { break } await waitForNetwork() } else if !moved { break } } // Handed over: wait for the object to confirm each (bounded: an hour, then the next run carries on). let deadline = ContinuousClock.now + .seconds(3600) var ticks = 0 var more = false let pending = Set(store.toKeep(100).map(\.asset)) while !stopAsked, onTheirWay.files > 0, ContinuousClock.now < deadline { // New photos in a kept album meanwhile: copied now, not after the wait. if store.toKeep(100).contains(where: { !pending.contains($0.asset) }) { more = true; break } try? await Task.sleep(for: .seconds(5)) await checkUploads() setProgress() ticks += 1 if ticks % 6 == 0 { say(handed, handedBytes, started) } } if !more || stopAsked { break } } say(handed, handedBytes, started) } /// Asks the object, per file, which handed-over photos it holds (`media.uploads`): one whose every original is /// uploaded is kept; one with a refused original could not be kept, with the reason; one the queue no longer knows /// at all waits to be kept again. /// Tells the core's drain the network (MEDIA DRAIN 1 item 2) when it changed: Wi-Fi-only files go up only while /// the core has heard `wifi`. private func sayNetwork() async { guard let core else { return } let path = Self.pathWord guard path != saidNetwork else { return } do { _ = try await core.call(CottonMethod.mediaNetwork, KeepNetworkSay(path: path), as: KeepNetworkSaid.self) saidNetwork = path } catch { Log.write("albums: keep: the core did not hear the network (\(error))") } } nonisolated static var pathWord: String { #if COTTON_DEV let off = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("albums-keep-no-wifi") if FileManager.default.fileExists(atPath: off.path) { return "mobile" } #endif return AlbumsPass.pathWord } private func checkUploads() async { await sayNetwork() guard let core else { return } let sending = store.keptSendingKeys() guard !sending.isEmpty else { onTheirWay = (0, 0); return } var files: [String: KeepUploads.File] = [:] let keys = sending.flatMap(\.keys) var at = 0 while at < keys.count { let page = Array(keys[at.. Self.ahead || onTheirWay.bytes > Self.aheadBytes { try? await Task.sleep(for: .seconds(2)) await checkUploads() ticks += 1 if ticks % 30 == 0 { Log.write("albums: keep: waiting for \(onTheirWay.files) files to upload") } } } private func waitForNetwork() async { Log.write("albums: keep: waiting for Wi-Fi") defer { Log.write("albums: keep: \(waitingForWiFi ? "still waiting for Wi-Fi" : "on Wi-Fi again")") } let deadline = ContinuousClock.now + .seconds(600) while !stopAsked, ContinuousClock.now < deadline { try? await Task.sleep(for: .seconds(2)) await sayNetwork() if Self.onWiFi { waitingForWiFi = false; return } } } private func say(_ handed: Int, _ bytes: Int64, _ started: ContinuousClock.Instant) { let all = store.keptCounts() let took = started.duration(to: .now) let seconds = Double(took.components.seconds) + Double(took.components.attoseconds) / 1e18 Log.write("albums: keep \(all.kept) kept, \(all.sending) sending, \(all.waiting) waiting, \(all.failed) failed, \(all.refused) refused, \(all.left) left, \(all.gone) gone of \(all.total); this run \(handed) handed over, \(bytes) bytes, \(Int(seconds)) s, \(onTheirWay.files) files on their way\(waitingForWiFi ? ", waiting for Wi-Fi" : "")") } /// The network keeping may use: Wi-Fi, or any when he turned on mobile data. static func network(cellular: Bool) -> Bool { cellular || onWiFi } nonisolated static var onWiFi: Bool { #if COTTON_DEV // The walk's Wi-Fi off on a simulator, which shares the Mac's network: Documents/albums-keep-no-wifi. let off = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("albums-keep-no-wifi") if FileManager.default.fileExists(atPath: off.path) { return false } #endif return AlbumsPass.onWiFi } nonisolated static func scratch() -> URL { let dir = FileManager.default.temporaryDirectory.appendingPathComponent("albums-keep-\(UUID().uuidString)", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) return dir } /// Scratch reads a kill left behind: swept at launch, before any read begins. nonisolated static func sweepScratch() { let tmp = FileManager.default.temporaryDirectory for name in (try? FileManager.default.contentsOfDirectory(atPath: tmp.path)) ?? [] where name.hasPrefix("albums-keep-") { try? FileManager.default.removeItem(at: tmp.appendingPathComponent(name)) } } // MARK: The background /// Started by his Keep tap: carries on when he leaves Albums, with the phone's own progress and Stop. The same /// wildcard the look pass is permitted under (`.pass.*`). nonisolated static var continuedID: String { (Bundle.main.bundleIdentifier ?? "com.cottondb.albums") + ".pass.keep" } nonisolated static func registerTask() { let permitted = Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? [] guard permitted.contains(where: { $0.hasSuffix(".pass.*") }) else { return } BGTaskScheduler.shared.register(forTaskWithIdentifier: continuedID, using: nil) { task in let held = KeepHeldTask(task) Task { @MainActor in await AlbumsKeeper.shared.runContinued(held.task) } } } private func runContinued(_ task: BGTask) async { continued = task continuedProgress = (task as? BGContinuedProcessingTask)?.progress // The end of the background time: stops at once and cancels the read in flight; nothing starts again until // the app is in front or a new task is granted. task.expirationHandler = { [stopFlag] in stopFlag.set(true) } // A new grant is a deliberate start. stopFlag.set(false) setProgress() // A run already going in the foreground carries on, reporting to this task. while running && !stopAsked { try? await Task.sleep(for: .seconds(1)) } if !stopAsked { await loop() } let all = store.keptCounts() task.setTaskCompleted(success: !stopAsked && all.waiting == 0 && all.sending == 0) continued = nil continuedProgress = nil } private func setProgress() { guard let progress = continuedProgress else { return } let all = store.keptCounts() let active = all.waiting + all.sending + all.kept + all.failed + all.refused progress.totalUnitCount = Int64(max(1, active)) progress.completedUnitCount = Int64(all.kept + all.refused) } private func submitContinued() { let permitted = Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? [] guard permitted.contains(where: { $0.hasSuffix(".pass.*") }) else { return } let waiting = store.keptCounts().waiting let request = BGContinuedProcessingTaskRequest(identifier: Self.continuedID, title: AlbumsWords.keeping(waiting), subtitle: AlbumsWords.keepingLine) request.strategy = .queue do { try BGTaskScheduler.shared.submit(request) } catch { Log.write("albums: keep: continued task not taken (\(error.localizedDescription))") } } } /// A task the scheduler hands over on its own queue, carried to the main actor that alone touches it after. private struct KeepHeldTask: @unchecked Sendable { let task: BGTask init(_ task: BGTask) { self.task = task } } /// `media.uploads`'s question. struct KeepUploadsAsk: Encodable { let keys: [String] } struct KeepNetworkSay: Encodable { let path: String } struct KeepNetworkSaid: Decodable { let path: String } /// `media.uploads`'s answer, the part Keep reads. struct KeepUploads: Decodable { struct File: Decodable { let key: String let phase: String let sent: Int64? let total: Int64? let code: String? let line: String? } let files: [File] } // MARK: - The screens /// On a Photos album of his: "Keep this album in Cotton", or, once kept, where its photos are. struct AlbumsKeepBand: View { let model: AlbumsModel let id: String let title: String private let keeper = AlbumsKeeper.shared @State private var asking = false private func say(_ path: String, _ fills: [String: String] = [:]) -> String { AlbumsWords.keep(path, fills) } var body: some View { let _ = keeper.revision Group { if let kept = keeper.kept(id) { band(kept, keeper.counts[id] ?? AlbumsStore.KeptCounts()) } else { Button { model.sheet = .keep(id: id, title: title) } label: { HStack(alignment: .center, spacing: 14) { Image(systemName: "icloud.and.arrow.up").font(.system(size: 18, weight: .light)).foregroundStyle(Olive.ink).accessibilityHidden(true) VStack(alignment: .leading, spacing: 3) { Text(verbatim: say("row")).font(AlbumsType.name).foregroundStyle(Olive.ink) Text(verbatim: say("ask_line")).font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true) } .frame(maxWidth: .infinity, alignment: .leading) Image(systemName: "chevron.right").font(.system(size: 13, weight: .semibold)).foregroundStyle(Olive.quiet).accessibilityHidden(true) } .padding(.vertical, 12) .overlay(alignment: .top) { Rectangle().fill(Olive.ink).frame(height: 2) } .overlay(alignment: .bottom) { AlbumsRule() } .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityIdentifier("albums-keep-row") } } .padding(.horizontal, Olive.side).padding(.top, 12) } private func band(_ kept: AlbumsStore.KeptAlbum, _ c: AlbumsStore.KeptCounts) -> some View { let active = c.waiting + c.sending + c.kept + c.failed + c.refused let size = AlbumsWords.size(c.bytes) // Going: something waits, is on its way, or will be tried again. let going = c.waiting + c.sending + c.retrying > 0 let head: String = { if !kept.keeping { return say("stopped", ["n": c.kept.formatted()]) } if !going { return say("done", ["n": c.kept.formatted(), "size": size]) } return say("band_head", ["n": active.formatted()]) }() var lines: [String] = [] if kept.keeping, going { // Kept: the object answered for every original of it. lines.append(say("band_progress", ["done": c.kept.formatted(), "n": active.formatted(), "size": size])) } if c.sending > 0, keeper.onTheirWay.files > 0 { lines.append(say(kept.keeping ? "sending_line" : "stopped_sending", ["n": keeper.onTheirWay.files.formatted()])) } if kept.keeping, going { if keeper.waitingForWiFi { lines.append(say("band_wifi")) } else if c.waiting > 0 { lines.append(say("band_away")) } } if c.retrying > 0 { lines.append(say("failed", ["n": c.retrying.formatted()])) } if c.failed > c.retrying { lines.append(say("failed_stopped", ["n": (c.failed - c.retrying).formatted()])) } for refusal in keeper.refusals[id] ?? [] { lines.append(say("refused", ["n": refusal.n.formatted(), "why": say("why_\(refusal.code)")])) } if c.left + c.gone > 0 { lines.append(say("left_line", ["n": (c.left + c.gone).formatted()])) } return AlbumsBand(head: head, lines: lines, end: { if kept.keeping { Button(say("stop")) { asking = true } .buttonStyle(AlbumsOutlineButtonStyle()) .accessibilityIdentifier("albums-keep-stop") } }, below: { if kept.keeping, going, active > 0 { AlbumsProgressBar(fraction: Double(c.kept + c.refused) / Double(active), paused: keeper.waitingForWiFi) } }) .accessibilityElement(children: .contain) .accessibilityIdentifier("albums-keep-band") .confirmationDialog(say("stop_ask"), isPresented: $asking, titleVisibility: .visible) { Button(say("stop")) { keeper.stopKeeping(id) } Button(say("cancel"), role: .cancel) {} } message: { Text(verbatim: say("stop_line", ["n": c.kept.formatted()])) } } } /// The ask before keeping: what it is, what it weighs, how RAW photos are kept, and the mobile data switch. struct AlbumsKeepSheet: View { let id: String let title: String let close: () -> Void @State private var cellular = false @State private var count = 0 @State private var size = KeepSize() @State private var measured = false private func say(_ path: String, _ fills: [String: String] = [:]) -> String { AlbumsWords.keep(path, fills) } var body: some View { VStack(alignment: .leading, spacing: 0) { Text(verbatim: say("ask_title", ["title": title])).font(AlbumsType.sans(25, .bold, .title2)).foregroundStyle(Olive.ink) .fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader) Text(verbatim: say("ask_size", ["n": count.formatted(), "size": AlbumsWords.size(size.bytes, exact: size.exact)])) .font(AlbumsType.name).foregroundStyle(Olive.ink).padding(.top, 10) .accessibilityIdentifier("albums-keep-size") Text(verbatim: say("row_line")) .font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 6) Text(verbatim: say("ask_line")).font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 6) if size.raw > 0 { Text(verbatim: say("raw_line", ["n": size.raw.formatted()])).font(AlbumsType.line).foregroundStyle(Olive.quiet) .fixedSize(horizontal: false, vertical: true).padding(.top, 6) .accessibilityIdentifier("albums-keep-raw-line") } Toggle(isOn: $cellular) { Text(verbatim: say("cellular")).font(AlbumsType.name).foregroundStyle(Olive.ink) } .tint(Olive.accent).padding(.vertical, 10) .overlay(alignment: .bottom) { AlbumsRule() } .padding(.top, 14) .accessibilityIdentifier("albums-keep-cellular") Button(say("keep")) { close() AlbumsKeeper.shared.keep(id, title: title, cellular: cellular) } .buttonStyle(AlbumsMainButtonStyle()) .disabled(count == 0) .padding(.top, 20) .accessibilityIdentifier("albums-keep-yes") } .task { guard !measured else { return } measured = true let album = id // Exactly what Keep sends (no RAW file), from PhotoKit's own sizes, off the main thread. His space is said // only when the object has said it (from 80% full), never a number assumed. let read = await Task.detached { () -> (Int, KeepSize) in let members = AlbumsLibrary.shared.keptMembers(of: album) ?? AlbumsLibrary.shared.members(of: album) return (members.count, AlbumsLibrary.shared.keepBytes(members)) }.value count = read.0 size = read.1 } } } #endif