660 lines · 34.7 KB · SwiftRaw
// Cotton Albums' photo library through PhotoKit: the ONLY code in any build that names PhotoKit's library for Albums// (`AlbumsLibrary` in CottonUI forwards here through `AlbumsPhotos`). In the app target, compiled only into Cotton Albums// (`COTTON_ALBUMS`, set by ios-spec-gate from the albums flavour's `conditions`): an app that does not use photos must// not reference PHPhotoLibrary, or App Store processing refuses it without a photo purpose string (ITMS-90683; the// Sites archive check at 5a7a2bd6a1, 27 Nov 2026). Each synchronous PhotoKit read drains its own autorelease pool: a// 64,000-item pass runs these in long loops off the main thread, where nothing else drains them. Guard: scripts/__tests__/business-flavour.test.ts ("albums: PhotoKit// is compiled only into Albums").#if COTTON_ALBUMSimport CottonUIimport CoreGraphicsimport Foundationimport ImageIOimport Photosimport UIKitimport UniformTypeIdentifiers/// The phone's library through PhotoKit. Everything here is metadata or a small local picture; no network, ever.final class SystemAlbumsPhotos: NSObject, AlbumsPhotos, @unchecked Sendable, PHPhotoLibraryChangeObserver { private let images = PHCachingImageManager() private var observers: [UUID: @Sendable (LibraryChange) -> Void] = [:] private let lock = NSLock() private var registered = false /// KEEP 1e: the kept albums' and kept photos' fetch results, held so a change names what LEFT them (review M1). private var keptAlbums: [String: PHFetchResult<PHAsset>] = [:] private var keptPhotos: PHFetchResult<PHAsset>? private var keptSeen: (@Sendable (KeptChange) -> Void)? // MARK: Access var access: AlbumsAccess { Self.access(PHPhotoLibrary.authorizationStatus(for: .readWrite)) } static func access(_ status: PHAuthorizationStatus) -> AlbumsAccess { switch status { case .authorized: .full case .limited: .limited case .denied: .denied case .restricted: .restricted default: .unasked } } /// Asks once; the phone's own question. Answers what was chosen. func ask() async -> AlbumsAccess { Self.access(await PHPhotoLibrary.requestAuthorization(for: .readWrite)) } /// With limited access, the phone's own picker of which photos Albums may see. @MainActor func chooseMore(from controller: UIViewController) { PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: controller) } // MARK: Reading /// Every photo and video, oldest first, every shot of a burst included. Hidden photos come only when the phone /// lets them (the Hidden album asks for Face ID by default, and then they are not returned). /// The whole library, and whether its absences may be read as deletions (coordinator's rule A, 27 Nov: absence /// never removes a choice): only with full access and an enumeration that ran to its end. With limited access a /// shorter list is only what he chose to show. func enumerate() -> (assets: [LibraryAsset], complete: Bool) { let full = access == .full let found = assets() return (found, full && found.count == count()) } func assets() -> [LibraryAsset] { autoreleasepool { allAssets() } } private func allAssets() -> [LibraryAsset] { let options = PHFetchOptions() options.includeAllBurstAssets = true options.includeHiddenAssets = true options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] options.predicate = NSPredicate(format: "mediaType == %d || mediaType == %d", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue) let found = PHAsset.fetchAssets(with: options) var out: [LibraryAsset] = [] out.reserveCapacity(found.count) found.enumerateObjects { asset, _, _ in out.append(Self.read(asset)) } return out } func count() -> Int { let options = PHFetchOptions() options.includeAllBurstAssets = true options.includeHiddenAssets = true options.predicate = NSPredicate(format: "mediaType == %d || mediaType == %d", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue) return PHAsset.fetchAssets(with: options).count } func assets(_ ids: [String]) -> [LibraryAsset] { autoreleasepool { someAssets(ids) } } private func someAssets(_ ids: [String]) -> [LibraryAsset] { let options = PHFetchOptions() options.includeAllBurstAssets = true options.includeHiddenAssets = true let found = PHAsset.fetchAssets(withLocalIdentifiers: ids, options: options) var out: [LibraryAsset] = [] found.enumerateObjects { asset, _, _ in out.append(Self.read(asset)) } return out } static func read(_ asset: PHAsset) -> LibraryAsset { var flags: LibraryAsset.Flags = [] let sub = asset.mediaSubtypes if sub.contains(.photoScreenshot) { flags.insert(.screenshot) } if sub.contains(.photoLive) { flags.insert(.live) } if sub.contains(.photoHDR) { flags.insert(.hdr) } if sub.contains(.photoPanorama) { flags.insert(.panorama) } if sub.contains(.photoDepthEffect) { flags.insert(.depth) } if sub.contains(.videoScreenRecording) { flags.insert(.screenRecording) } if sub.contains(.videoCinematic) { flags.insert(.cinematic) } if sub.contains(.videoHighFrameRate) { flags.insert(.slowMo) } if sub.contains(.videoTimelapse) { flags.insert(.timelapse) } if asset.isFavorite { flags.insert(.favourite) } if asset.isHidden { flags.insert(.hidden) } if asset.burstIdentifier != nil, asset.burstSelectionTypes.contains(.userPick) || asset.burstSelectionTypes.contains(.autoPick) { flags.insert(.burstPick) } if !asset.sourceType.contains(.typeUserLibrary) { flags.insert(.notCameraRoll) } let kind: LibraryAsset.Kind = switch asset.mediaType { case .image: .photo case .video: .video case .audio: .audio default: .other } return LibraryAsset( id: asset.localIdentifier, kind: kind, flags: flags, created: asset.creationDate, modified: asset.modificationDate, width: asset.pixelWidth, height: asset.pixelHeight, duration: asset.duration, burst: asset.burstIdentifier, latitude: asset.location?.coordinate.latitude, longitude: asset.location?.coordinate.longitude ) } /// Apple's cloud identifiers for these assets, the same on every Apple device on one iCloud library. func cloudIDs(_ ids: [String]) -> [String: String] { var out: [String: String] = [:] for (id, result) in PHPhotoLibrary.shared().cloudIdentifierMappings(forLocalIdentifiers: ids) { if case .success(let cloud) = result { out[id] = cloud.stringValue } } return out } // MARK: Sizes /// What each asset takes on disk: every resource of it summed (a Live photo's picture and its film, an edit and /// its original). Exact where the phone says; else "about". func size(_ asset: LibraryAsset) -> LibrarySize { guard let phAsset = PHAsset.fetchAssets(withLocalIdentifiers: [asset.id], options: nil).firstObject else { return LibrarySize(bytes: asset.aboutBytes, exact: false, filename: nil) } return size(phAsset, asset) } func sizes(_ assets: [LibraryAsset]) -> [String: LibrarySize] { autoreleasepool { someSizes(assets) } } private func someSizes(_ assets: [LibraryAsset]) -> [String: LibrarySize] { let byID = Dictionary(assets.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) let found = PHAsset.fetchAssets(withLocalIdentifiers: assets.map(\.id), options: nil) var out: [String: LibrarySize] = [:] found.enumerateObjects { phAsset, _, _ in if let asset = byID[phAsset.localIdentifier] { out[asset.id] = self.size(phAsset, asset) } } return out } private func size(_ phAsset: PHAsset, _ asset: LibraryAsset) -> LibrarySize { let resources = PHAssetResource.assetResources(for: phAsset) var total: Int64 = 0 var known = !resources.isEmpty for resource in resources { if let bytes = Self.bytes(resource) { total += bytes } else { known = false } } let name = resources.first(where: { $0.type == .photo || $0.type == .video })?.originalFilename ?? resources.first?.originalFilename let parts = resources.map { LibrarySize.Part(kind: Self.partName($0.type), bytes: Self.bytes($0), filename: $0.originalFilename) } if known, total > 0 { return LibrarySize(bytes: total, exact: true, filename: name, parts: parts) } return LibrarySize(bytes: asset.aboutBytes, exact: false, filename: name, parts: parts) } static func partName(_ type: PHAssetResourceType) -> String { switch type { case .photo: "photo" case .video: "video" case .audio: "audio" case .alternatePhoto: "alternate_photo" case .fullSizePhoto: "edited_photo" case .fullSizeVideo: "edited_video" case .adjustmentData: "adjustments" case .adjustmentBasePhoto: "adjustment_base_photo" case .pairedVideo: "live_video" case .fullSizePairedVideo: "edited_live_video" case .adjustmentBasePairedVideo: "adjustment_base_live_video" case .adjustmentBaseVideo: "adjustment_base_video" case .photoProxy: "photo_proxy" @unknown default: "other" } } /// One resource's size: iOS 27's `dataSize` ("nil means unknown, not zero"), else the older `fileSize` key. static func bytes(_ resource: PHAssetResource) -> Int64? { if #available(iOS 27.0, *) { if let size = resource.dataSize { return Int64(size) } } return (resource.value(forKey: "fileSize") as? NSNumber)?.int64Value } // MARK: Pictures /// The original's long edge in pixels, nil when the asset is gone. func originalLongEdge(_ id: String) -> Int? { autoreleasepool { PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil).firstObject.map { max($0.pixelWidth, $0.pixelHeight) } } } /// One ask for a picture near `side`, the network off unless `network` (AlbumsPicture decides which ways to ask). func request(_ id: String, side: CGFloat, mode: AlbumsPictureMode, network: Bool) async -> LocalPicture { guard let asset = autoreleasepool(invoking: { PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil).firstObject }) else { return .failed("gone") } return await request(asset, side: side, mode: mode == .highQuality ? .highQualityFormat : .fastFormat, network: network) } private func request(_ asset: PHAsset, side: CGFloat, mode: PHImageRequestOptionsDeliveryMode, network: Bool = false) async -> LocalPicture { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = network options.deliveryMode = mode options.resizeMode = .fast options.isSynchronous = false options.version = .current let size = CGSize(width: side, height: side) return await withCheckedContinuation { done in images.requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: options) { image, info in let inCloud = (info?[PHImageResultIsInCloudKey] as? Bool) ?? false let degraded = (info?[PHImageResultIsDegradedKey] as? Bool) ?? false if let cg = image?.cgImage { done.resume(returning: .picture(cg, degraded: degraded)) } else if inCloud { done.resume(returning: .onlyInCloud) } else if let error = info?[PHImageErrorKey] as? NSError { done.resume(returning: error.domain == PHPhotosErrorDomain && error.code == PHPhotosError.networkAccessRequired.rawValue ? .onlyInCloud : .failed("\(error.domain) \(error.code)")) } else { done.resume(returning: .failed("no picture")) } } } } /// Dev: what each way of asking returns with the network off, for the report (coordinator, NEXT-SMALL-PICTURE.md): for up /// to `count` photos, the long edge, degraded flag, error and time of `.fastFormat`, `.opportunistic` (every /// callback, in order) and `.highQualityFormat`, each at 360 px. Written to Documents/albums-sizes.json. func measureSizes(count: Int) async { let options = PHFetchOptions() options.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) let found = PHAsset.fetchAssets(with: options) let step = max(1, found.count / max(1, count)) var rows: [[String: Any]] = [] for index in stride(from: 0, to: found.count, by: step).prefix(count) { let asset = found.object(at: index) var row: [String: Any] = ["original": max(asset.pixelWidth, asset.pixelHeight)] for (name, mode) in [("fast", PHImageRequestOptionsDeliveryMode.fastFormat), ("opportunistic", .opportunistic), ("highQuality", .highQualityFormat)] { let started = ContinuousClock.now let calls = await sizes(asset, mode: mode) let took = started.duration(to: .now) row[name] = ["calls": calls, "ms": Double(took.components.seconds) * 1000 + Double(took.components.attoseconds) / 1e15] } rows.append(row) } let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] if let data = try? JSONSerialization.data(withJSONObject: ["side": 360, "rows": rows], options: [.prettyPrinted]) { try? data.write(to: docs.appendingPathComponent("albums-sizes.json")) } print("albums: sizes measured for \(rows.count) photos") } /// Every callback one request makes: long edge (0 for none), degraded, in iCloud, error. private func sizes(_ asset: PHAsset, mode: PHImageRequestOptionsDeliveryMode) async -> [[String: Any]] { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = false options.deliveryMode = mode options.resizeMode = .fast options.version = .current final class Calls: @unchecked Sendable { var list: [[String: Any]] = []; var done = false } let calls = Calls() return await withCheckedContinuation { finish in images.requestImage(for: asset, targetSize: CGSize(width: 360, height: 360), contentMode: .aspectFit, options: options) { image, info in let degraded = (info?[PHImageResultIsDegradedKey] as? Bool) ?? false var call: [String: Any] = ["edge": image.map { Int(max($0.size.width * $0.scale, $0.size.height * $0.scale)) } ?? 0, "degraded": degraded] if (info?[PHImageResultIsInCloudKey] as? Bool) == true { call["inCloud"] = true } if let error = info?[PHImageErrorKey] as? NSError { call["error"] = "\(error.domain) \(error.code)" } calls.list.append(call) // Opportunistic calls again with the better picture; the last call is the one not degraded. if !degraded && !calls.done { calls.done = true finish.resume(returning: calls.list) } } } } /// A picture for a screen (a grid tile, a Set's shot), which may be degraded first and then sharpen. Never asks /// the network: a photo only in iCloud shows what the phone has. func thumbnail(_ id: String, side: CGFloat, deliver: @escaping @Sendable (UIImage?) -> Void) -> Int32? { guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil).firstObject else { deliver(nil); return nil } let options = PHImageRequestOptions() options.isNetworkAccessAllowed = false options.deliveryMode = .opportunistic options.resizeMode = .fast let scale = UITraitCollection.current.displayScale return images.requestImage(for: asset, targetSize: CGSize(width: side * scale, height: side * scale), contentMode: .aspectFill, options: options) { image, _ in deliver(image) } } func cancel(_ request: Int32) { images.cancelImageRequest(request) } // MARK: Albums /// Photos' albums he made, then the smart albums worth showing (Favourites, Screenshots and the others with /// anything in them), then shared iCloud albums. func albums() -> [LibraryAlbum] { var out: [LibraryAlbum] = [] let mine = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil) mine.enumerateObjects { collection, _, _ in out.append(Self.album(collection, .mine)) } // The SHELL BRIEF: his own albums, and of Photos' smart albums only Favourites and Screenshots. for subtype: PHAssetCollectionSubtype in [.smartAlbumFavorites, .smartAlbumScreenshots] { PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: subtype, options: nil).enumerateObjects { collection, _, _ in let album = Self.album(collection, .smart) if album.count > 0 { out.append(album) } } } PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumCloudShared, options: nil).enumerateObjects { collection, _, _ in out.append(Self.album(collection, .shared)) } return out } private static func album(_ collection: PHAssetCollection, _ kind: LibraryAlbum.Kind) -> LibraryAlbum { let options = PHFetchOptions() options.includeAllBurstAssets = false let count = PHAsset.fetchAssets(in: collection, options: options).count return LibraryAlbum(id: collection.localIdentifier, title: collection.localizedTitle ?? "", kind: kind, count: count, canAdd: collection.canPerform(.addContent)) } /// One album's assets, newest first. func members(of albumID: String) -> [String] { guard let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumID], options: nil).firstObject else { return [] } let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] var ids: [String] = [] PHAsset.fetchAssets(in: collection, options: options).enumerateObjects { asset, _, _ in ids.append(asset.localIdentifier) } return ids } // MARK: Keep func keepParts(_ id: String, into dir: URL, mayGo: @escaping @Sendable () -> Bool) async -> KeepParts { let hidden = PHFetchOptions() hidden.includeHiddenAssets = true guard let asset = autoreleasepool(invoking: { PHAsset.fetchAssets(withLocalIdentifiers: [id], options: hidden).firstObject }) else { return .gone } // A photo he hid in Photos is never read, whatever album it is in. if asset.isHidden { return .hidden } let chosen = Self.keepResources(asset) var parts: [KeepPart] = [] // A RAW-only photo (ProRAW, a camera's RAW): its RENDERED picture stands for it (review M2), drawn by PhotoKit // as he sees it, and its film if it is Live. if asset.mediaType == .image, !chosen.contains(where: { $0.role == "picture" }) { let url = dir.appendingPathComponent(UUID().uuidString + "-rendered") switch await Self.rendered(asset, to: url, mayGo: mayGo) { case .done(let mime, let ext): let named = url.appendingPathExtension(ext) try? FileManager.default.moveItem(at: url, to: named) let bytes = ((try? FileManager.default.attributesOfItem(atPath: named.path)[.size]) as? NSNumber)?.int64Value ?? 0 let base = (PHAssetResource.assetResources(for: asset).first?.originalFilename as NSString?)?.deletingPathExtension ?? "photo" parts.append(KeepPart(role: "picture", isVideo: false, url: named, mime: mime, filename: base + "." + ext, bytes: bytes)) case .stopped: try? FileManager.default.removeItem(at: url); return .stopped case .needsNetwork: try? FileManager.default.removeItem(at: url); return .needsNetwork case .failed(let why): try? FileManager.default.removeItem(at: url); return .failed(why) } } guard !chosen.isEmpty || !parts.isEmpty else { return .failed("no part") } for one in chosen { let name = one.resource.originalFilename let url = dir.appendingPathComponent(UUID().uuidString + "-" + name) let read = await Self.read(one.resource, to: url, mayGo: mayGo) guard case .done = read else { for part in parts { try? FileManager.default.removeItem(at: part.url) } try? FileManager.default.removeItem(at: url) switch read { case .stopped: return .stopped case .needsNetwork: return .needsNetwork case .failed(let why): return .failed(why) case .done: break } return .failed("unread") } let bytes = ((try? FileManager.default.attributesOfItem(atPath: url.path)[.size]) as? NSNumber)?.int64Value ?? 0 let mime = UTType(one.resource.uniformTypeIdentifier)?.preferredMIMEType ?? (one.video ? "video/quicktime" : "image/jpeg") parts.append(KeepPart(role: one.role, isVideo: one.video, url: url, mime: mime, filename: name, bytes: bytes)) } return .parts(parts) } private enum Read: Sendable { case done, stopped, needsNetwork, failed(String) } private enum Rendered: Sendable { case done(mime: String, ext: String), stopped, needsNetwork, failed(String) } /// A photo's picture as he sees it, rendered by PhotoKit (HEIC or JPEG), cancelled as `read` is. private static func rendered(_ asset: PHAsset, to url: URL, mayGo: @escaping @Sendable () -> Bool) async -> Rendered { final class State: @unchecked Sendable { let lock = NSLock(); var request: PHImageRequestID?; var stopped = false } let state = State() let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true options.deliveryMode = .highQualityFormat options.version = .current let manager = PHImageManager.default() options.progressHandler = { _, _, stop, _ in if !mayGo() { state.lock.lock(); state.stopped = true; state.lock.unlock() stop.pointee = true } } return await withCheckedContinuation { continuation in let id = manager.requestImageDataAndOrientation(for: asset, options: options) { data, uti, _, info in state.lock.lock(); let stopped = state.stopped; state.lock.unlock() if stopped || (info?[PHImageCancelledKey] as? Bool) == true { continuation.resume(returning: .stopped); return } if (info?[PHImageResultIsInCloudKey] as? Bool) == true, data == nil { continuation.resume(returning: .needsNetwork); return } guard let data else { let error = info?[PHImageErrorKey] as? NSError continuation.resume(returning: .failed(error.map { "\($0.domain) \($0.code)" } ?? "no picture")) return } let type = uti.flatMap { UTType($0) } ?? .jpeg guard !type.conforms(to: .rawImage), let mime = type.preferredMIMEType, let ext = type.preferredFilenameExtension else { continuation.resume(returning: .failed("no rendered picture")) return } do { try data.write(to: url); continuation.resume(returning: .done(mime: mime, ext: ext)) } catch { continuation.resume(returning: .failed("the scratch file could not be written")) } } state.lock.lock(); state.request = id; state.lock.unlock() } } /// One resource to a file, piece by piece, CANCELLED the moment `mayGo` answers false (review M3, M4): the /// network Keep may use went while an iCloud original was coming down, Stop, or the background time ran out. private static func read(_ resource: PHAssetResource, to url: URL, mayGo: @escaping @Sendable () -> Bool) async -> Read { guard FileManager.default.createFile(atPath: url.path, contents: nil), let handle = try? FileHandle(forWritingTo: url) else { return .failed("no scratch file") } final class State: @unchecked Sendable { let lock = NSLock() var request: PHAssetResourceDataRequestID? var stopped = false var finished = false var writeFailed = false } let state = State() let options = PHAssetResourceRequestOptions() options.isNetworkAccessAllowed = true let manager = PHAssetResourceManager.default() let outcome: Read = await withCheckedContinuation { continuation in let id = manager.requestData(for: resource, options: options, dataReceivedHandler: { data in if !mayGo() { state.lock.lock() let first = !state.stopped state.stopped = true let request = state.request state.lock.unlock() if first, let request { manager.cancelDataRequest(request) } return } do { try handle.write(contentsOf: data) } catch { state.lock.lock(); state.writeFailed = true; let request = state.request; state.lock.unlock() if let request { manager.cancelDataRequest(request) } } }, completionHandler: { error in state.lock.lock() guard !state.finished else { state.lock.unlock(); return } state.finished = true let stopped = state.stopped let writeFailed = state.writeFailed state.lock.unlock() if stopped { continuation.resume(returning: .stopped); return } if writeFailed { continuation.resume(returning: .failed("the scratch file could not be written")); return } if let error = error as NSError? { if error.domain == PHPhotosErrorDomain, error.code == PHPhotosError.networkAccessRequired.rawValue { continuation.resume(returning: .needsNetwork) } else if error.domain == NSCocoaErrorDomain, error.code == NSUserCancelledError { continuation.resume(returning: .stopped) } else { continuation.resume(returning: .failed("\(error.domain) \(error.code)")) } return } continuation.resume(returning: .done) }) state.lock.lock() state.request = id let stopNow = state.stopped && !state.finished state.lock.unlock() if stopNow { manager.cancelDataRequest(id) } } try? handle.close() return outcome } /// The resources Keep sends for one asset: the photo as he sees it now (rule D: an edit and a Live photo's film are /// parts of one item; a RAW photo's rendered picture stands for it, review M2), or a video as it is now. static func keepResources(_ asset: PHAsset) -> [(resource: PHAssetResource, role: String, video: Bool)] { let resources = PHAssetResource.assetResources(for: asset) func first(_ types: [PHAssetResourceType]) -> PHAssetResource? { for type in types { if let found = resources.first(where: { $0.type == type }) { return found } } return nil } var chosen: [(resource: PHAssetResource, role: String, video: Bool)] = [] if asset.mediaType == .video { if let film = first([.fullSizeVideo, .video]) { chosen.append((film, "picture", true)) } } else { // The picture he sees: an edit's full-size render, else the photo. For a RAW-only photo (no rendered // .photo), PhotoKit's .photo is the RAW: refused as a type here, never sent as one. if let picture = first([.fullSizePhoto, .photo]), !isRaw(picture) { chosen.append((picture, "picture", false)) } if let motion = first([.fullSizePairedVideo, .pairedVideo]) { chosen.append((motion, "motion", true)) } } return chosen } /// A RAW file (DNG, a camera's own RAW): Cotton's rules do not take one yet (review M2). static func isRaw(_ resource: PHAssetResource) -> Bool { guard let type = UTType(resource.uniformTypeIdentifier) else { return false } return type.conforms(to: .rawImage) } func keepBytes(_ ids: [String]) -> KeepSize { var size = KeepSize(bytes: 0, exact: true, raw: 0) autoreleasepool { PHAsset.fetchAssets(withLocalIdentifiers: ids, options: nil).enumerateObjects { asset, _, _ in if PHAssetResource.assetResources(for: asset).contains(where: { Self.isRaw($0) }) { size.raw += 1 } let chosen = Self.keepResources(asset) // A RAW-only photo is kept as its rendered picture, whose size PhotoKit does not say before it is drawn. if asset.mediaType == .image, !chosen.contains(where: { $0.role == "picture" }) { size.exact = false } for one in chosen { if let bytes = Self.bytes(one.resource) { size.bytes += bytes } else { size.exact = false } } } } return size } func keptMembers(of albumID: String) -> [String]? { // Limited access shows only the photos he chose: the album as Albums sees it then is not the album. guard PHPhotoLibrary.authorizationStatus(for: .readWrite) == .authorized, let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumID], options: nil).firstObject else { return nil } var ids: [String] = [] PHAsset.fetchAssets(in: collection, options: nil).enumerateObjects { asset, _, _ in ids.append(asset.localIdentifier) } return ids } func watchKept(albums: [String], assets: [String], seen: @escaping @Sendable (KeptChange) -> Void) { var results: [String: PHFetchResult<PHAsset>] = [:] for album in albums { if let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [album], options: nil).firstObject { results[album] = PHAsset.fetchAssets(in: collection, options: nil) } } let hidden = PHFetchOptions() hidden.includeHiddenAssets = true let photos = assets.isEmpty ? nil : PHAsset.fetchAssets(withLocalIdentifiers: assets, options: hidden) lock.lock() keptAlbums = results keptPhotos = photos keptSeen = seen let first = !registered registered = true lock.unlock() if first { PHPhotoLibrary.shared().register(self) } } /// What a change did to the kept albums and photos, by the library's own word (its removed objects), and the /// fetch results moved on to the change. private func keptChange(_ change: PHChange) -> KeptChange { lock.lock() defer { lock.unlock() } var out = KeptChange() for (album, result) in keptAlbums { guard let details = change.changeDetails(for: result) else { continue } let removed = details.removedObjects.map(\.localIdentifier) if !removed.isEmpty { out.left[album] = removed } if !details.insertedObjects.isEmpty { out.grew.append(album) } keptAlbums[album] = details.fetchResultAfterChanges } if let photos = keptPhotos, let details = change.changeDetails(for: photos) { out.deleted = details.removedObjects.map(\.localIdentifier) keptPhotos = details.fetchResultAfterChanges } return out } // MARK: Changes /// Calls `seen` with each change while Albums runs. Answers a key to stop. func observe(_ seen: @escaping @Sendable (LibraryChange) -> Void) -> UUID { let key = UUID() lock.lock() observers[key] = seen let first = !registered registered = true lock.unlock() if first { PHPhotoLibrary.shared().register(self) } return key } func stopObserving(_ key: UUID) { lock.lock() observers[key] = nil lock.unlock() } func photoLibraryDidChange(_ changeInstance: PHChange) { // "Read again": what changed by id is asked of the persistent changes, from the token saved last time. let kept = keptChange(changeInstance) lock.lock() let all = Array(observers.values) let keptSeen = self.keptSeen lock.unlock() if !kept.isEmpty { keptSeen?(kept) } for seen in all { seen(.changed(inserted: [], removed: [], updated: [])) } } private var lastToken: Data? { get { UserDefaults.standard.data(forKey: Self.tokenKey) } set { UserDefaults.standard.set(newValue, forKey: Self.tokenKey) } } private static let tokenKey = "albums.library.token" /// What changed since the token saved after the store last took the library in, by id; `.wholePass` when there /// is none or it expired. Answers the token to save once the store has taken the change in (`saveToken`), so a /// stop in between asks again rather than losing it. func changes() throws -> (LibraryChange, Data?) { let library = PHPhotoLibrary.shared() let current = try? NSKeyedArchiver.archivedData(withRootObject: library.currentChangeToken, requiringSecureCoding: true) guard let token = lastToken, let saved = try NSKeyedUnarchiver.unarchivedObject(ofClass: PHPersistentChangeToken.self, from: token) else { return (.wholePass, current) } let found: PHPersistentChangeFetchResult do { found = try library.fetchPersistentChanges(since: saved) } catch let error as NSError where error.domain == PHPhotosErrorDomain && error.code == PHPhotosError.persistentChangeTokenExpired.rawValue { return (.wholePass, current) } var inserted = Set<String>(), removed = Set<String>(), updated = Set<String>() for change in found { guard let details = try? change.changeDetails(for: .asset) else { continue } inserted.formUnion(details.insertedLocalIdentifiers) removed.formUnion(details.deletedLocalIdentifiers) updated.formUnion(details.updatedLocalIdentifiers) } return (.changed(inserted: Array(inserted), removed: Array(removed), updated: Array(updated.subtracting(inserted))), current) } func saveToken(_ token: Data?) { if let token { lastToken = token } } var hasToken: Bool { lastToken != nil }}#endif