Cotton code
99 lines · 5.1 KB · SwiftRaw
// Cotton Albums' writes to the photo library: the ONLY code in any build that makes, renames or deletes an album or// deletes a photo (`AlbumsLibrary.writes` in CottonUI forwards here). In the app target, never the package, so a// test bundle cannot reach it; and not compiled at all into an app whose flavour says `photoWrites: false`// (`COTTON_NO_PHOTO_WRITES`, ios-spec-gate): Cotton Albums' first build only looks (owner, 27 Nov), so its binary// holds no call to `PHPhotoLibrary.performChanges`; and only ever into Cotton Albums (`COTTON_ALBUMS`). Guard: scripts/__tests__/business-flavour.test.ts ("albums: the look-only build").#if COTTON_ALBUMS && !COTTON_NO_PHOTO_WRITESimport CottonUIimport Foundationimport Photosstruct SystemAlbumsWrites: AlbumsWrites {    /// Makes a real album in Photos holding `ids`; answers its id. Needs full access (limited access "can't create or    /// fetch user albums").    func makeAlbum(_ title: String, with ids: [String]) async throws -> String {        var placeholder: String?        try await PHPhotoLibrary.shared().performChanges {            let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title)            placeholder = request.placeholderForCreatedAssetCollection.localIdentifier            let assets = PHAsset.fetchAssets(withLocalIdentifiers: ids, options: nil)            if assets.count > 0 { request.addAssets(assets) }        }        guard let placeholder else { throw AlbumsLibraryError.notMade }        return placeholder    }    func add(_ ids: [String], to albumID: String) async throws {        guard let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumID], options: nil).firstObject,              collection.canPerform(.addContent) else { throw AlbumsLibraryError.cannotAdd }        try await PHPhotoLibrary.shared().performChanges {            let assets = PHAsset.fetchAssets(withLocalIdentifiers: ids, options: nil)            PHAssetCollectionChangeRequest(for: collection)?.addAssets(assets)        }    }    func rename(_ albumID: String, to title: String) async throws {        guard let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumID], options: nil).firstObject,              collection.canPerform(.rename) else { throw AlbumsLibraryError.cannotAdd }        try await PHPhotoLibrary.shared().performChanges {            PHAssetCollectionChangeRequest(for: collection)?.title = title        }    }    /// Deletes the album, never its photos.    func deleteAlbum(_ albumID: String) async throws {        let found = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumID], options: nil)        guard found.count > 0 else { return }        try await PHPhotoLibrary.shared().performChanges {            PHAssetCollectionChangeRequest.deleteAssetCollections(found)        }    }    // MARK: Deleting    /// Only ever called from his Delete tap on this phone, with exactly the ids the screen showed (coordinator's rule    /// C): nothing else in Albums asks the system to delete.    ///    /// Deletes `ids` from the library: one phone confirmation for each batch (one batch unless it is very large),    /// then a re-read of what is really gone. The confirmation's answer can be lost (iOS 18.5–27 after a ProRAW    /// capture), so each batch waits at most `timeout` seconds and then reads the library instead of assuming.    /// Photos keeps what went in Recently Deleted for 30 days.    func delete(_ ids: [String], batch: Int = 10_000, timeout: TimeInterval = 300) async -> LibraryDeleteOutcome {        var gone = 0        var refused = false        var timedOut = false        for start in stride(from: 0, to: ids.count, by: batch) {            let part = Array(ids[start..<min(ids.count, start + batch)])            let answer = await Self.withTimeout(timeout) {                do {                    try await PHPhotoLibrary.shared().performChanges {                        PHAssetChangeRequest.deleteAssets(PHAsset.fetchAssets(withLocalIdentifiers: part, options: nil))                    }                    return true                } catch {                    return false                }            }            let left = PHAsset.fetchAssets(withLocalIdentifiers: part, options: nil).count            gone += part.count - left            switch answer {            case nil: timedOut = true            case false?: if left == part.count { refused = true }            case true?: break            }            if refused { break }        }        return LibraryDeleteOutcome(asked: ids.count, gone: gone, refused: refused, timedOut: timedOut)    }    private static func withTimeout<T: Sendable>(_ seconds: TimeInterval, _ work: @escaping @Sendable () async -> T) async -> T? {        await withTaskGroup(of: T?.self) { group in            group.addTask { await work() }            group.addTask { try? await Task.sleep(for: .seconds(seconds)); return nil }            let first = await group.next() ?? nil            group.cancelAll()            return first        }    }}#endif