Cotton code
94 lines · 4.2 KB · SwiftRaw
// EXPORT LIBRARY (Books, Music, Podcasts and Cinemas, 7 Nov 2026): a// person's library leaves Cotton whole. The tool's act answers `export_open`// (`tools.act`); the core lays the kit's open bundle — the Kodi, Plex, OPDS,// M3U8 and OPML trees other apps open — into a fresh folder under this app's// temporary directory (`package.exportOpen`), this zips the folder with the// system's own file coordinator, hands the zip to the share sheet (Files,// AirDrop) and, once the sheet closes, says how many files went and how many// of the library's files are not on this phone. The folder and the zip are// removed then. A refusal says the core's sentence.import CottonKitimport Foundation@MainActorfinal class LibraryExport {    static let shared = LibraryExport()    private var core: (any CottonCalling)?    private var say: ((String) -> Void)?    private var tell: ((String) -> Void)?    private let sharing: any FileSharing    private let temporary: URL    private let now: () -> Date    init(sharing: any FileSharing = SystemShareSheet(),         temporary: URL = FileManager.default.temporaryDirectory,         now: @escaping () -> Date = Date.init) {        self.sharing = sharing        self.temporary = temporary        self.now = now    }    /// The core and the toasts, from the root once a core is open: `say` an    /// error, `tell` a receipt.    func attach(core: any CottonCalling, say: @escaping (String) -> Void, tell: @escaping (String) -> Void) {        self.core = core        self.say = say        self.tell = tell    }    /// Lay `kit`'s open bundle, zip it as `Cotton <name> <date>.zip`, share    /// it, and say what it held once the sheet closes.    func export(kit: String, name: String) async {        guard let core else {            say?(ShellLines.line("databases", "export_open.refused"))            return        }        let work = temporary.appendingPathComponent("library-export-\(UUID().uuidString)", isDirectory: true)        defer { try? FileManager.default.removeItem(at: work) }        let title = Self.title(name: name, on: now())        let folder = work.appendingPathComponent(title, isDirectory: true)        let exported: OpenBundleExported        do {            exported = try await Packages(core: core).exportOpen(kit: kit, dir: folder.path)        } catch {            say?(ActionRefused.words(for: error))            return        }        guard let zip = await Task.detached(operation: { Self.zipped(folder, into: work) }).value else {            say?(ShellLines.line("databases", "export_open.refused"))            return        }        await sharing.share(title: title, url: zip)        tell?(Self.receipt(exported))    }    /// The zip's name, and the folder's inside it: the tool's name and the day.    static func title(name: String, on date: Date) -> String {        ShellLines.line("databases", "export_open.name", ["kit": name, "date": date.formatted(day)])    }    /// What the export says: the files written, and how many of the    /// library's files this phone does not keep where any are missing.    static func receipt(_ exported: OpenBundleExported) -> String {        let written = String(exported.files)        guard !exported.missingMedia.isEmpty else { return ShellLines.line("databases", "export_open.written", ["n": written]) }        return ShellLines.line("databases", "export_open.written_missing", ["n": written, "missing": String(exported.missingMedia.count)])    }    /// `folder` zipped beside it as `<folder's name>.zip` by the system's    /// file coordinator (the zip it makes for an upload); nil when it could    /// not be made.    nonisolated static func zipped(_ folder: URL, into directory: URL) -> URL? {        let target = directory.appendingPathComponent(folder.lastPathComponent).appendingPathExtension("zip")        var refused: NSError?        var made = false        NSFileCoordinator().coordinate(readingItemAt: folder, options: .forUploading, error: &refused) { zip in            made = (try? FileManager.default.moveItem(at: zip, to: target)) != nil        }        return refused == nil && made ? target : nil    }    private static let day = Date.ISO8601FormatStyle(timeZone: .current).year().month().day()}