SPB Git

Repository Public

ShareIntake.swift 7.2 KB 119 lines swift

1// SP Drive iOS2// File: Core/Capture/ShareIntake.swift3// Description: What the share sheet hands over, turned into files: documents, photos and videos as they are; a PDF when the source4//              offers one (Safari on a PDF, Mail attachments); a web page as a `.webloc` link file; selected text as a `.txt` file.5//              Foundation only, so the decisions are tested on the Mac with real NSItemProviders.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import UniformTypeIdentifiers1112public enum ShareIntake {13    public enum Plan: Sendable, Equatable {14        /// A real file or media: copy the representation of this type.15        case file(type: String)16        /// A web address: saved as a link file.17        case webLink18        /// Plain text: saved as a text file.19        case text(type: String)20        case unsupported21    }2223    public struct Collected: Sendable, Equatable {24        public enum Kind: String, Sendable { case file, pdf, webLink, text }25        public var url: URL26        public var name: String27        public var kind: Kind28    }2930    /// Decides what to do with one shared item from the types it offers, best representation first.31    public static func plan(types: [String]) -> Plan {32        let uts = types.compactMap { id in UTType(id).map { (id, $0) } }33        // a PDF beats everything: Safari offers it for PDF pages, Mail for attachments34        if let pdf = uts.first(where: { $0.1.conforms(to: .pdf) }) { return .file(type: pdf.0) }35        let isFile = uts.contains { $0.1.conforms(to: .fileURL) }36        let concrete = uts.filter { $0.1.conforms(to: .data) && !$0.1.conforms(to: .url) && $0.1 != .data && $0.1 != .item && $0.1 != .content }37        if isFile, let best = concrete.first { return .file(type: best.0) }38        if let media = concrete.first(where: { !$0.1.conforms(to: .text) && !$0.1.conforms(to: .propertyList) }) { return .file(type: media.0) }39        if isFile, let any = uts.first(where: { $0.1.conforms(to: .data) && !$0.1.conforms(to: .url) }) { return .file(type: any.0) }40        if uts.contains(where: { $0.1.conforms(to: .url) && !$0.1.conforms(to: .fileURL) }) { return .webLink }41        if let text = uts.first(where: { $0.1.conforms(to: .plainText) }) ?? uts.first(where: { $0.1.conforms(to: .text) }) { return .text(type: text.0) }42        if let first = types.first, UTType(first) == nil { return .file(type: first) } // an app's private type: take the bytes as they are43        return .unsupported44    }4546    /// The content of a `.webloc` file (what Finder and Files open as a link to the page).47    public static func webloc(for url: URL) -> Data {48        (try? PropertyListSerialization.data(fromPropertyList: ["URL": url.absoluteString], format: .xml, options: 0)) ?? Data()49    }5051    /// A file name from a page title or a piece of text: one line, no path characters, reasonable length.52    public static func name(from title: String?, fallback: String, ext: String) -> String {53        var base = (title ?? "").components(separatedBy: .newlines).first?.trimmingCharacters(in: .whitespaces) ?? ""54        if base.count > 80 { base = String(base.prefix(80)).trimmingCharacters(in: .whitespaces) }55        if base.isEmpty { base = fallback }56        return LocalFiles.safeName(base) + "." + ext57    }5859    /// Materialises one shared item as a file in `directory`. Returns nil when the item has nothing that can become a file.60    public static func collect(_ provider: NSItemProvider, title: String? = nil, into directory: URL) async -> Collected? {61        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)62        let suggested = provider.suggestedName63        switch plan(types: provider.registeredTypeIdentifiers) {64        case .file(let type):65            // the representation the system hands over may be renamed after its type (« JPEG image.jpeg »): the lent file's own name is asked first66            var original: String?67            if provider.registeredTypeIdentifiers.contains(UTType.fileURL.identifier), let lent = await loadURL(provider), lent.isFileURL { original = lent.lastPathComponent }68            let originalName = original69            // the system lends the file only during the callback: copy it now (a clone on APFS, no bytes in memory)70            let copied: URL? = await withCheckedContinuation { c in71                _ = provider.loadFileRepresentation(forTypeIdentifier: type) { url, _ in72                    guard let url else { c.resume(returning: nil); return }73                    var name = originalName ?? url.lastPathComponent74                    if originalName == nil, let suggested, !suggested.isEmpty { name = (suggested as NSString).pathExtension.isEmpty && !url.pathExtension.isEmpty ? "\(suggested).\(url.pathExtension)" : suggested }75                    if (name as NSString).pathExtension.isEmpty, let ext = UTType(type)?.preferredFilenameExtension { name += ".\(ext)" }76                    let dest = directory.appendingPathComponent(LocalFiles.safeName(name))77                    do { try FileManager.default.copyItem(at: url, to: dest); c.resume(returning: dest) } catch { c.resume(returning: nil) }78                }79            }80            guard let copied else { return nil }81            return Collected(url: copied, name: copied.lastPathComponent, kind: UTType(type)?.conforms(to: .pdf) == true ? .pdf : .file)82        case .webLink:83            guard let url = await loadURL(provider), let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme) else { return nil }84            let name = name(from: title ?? suggested, fallback: url.host() ?? "Lien", ext: "webloc")85            let dest = directory.appendingPathComponent(name)86            guard (try? webloc(for: url).write(to: dest)) != nil else { return nil }87            return Collected(url: dest, name: name, kind: .webLink)88        case .text(let type):89            guard let text = await loadText(provider, type: type), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }90            let name = name(from: suggested ?? text, fallback: "Texte", ext: "txt")91            let dest = directory.appendingPathComponent(name)92            guard (try? Data(text.utf8).write(to: dest)) != nil else { return nil }93            return Collected(url: dest, name: name, kind: .text)94        case .unsupported:95            return nil96        }97    }9899    static func loadURL(_ provider: NSItemProvider) async -> URL? {100        await withCheckedContinuation { c in101            _ = provider.loadObject(ofClass: NSURL.self) { object, _ in c.resume(returning: (object as? NSURL) as URL?) }102        }103    }104105    static func loadText(_ provider: NSItemProvider, type: String) async -> String? {106        if provider.canLoadObject(ofClass: NSString.self) {107            let s: String? = await withCheckedContinuation { c in108                _ = provider.loadObject(ofClass: NSString.self) { object, _ in c.resume(returning: object as? String) }109            }110            if let s { return s }111        }112        return await withCheckedContinuation { c in113            _ = provider.loadDataRepresentation(forTypeIdentifier: type) { data, _ in114                c.resume(returning: data.flatMap { String(data: $0, encoding: .utf8) ?? String(data: $0, encoding: .utf16) })115            }116        }117    }118}119
Files main
Menu

Theme