SPB Git

Repository Public

SharedInbox.swift 3.9 KB 84 lines swift

1// SP Notes iOS2// File: Shared/SharedInbox.swift3// Description: Hand-off between the share extension and the app: the extension writes each shared item (text, link, files) as a4//              small folder in the App Group container; the app turns the folders into notes at its next activation. Durable and5//              independent of the database, so the extension stays tiny and nothing is lost if the app is not running.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011struct SharedItem: Codable, Sendable, Identifiable {12    var id: String = UUID().uuidString.lowercased()13    var createdAt = Date()14    var title: String?15    var text: String?16    var url: String?17    /// Names of the files stored next to the manifest.18    var files: [String] = []19}2021struct SharedInbox: Sendable {22    let directory: URL2324    init(container: URL) { directory = container.appendingPathComponent("SharedInbox", isDirectory: true) }2526    private func folder(_ id: String) -> URL { directory.appendingPathComponent(id, isDirectory: true) }27    func fileURL(item: SharedItem, name: String) -> URL { folder(item.id).appendingPathComponent(name) }2829    /// Writes an item atomically: files first, the manifest last (an item without manifest is ignored, then cleaned up).30    func save(_ item: SharedItem, files: [(name: String, source: URL)], data: [(name: String, data: Data)] = []) throws {31        var item = item32        let target = folder(item.id)33        try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)34        var used = Set<String>()35        func unique(_ name: String) -> String {36            let clean = name.replacingOccurrences(of: "/", with: "-")37            var candidate = clean.isEmpty ? "fichier" : clean38            var n = 239            while used.contains(candidate.lowercased()) {40                let ext = (clean as NSString).pathExtension, stem = (clean as NSString).deletingPathExtension41                candidate = ext.isEmpty ? "\(stem) \(n)" : "\(stem) \(n).\(ext)"42                n += 143            }44            used.insert(candidate.lowercased())45            return candidate46        }47        for file in files {48            let name = unique(file.name)49            try FileManager.default.copyItem(at: file.source, to: target.appendingPathComponent(name))50            item.files.append(name)51        }52        for blob in data {53            let name = unique(blob.name)54            try blob.data.write(to: target.appendingPathComponent(name), options: .atomic)55            item.files.append(name)56        }57        let manifest = try JSONEncoder.sharedInbox.encode(item)58        try manifest.write(to: target.appendingPathComponent("item.json"), options: .atomic)59    }6061    /// Complete items, oldest first.62    func pending() -> [SharedItem] {63        guard let folders = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.creationDateKey]) else { return [] }64        var items: [SharedItem] = []65        for folder in folders {66            if let data = try? Data(contentsOf: folder.appendingPathComponent("item.json")), let item = try? JSONDecoder.sharedInbox.decode(SharedItem.self, from: data) {67                items.append(item)68            } else if let created = try? folder.resourceValues(forKeys: [.creationDateKey]).creationDate, Date().timeIntervalSince(created) > 3600 {69                try? FileManager.default.removeItem(at: folder) // an interrupted save, long abandoned70            }71        }72        return items.sorted { $0.createdAt < $1.createdAt }73    }7475    func remove(_ item: SharedItem) { try? FileManager.default.removeItem(at: folder(item.id)) }76}7778extension JSONEncoder {79    static var sharedInbox: JSONEncoder { let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; return e }80}81extension JSONDecoder {82    static var sharedInbox: JSONDecoder { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d }83}84
Files main
Menu

Theme