Repository Public
1// SP Notes iOS2// File: ShareExtension/ShareContentLoader.swift3// Description: Reads what another app shares (text, links, images, PDFs, any file) from the item providers. Files are received4// as file representations and copied to a staging folder without ever being loaded in memory (the extension has5// about 120 MB); only an image without a file behind it is re-encoded as JPEG, one at a time.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import ImageIO11import UIKit12import UniformTypeIdentifiers1314/// A shared file, already copied to the staging folder.15struct StagedFile: Sendable, Identifiable {16 let id = UUID()17 var name: String18 var url: URL19 var size: Int6420 var isImage: Bool21}2223/// Everything read from the share request.24struct SharePayload: Sendable {25 var suggestedTitle = ""26 var text = ""27 var link: URL?28 var files: [StagedFile] = []29 /// Items that could not be read, were too large or of a refused type.30 var failures: [String] = []31 /// Items beyond the limits (10 images, 10 files).32 var skipped = 03334 var isEmpty: Bool { text.isEmpty && link == nil && files.isEmpty }35}3637enum ShareLoadError: Error, Sendable {38 case unreadable39 case tooLarge(String)40 case refused(String)41}4243/// File helpers, callable from the item providers' background callbacks.44enum ShareFiles {45 static let maxImages = 1046 static let maxFiles = 1047 /// The server's limit: a larger file would wait in the upload queue forever.48 static let maxFileSize: Int64 = 200 << 2049 /// Types the server refuses (same list as the app).50 static let refusedExtensions: Set<String> = ["exe", "msi", "sh", "html", "htm", "js", "mjs"]5152 /// A readable file name: the provider's suggestion, completed by the extension of the file received.53 static func fileName(suggested: String?, url: URL, fallbackExtension: String? = nil) -> String {54 var name = (suggested ?? "").trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "/", with: "-")55 let received = url.lastPathComponent56 if name.isEmpty { name = received }57 if (name as NSString).pathExtension.isEmpty {58 let ext = url.pathExtension.isEmpty ? (fallbackExtension ?? "") : url.pathExtension59 if !ext.isEmpty { name += "." + ext }60 }61 return name.isEmpty ? "fichier" : name62 }6364 /// Copies (APFS clone: no data is read) a received file into its own staging folder and checks it can be accepted.65 static func stage(_ source: URL, name: String, in staging: URL, isImage: Bool) throws -> StagedFile {66 guard !refusedExtensions.contains((name as NSString).pathExtension.lowercased()) else { throw ShareLoadError.refused(name) }67 let size = Int64((try? source.resourceValues(forKeys: [.fileSizeKey]))?.fileSize ?? 0)68 guard size <= maxFileSize else { throw ShareLoadError.tooLarge(name) }69 let folder = staging.appendingPathComponent(UUID().uuidString, isDirectory: true)70 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)71 let target = folder.appendingPathComponent(name)72 try FileManager.default.copyItem(at: source, to: target)73 return StagedFile(name: name, url: target, size: size, isImage: isImage)74 }7576 static func stage(_ data: Data, name: String, in staging: URL, isImage: Bool) throws -> StagedFile {77 let folder = staging.appendingPathComponent(UUID().uuidString, isDirectory: true)78 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)79 let target = folder.appendingPathComponent(name)80 try data.write(to: target, options: .atomic)81 return StagedFile(name: name, url: target, size: Int64(data.count), isImage: isImage)82 }8384 /// A small picture decoded straight at thumbnail size (the full image is never decoded).85 static func thumbnail(of url: URL, maxPixel: CGFloat = 240) -> UIImage? {86 guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil }87 let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,88 kCGImageSourceThumbnailMaxPixelSize: maxPixel, kCGImageSourceShouldCacheImmediately: true]89 guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }90 return UIImage(cgImage: image)91 }92}9394@MainActor95final class ShareContentLoader {96 /// Temporary folder of this share request; removed when the request ends.97 let staging: URL9899 init() {100 staging = FileManager.default.temporaryDirectory.appendingPathComponent("share-\(UUID().uuidString)", isDirectory: true)101 try? FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)102 }103104 func cleanUp() { try? FileManager.default.removeItem(at: staging) }105106 func load(_ items: [NSExtensionItem]) async -> SharePayload {107 var payload = SharePayload()108 var texts: [String] = []109 var images = 0, others = 0110 for item in items {111 let providers = item.attachments ?? []112 if payload.suggestedTitle.isEmpty, let title = item.attributedTitle?.string.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty {113 payload.suggestedTitle = String(title.prefix(120))114 }115 var itemHasLink = false116 for provider in providers {117 switch Self.kind(of: provider) {118 case .image, .file:119 let isImage = Self.kind(of: provider) == .image120 if isImage ? images >= ShareFiles.maxImages : others >= ShareFiles.maxFiles { payload.skipped += 1; continue }121 switch await loadFile(provider, isImage: isImage) {122 case .success(let file):123 payload.files.append(file)124 if isImage { images += 1 } else { others += 1 }125 case .failure(.tooLarge(let name)): payload.failures.append(String(localized: "« \(name) » dépasse 200 Mo."))126 case .failure(.refused(let name)): payload.failures.append(String(localized: "« \(name) » : ce type de fichier n’est pas accepté."))127 case .failure(.unreadable): payload.failures.append(String(localized: "Un fichier n’a pas pu être lu."))128 }129 case .link:130 guard let url = await loadURL(provider) else { payload.failures.append(String(localized: "Un lien n’a pas pu être lu.")); continue }131 itemHasLink = true132 if payload.link == nil { payload.link = url } else { texts.append(url.absoluteString) }133 case .text:134 if let text = await loadText(provider), !text.isEmpty { texts.append(text) } else { payload.failures.append(String(localized: "Un texte n’a pas pu être lu.")) }135 case .attributedText:136 if let text = await loadAttributedText(provider), !text.isEmpty { texts.append(text) } else { payload.failures.append(String(localized: "Un texte n’a pas pu être lu.")) }137 case .unsupported:138 payload.failures.append(String(localized: "Un élément n’est pas d’un type pris en charge."))139 }140 }141 // Safari and most apps give the page title as the item's text when a link is shared.142 let content = item.attributedContentText?.string.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""143 if !content.isEmpty {144 if itemHasLink, payload.suggestedTitle.isEmpty {145 payload.suggestedTitle = String((content.split(whereSeparator: \.isNewline).first ?? "").prefix(120))146 } else if !texts.contains(content), !itemHasLink, providers.isEmpty {147 texts.append(content)148 }149 }150 }151 payload.text = texts.joined(separator: "\n\n")152 return payload153 }154155 // MARK: classification156157 enum Kind { case file, image, link, text, attributedText, unsupported }158159 static func kind(of provider: NSItemProvider) -> Kind {160 func has(_ type: UTType) -> Bool { provider.hasItemConformingToTypeIdentifier(type.identifier) }161 if has(.image) { return .image }162 if has(.fileURL) || has(.pdf) || has(.audiovisualContent) || has(.archive) { return .file }163 if has(.url) { return .link }164 if has(.plainText) { return .text }165 if has(.rtf) || has(.rtfd) || has(.flatRTFD) { return .attributedText }166 if has(.data) { return .file }167 return .unsupported168 }169170 /// The type to ask the file for: the most specific one the provider registered.171 private static func fileType(of provider: NSItemProvider, isImage: Bool) -> String {172 let registered = provider.registeredTypeIdentifiers173 let excluded: Set<String> = [UTType.fileURL.identifier, UTType.url.identifier]174 if isImage, let match = registered.first(where: { UTType($0)?.conforms(to: .image) == true }) { return match }175 return registered.first { !excluded.contains($0) } ?? (isImage ? UTType.image.identifier : UTType.data.identifier)176 }177178 // MARK: loading (each callback runs on a background queue and only hands back Sendable values)179180 private func loadFile(_ provider: NSItemProvider, isImage: Bool) async -> Result<StagedFile, ShareLoadError> {181 let type = Self.fileType(of: provider, isImage: isImage)182 let suggested = provider.suggestedName, staging = staging183 let fallbackExtension = UTType(type)?.preferredFilenameExtension184 let first: Result<StagedFile, ShareLoadError> = await withCheckedContinuation { continuation in185 _ = provider.loadFileRepresentation(forTypeIdentifier: type) { url, _ in186 guard let url else { continuation.resume(returning: .failure(.unreadable)); return }187 // The file only exists during this callback: it is copied now.188 continuation.resume(returning: Self.staged { try ShareFiles.stage(url, name: ShareFiles.fileName(suggested: suggested, url: url, fallbackExtension: fallbackExtension), in: staging, isImage: isImage) })189 }190 }191 guard case .failure(.unreadable) = first else { return first }192 if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) {193 // A document given by reference (Files): copied from its location, inside its security scope.194 let viaURL: Result<StagedFile, ShareLoadError> = await withCheckedContinuation { continuation in195 _ = provider.loadObject(ofClass: URL.self) { url, _ in196 guard let url, url.isFileURL else { continuation.resume(returning: .failure(.unreadable)); return }197 let scoped = url.startAccessingSecurityScopedResource()198 defer { if scoped { url.stopAccessingSecurityScopedResource() } }199 continuation.resume(returning: Self.staged { try ShareFiles.stage(url, name: ShareFiles.fileName(suggested: suggested, url: url), in: staging, isImage: isImage) })200 }201 }202 if case .success = viaURL { return viaURL }203 }204 guard isImage, provider.canLoadObject(ofClass: UIImage.self) else { return first }205 // An image without a file (a screenshot being edited, a picture drawn by an app): encoded as JPEG.206 return await withCheckedContinuation { continuation in207 _ = provider.loadObject(ofClass: UIImage.self) { object, _ in208 guard let image = object as? UIImage, let data = image.jpegData(compressionQuality: 0.88) else { continuation.resume(returning: .failure(.unreadable)); return }209 let stem = (suggested ?? "").isEmpty ? "Image" : ((suggested ?? "") as NSString).deletingPathExtension210 continuation.resume(returning: Self.staged { try ShareFiles.stage(data, name: stem + ".jpg", in: staging, isImage: true) })211 }212 }213 }214215 private nonisolated static func staged(_ body: () throws -> StagedFile) -> Result<StagedFile, ShareLoadError> {216 do { return .success(try body()) } catch let error as ShareLoadError { return .failure(error) } catch { return .failure(.unreadable) }217 }218219 private func loadURL(_ provider: NSItemProvider) async -> URL? {220 await withCheckedContinuation { continuation in221 _ = provider.loadObject(ofClass: URL.self) { url, _ in continuation.resume(returning: url) }222 }223 }224225 private func loadText(_ provider: NSItemProvider) async -> String? {226 await withCheckedContinuation { continuation in227 _ = provider.loadObject(ofClass: String.self) { text, _ in228 continuation.resume(returning: text?.trimmingCharacters(in: .whitespacesAndNewlines))229 }230 }231 }232233 /// Formatted text is kept as plain text.234 private func loadAttributedText(_ provider: NSItemProvider) async -> String? {235 let isRTFD = !provider.hasItemConformingToTypeIdentifier(UTType.rtf.identifier)236 let type = isRTFD ? (provider.hasItemConformingToTypeIdentifier(UTType.flatRTFD.identifier) ? UTType.flatRTFD : UTType.rtfd) : UTType.rtf237 return await withCheckedContinuation { continuation in238 _ = provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in239 guard let data, data.count < 8 << 20 else { continuation.resume(returning: nil); return }240 let documentType: NSAttributedString.DocumentType = type == .rtf ? .rtf : .rtfd241 let text = try? NSAttributedString(data: data, options: [.documentType: documentType], documentAttributes: nil).string242 continuation.resume(returning: text?.trimmingCharacters(in: .whitespacesAndNewlines))243 }244 }245 }246}247