| 1 | #if os(iOS) |
| 2 | import SwiftUI |
| 3 | import Photos |
| 4 | import PhotosUI |
| 5 | import EquipoShareCore |
| 6 | |
| 7 | @MainActor @Observable final class RecentScreenshot: NSObject, PHPhotoLibraryChangeObserver { |
| 8 | var policy = ScreenshotPolicy(explained: UserDefaults.standard.bool(forKey: "screenshot.explained")) |
| 9 | var asset: PHAsset? |
| 10 | var thumbnail: UIImage? |
| 11 | var permission: PHAuthorizationStatus { PHPhotoLibrary.authorizationStatus(for: .readWrite) } |
| 12 | private var active = false |
| 13 | private var observing = false |
| 14 | private var generation = UUID() |
| 15 | private var fetching: PHImageRequestID? |
| 16 | override init() { |
| 17 | super.init() |
| 18 | #if DEBUG && targetEnvironment(simulator) |
| 19 | if ProcessInfo.processInfo.environment["EQUIPO_SCREENSHOT_FIXTURE"] == "permission" { policy = ScreenshotPolicy(explained: false) } |
| 20 | #endif |
| 21 | } |
| 22 | func start() { |
| 23 | #if DEBUG && targetEnvironment(simulator) |
| 24 | if ProcessInfo.processInfo.environment["EQUIPO_SCREENSHOT_FIXTURE"] == "chip" { |
| 25 | active = true; thumbnail = UIImage(data: AttachmentsFixture.image); return |
| 26 | } |
| 27 | #endif |
| 28 | guard !active else { refresh(); return } |
| 29 | active = true; refresh() |
| 30 | } |
| 31 | func stop() { |
| 32 | active = false |
| 33 | if observing { PHPhotoLibrary.shared().unregisterChangeObserver(self); observing = false } |
| 34 | generation = UUID(); asset = nil; thumbnail = nil |
| 35 | if let fetching { PHImageManager.default().cancelImageRequest(fetching); self.fetching = nil } |
| 36 | } |
| 37 | nonisolated func photoLibraryDidChange(_ changeInstance: PHChange) { Task { @MainActor [weak self] in self?.refresh() } } |
| 38 | func explain() { policy.plusTapped() } |
| 39 | func decline() { policy.decline(); UserDefaults.standard.set(true, forKey: "screenshot.explained") } |
| 40 | func requestPermission() async { |
| 41 | decline() |
| 42 | _ = await PHPhotoLibrary.requestAuthorization(for: .readWrite) |
| 43 | refresh() |
| 44 | } |
| 45 | func refresh(now: Date = Date()) { |
| 46 | policy.prune(now: now) |
| 47 | if let fetching { PHImageManager.default().cancelImageRequest(fetching); self.fetching = nil } |
| 48 | generation = UUID(); let generation = generation |
| 49 | guard active, permission == .authorized || permission == .limited else { |
| 50 | if observing { PHPhotoLibrary.shared().unregisterChangeObserver(self); observing = false } |
| 51 | asset = nil; thumbnail = nil; return |
| 52 | } |
| 53 | // Registering before authorization can trigger the system prompt. |
| 54 | // The only prompt belongs to the explicit Choose screenshots action. |
| 55 | if !observing { PHPhotoLibrary.shared().register(self); observing = true } |
| 56 | let options = PHFetchOptions() |
| 57 | options.predicate = NSPredicate(format: "(mediaSubtype & %d) != 0 AND creationDate >= %@ AND creationDate <= %@", PHAssetMediaSubtype.photoScreenshot.rawValue, now.addingTimeInterval(-300) as NSDate, now as NSDate) |
| 58 | options.includeHiddenAssets = false |
| 59 | options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]; options.fetchLimit = 1 |
| 60 | guard let candidate = PHAsset.fetchAssets(with: .image, options: options).firstObject, |
| 61 | let created = candidate.creationDate, |
| 62 | policy.eligible(id: candidate.localIdentifier, created: created, isScreenshot: candidate.mediaSubtypes.contains(.photoScreenshot), hidden: candidate.isHidden, permitted: true, now: now) else { asset = nil; thumbnail = nil; return } |
| 63 | let request = PHImageRequestOptions(); request.isNetworkAccessAllowed = false; request.deliveryMode = .fastFormat |
| 64 | fetching = PHImageManager.default().requestImage(for: candidate, targetSize: CGSize(width: 120, height: 120), contentMode: .aspectFit, options: request) { [weak self] image, _ in |
| 65 | Task { @MainActor in |
| 66 | guard let self, self.active, self.generation == generation, let image else { return } |
| 67 | self.asset = candidate; self.thumbnail = image |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | func dismiss() { |
| 72 | if let asset, let date = asset.creationDate { policy.dismiss(asset.localIdentifier, created: date) } |
| 73 | generation = UUID(); asset = nil; thumbnail = nil |
| 74 | } |
| 75 | func attach(to draft: AttachmentDraft) async { |
| 76 | guard let asset, let created = asset.creationDate, |
| 77 | policy.eligible(id: asset.localIdentifier, created: created, isScreenshot: asset.mediaSubtypes.contains(.photoScreenshot), hidden: asset.isHidden, permitted: permission == .authorized || permission == .limited, now: Date()), |
| 78 | PHAsset.fetchAssets(withLocalIdentifiers: [asset.localIdentifier], options: nil).count == 1 else { refresh(); return } |
| 79 | let generation = generation |
| 80 | let options = PHContentEditingInputRequestOptions(); options.isNetworkAccessAllowed = false |
| 81 | let url: URL? = await withCheckedContinuation { continuation in |
| 82 | asset.requestContentEditingInput(with: options) { input, _ in continuation.resume(returning: input?.fullSizeImageURL) } |
| 83 | } |
| 84 | guard active, self.generation == generation, let url else { return } |
| 85 | let directory = FileManager.default.temporaryDirectory.appendingPathComponent("screenshot-" + UUID().uuidString) |
| 86 | var transferred = false |
| 87 | defer { if !transferred { try? FileManager.default.removeItem(at: directory) } } |
| 88 | do { |
| 89 | let worker = Task.detached { try autoreleasepool { try AttachmentFile.prepareFile(url, directory: directory, name: "Screenshot.png") } } |
| 90 | let file = try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() } |
| 91 | guard active, self.generation == generation else { return } |
| 92 | dismiss() |
| 93 | transferred = true |
| 94 | await draft.add(staged: file, directory: directory) |
| 95 | } catch { refresh() } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | struct ScreenshotChip: View { |
| 100 | let model: RecentScreenshot |
| 101 | let draft: AttachmentDraft |
| 102 | var body: some View { |
| 103 | if let thumbnail = model.thumbnail { |
| 104 | HStack { |
| 105 | Button { Task { await model.attach(to: draft) } } label: { |
| 106 | HStack { |
| 107 | Image(uiImage: thumbnail).resizable().scaledToFit().frame(width: 38, height: 44) |
| 108 | Text(EquipoStrings.text("native.screenshot.offer")).font(Typo.secondary) |
| 109 | }.frame(minHeight: 44) |
| 110 | }.buttonStyle(.plain) |
| 111 | Spacer(minLength: 4) |
| 112 | Button { model.dismiss() } label: { Image(systemName: "xmark").frame(width: 44, height: 44) } |
| 113 | .accessibilityLabel(EquipoStrings.text("chat.connections.dismiss")) |
| 114 | }.padding(.leading, 8).background(Palette.surface2, in: RoundedRectangle(cornerRadius: 10)) |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | struct ScreenshotPermission: View { |
| 119 | let choose: () -> Void |
| 120 | let decline: () -> Void |
| 121 | var body: some View { |
| 122 | VStack(alignment: .leading, spacing: 20) { |
| 123 | Text(EquipoStrings.text("native.screenshot.permission_title")).font(.title2.bold()) |
| 124 | Text(EquipoStrings.text("native.screenshot.permission_detail")) |
| 125 | Button(EquipoStrings.text("native.screenshot.choose"), action: choose).buttonStyle(.borderedProminent).frame(minHeight: 44) |
| 126 | Button(EquipoStrings.text("chat.card.not_now"), action: decline).frame(minHeight: 44) |
| 127 | }.padding(24).presentationDetents([.medium, .large]) |
| 128 | } |
| 129 | } |
| 130 | struct LimitedScreenshotPicker: UIViewControllerRepresentable { |
| 131 | let completed: () -> Void |
| 132 | func makeUIViewController(context: Context) -> UIViewController { UIViewController() } |
| 133 | func updateUIViewController(_ controller: UIViewController, context: Context) { |
| 134 | guard !context.coordinator.presented else { return } |
| 135 | context.coordinator.presented = true |
| 136 | DispatchQueue.main.async { PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: controller) { _ in completed() } } |
| 137 | } |
| 138 | func makeCoordinator() -> Coordinator { Coordinator() } |
| 139 | final class Coordinator { var presented = false } |
| 140 | } |
| 141 | #endif |
| 142 | |