Repository Public
1// SP Drive iOS2// File: Sync/ShareInbox.swift3// Description: Hand-over between the share extension and the app, through the group container. Everything the extension receives is4// parked there FIRST, with its destination: if the extension is stopped mid-way, or there is no network, or « Wi-Fi only »5// applies, the app sends it at its next launch. An entry remembers the upload session the extension opened, so a file the6// extension did finish sending is never sent a second time.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112public struct ShareInbox: Sendable {13 public struct Entry: Codable, Sendable, Equatable, Identifiable {14 /// Name of the parked file inside the inbox.15 public var fileName: String16 public var displayName: String17 /// Destination folder identifier; nil = root of the Drive.18 public var folderID: String?19 /// Server-side upload session opened by the extension, if it got that far.20 public var uploadID: String?21 public var queuedAt: Date?22 public var id: String { fileName }23 }2425 public let directory: URL26 public init(directory: URL = AppGroup.inbox) {27 self.directory = directory28 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)29 }3031 var manifest: URL { directory.appendingPathComponent("manifest.json") }32 public func url(of entry: Entry) -> URL { directory.appendingPathComponent(entry.fileName) }3334 public func entries() -> [Entry] { (try? JSONDecoder().decode([Entry].self, from: Data(contentsOf: manifest))) ?? [] }35 func save(_ e: [Entry]) { try? JSONEncoder().encode(e).write(to: manifest, options: .atomic) }3637 /// Parks a file for the app. The file is moved into the group container. Returns the entry.38 @discardableResult39 public func park(_ file: URL, displayName: String, folderID: String?) throws -> Entry {40 let entry = Entry(fileName: UUID().uuidString, displayName: displayName, folderID: folderID, uploadID: nil, queuedAt: .now)41 try FileManager.default.moveItem(at: file, to: url(of: entry))42 save(entries() + [entry])43 return entry44 }4546 /// The extension opened an upload session for this entry.47 public func note(uploadID: String, for entry: Entry) {48 var all = entries()49 guard let i = all.firstIndex(where: { $0.fileName == entry.fileName }) else { return }50 all[i].uploadID = uploadID51 save(all)52 }5354 /// The extension sent the file itself: nothing is left for the app to do.55 public func remove(_ entry: Entry) {56 try? FileManager.default.removeItem(at: url(of: entry))57 save(entries().filter { $0.fileName != entry.fileName })58 }5960 /// Hands every parked file to `importer` (which takes ownership of the bytes) and forgets those it accepted. A file whose upload61 /// session the server reports as complete was already sent by the extension: it is dropped, not sent again. A session left open is62 /// aborted (the app's own queue starts a fresh, resumable one).63 public func drain(remote: DriveRemote? = nil, _ importer: @Sendable (URL, Entry) async throws -> Void) async {64 var left: [Entry] = []65 for e in entries() {66 let file = url(of: e)67 guard FileManager.default.fileExists(atPath: file.path) else { continue }68 if let upload = e.uploadID, let remote {69 do {70 let status = try await remote.uploadStatus(id: upload)71 if status.status == "done" { try? FileManager.default.removeItem(at: file); continue }72 try? await remote.abortUpload(id: upload)73 } catch let error as RemoteError where error.isTransient || error == .unauthenticated {74 left.append(e) // cannot tell yet: decide when the server answers75 continue76 } catch {}77 }78 do { try await importer(file, e); try? FileManager.default.removeItem(at: file) } catch { left.append(e) }79 }80 // entries parked while this pass was running are kept81 let handled = Set(entries().map(\.fileName)).subtracting(left.map(\.fileName))82 save(left + entries().filter { !handled.contains($0.fileName) && !left.map(\.fileName).contains($0.fileName) })83 }84}85