SPB Git

Repository Public

ShareViewController.swift 11.1 KB 219 lines swift

1// SP Drive iOS2// File: ShareExtension/ShareViewController.swift3// Description: « Send to SP Drive » from the share sheet of any app. Native SwiftUI: choice of the destination folder, upload with4//              progress and verification. Without network, the files are handed to the app, which sends them at its next launch.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import UIKit10import UniformTypeIdentifiers1112final class ShareViewController: UIViewController {13    private let model = ShareModel()1415    override func viewDidLoad() {16        super.viewDidLoad()17        let host = UIHostingController(rootView: ShareView(model: model, close: { [weak self] in self?.finish() }))18        addChild(host)19        host.view.frame = view.bounds20        host.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]21        view.addSubview(host.view)22        host.didMove(toParent: self)23        // each attachment keeps the title of the item it came with (the page title for a link shared from Safari)24        let items = extensionContext?.inputItems as? [NSExtensionItem] ?? []25        let shared = items.flatMap { item in (item.attachments ?? []).map { ShareModel.Shared(provider: $0, title: item.attributedTitle?.string ?? item.attributedContentText?.string) } }26        Task { await model.load(shared) }27    }2829    private func finish() {30        model.cleanUp()31        extensionContext?.completeRequest(returningItems: nil)32    }33}3435@MainActor @Observable36final class ShareModel {37    struct Shared: @unchecked Sendable { let provider: NSItemProvider; let title: String? }38    struct Pending: Identifiable { let id = UUID(); var url: URL; let name: String; let size: Int64; let kind: ShareIntake.Collected.Kind; var sent: Int64 = 0; var state: State = .waiting }39    enum State: Equatable { case waiting, sending, done, parked, failed(String) }40    enum Phase { case loading, ready, sending, finished }4142    var files: [Pending] = []43    /// Items of the share that could not become a file (said, not hidden).44    var skipped = 045    var phase: Phase = .loading46    var signedIn = true47    var folderPath: [DriveItem] = []48    var subfolders: [DriveItem] = []49    var loadingFolders = false50    var message: String?51    /// « Wi-Fi only » is on and the path is cellular: everything is queued for the app.52    var wifiOnlyHold = false5354    private let api = DriveAPI(tokens: KeychainTokenStore())55    private let inbox = ShareInbox()56    private let work = FileManager.default.temporaryDirectory.appendingPathComponent("share-\(UUID().uuidString)", isDirectory: true)57    private var rootID: String?5859    var destinationName: String { folderPath.last?.name ?? "Mon Drive" }60    var destinationID: String? { folderPath.last?.id ?? rootID }6162    func load(_ shared: [Shared]) async {63        try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)64        signedIn = api.isSignedIn65        let status = NetworkMonitor.shared.status66        wifiOnlyHold = status.expensive && AppGroup.sharedDefaults.object(forKey: "transfers.cellular") as? Bool == false67        for (i, s) in shared.enumerated() {68            if let c = await ShareIntake.collect(s.provider, title: s.title, into: work.appendingPathComponent("\(i)", isDirectory: true)) {69                files.append(Pending(url: c.url, name: c.name, size: IntegrityVerifier.size(of: c.url), kind: c.kind))70            } else { skipped += 1 }71        }72        phase = .ready73        if signedIn { await openFolder(nil) }74    }7576    /// Lists the sub-folders of the destination being browsed (nil = root).77    func openFolder(_ folder: DriveItem?) async {78        loadingFolders = true79        defer { loadingFolders = false }80        do {81            if rootID == nil { rootID = try await api.rootID() }82            if let folder { folderPath.append(folder) }83            subfolders = try await api.subfolders(of: destinationID ?? "root")84            message = nil85        } catch RemoteError.unauthenticated {86            signedIn = false87        } catch {88            subfolders = []89            message = "Hors ligne : les fichiers seront envoyés à la prochaine ouverture de SP Drive."90        }91    }9293    func goUp() async {94        guard !folderPath.isEmpty else { return }95        folderPath.removeLast()96        await openFolder(nil)97    }9899    /// Everything is parked in the group container first; what can be sent now is sent from there and leaves the inbox. Whatever100    /// remains (no network, Wi-Fi only, extension stopped by the system) is sent by the app.101    func send() async {102        phase = .sending103        let dest = destinationID104        var parked: [UUID: ShareInbox.Entry] = [:]105        for i in files.indices {106            if let entry = try? inbox.park(files[i].url, displayName: files[i].name, folderID: dest) {107                parked[files[i].id] = entry108                files[i].url = inbox.url(of: entry)109                files[i].state = .parked110            }111        }112        guard !wifiOnlyHold, NetworkMonitor.shared.status.online, let dest else { phase = .finished; return }113        for i in files.indices {114            let f = files[i]115            let id = f.id116            guard let entry = parked[id] else { files[i].state = .failed("Impossible de préparer ce fichier"); continue }117            files[i].state = .sending118            do {119                let api = api, inbox = inbox120                _ = try await DirectTransfer.upload(file: f.url, remote: api, store: nil, resumeKey: nil, scratch: work.appendingPathComponent("chunk-\(i)"),121                                                    progress: { [weak self] done, _ in Task { @MainActor in self?.progress(id, done) } }) { size in122                    let upload = try await api.createUpload(parentID: dest, name: f.name, size: size, onConflict: .rename, fileID: nil, baseVersionID: nil)123                    inbox.note(uploadID: upload.id, for: entry) // if the extension dies now, the app can tell whether this file arrived124                    return upload125                }126                inbox.remove(entry)127                files[i].sent = f.size128                files[i].state = .done129            } catch let e {130                let remote = (e as? RemoteError) ?? (e as? DirectTransfer.UploadRefused)?.error131                if remote?.isTransient ?? true {132                    files[i].state = .parked // stays in the inbox: the app takes over133                } else {134                    inbox.remove(entry)135                    files[i].state = .failed(remote == .quotaExceeded ? "Espace insuffisant sur le Drive" : remote == .unauthenticated ? "Ouvre SP Drive pour te connecter" : remote == .fileTooLarge ? "Fichier trop volumineux" : "Envoi refusé")136                }137            }138        }139        phase = .finished140    }141142    private func progress(_ id: UUID, _ done: Int64) {143        if let i = files.firstIndex(where: { $0.id == id }) { files[i].sent = done }144    }145146    func cleanUp() { try? FileManager.default.removeItem(at: work) }147}148149struct ShareView: View {150    @Bindable var model: ShareModel151    let close: () -> Void152153    var body: some View {154        NavigationStack {155            Group {156                if !model.signedIn {157                    ContentUnavailableView("Connexion requise", systemImage: "person.crop.circle.badge.exclamationmark", description: Text("Ouvre SP Drive et connecte-toi, puis partage à nouveau."))158                } else if model.phase == .loading {159                    ProgressView("Préparation…")160                } else {161                    list162                }163            }164            .navigationTitle("Envoyer vers SP Drive")165            .navigationBarTitleDisplayMode(.inline)166            .toolbar {167                ToolbarItem(placement: .cancellationAction) { Button(model.phase == .finished ? "Fermer" : "Annuler", action: close).disabled(model.phase == .sending) }168                ToolbarItem(placement: .confirmationAction) {169                    if model.phase == .ready { Button(model.wifiOnlyHold ? "Mettre en file" : "Envoyer") { Task { await model.send() } }.bold().disabled(model.files.isEmpty || !model.signedIn) }170                    else if model.phase == .finished { Button("OK", action: close).bold() }171                }172            }173        }174        .tint(Color("AccentColor"))175    }176177    private var list: some View {178        List {179            Section(model.files.count > 1 ? "\(model.files.count) fichiers" : "Fichier") {180                if model.files.isEmpty { Text("Rien à envoyer : ce contenu ne peut pas devenir un fichier.").foregroundStyle(.secondary) }181                if model.skipped > 0, !model.files.isEmpty { Text(model.skipped == 1 ? "1 élément ignoré (pas de contenu exploitable)." : "\(model.skipped) éléments ignorés (pas de contenu exploitable).").font(.caption).foregroundStyle(.secondary) }182                ForEach(model.files) { f in183                    HStack(spacing: 12) {184                        Image(systemName: f.kind == .webLink ? "link" : FileKind(extension: (f.name as NSString).pathExtension.lowercased()).symbol).foregroundStyle(.tint).frame(width: 28)185                        VStack(alignment: .leading, spacing: 3) {186                            Text(f.name).lineLimit(2)187                            switch f.state {188                            case .waiting: Text(f.size.formatted(.byteCount(style: .file))).font(.caption).foregroundStyle(.secondary)189                            case .sending: ProgressView(value: f.size > 0 ? Double(f.sent) / Double(f.size) : 0)190                            case .done: Label("Envoyé et vérifié", systemImage: "checkmark.circle.fill").font(.caption).foregroundStyle(.green)191                            case .parked: Label("Sera envoyé à l’ouverture de SP Drive", systemImage: "clock.arrow.circlepath").font(.caption).foregroundStyle(.orange)192                            case .failed(let m): Label(m, systemImage: "exclamationmark.triangle.fill").font(.caption).foregroundStyle(.red)193                            }194                        }195                    }196                }197            }198            if model.phase == .ready {199                Section {200                    if !model.folderPath.isEmpty {201                        Button { Task { await model.goUp() } } label: { Label("Dossier parent", systemImage: "arrow.up.left") }202                    }203                    if model.loadingFolders { ProgressView() }204                    ForEach(model.subfolders) { folder in205                        Button { Task { await model.openFolder(folder) } } label: {206                            HStack { Label(folder.name, systemImage: "folder.fill"); Spacer(); Image(systemName: "chevron.right").font(.footnote).foregroundStyle(.tertiary) }207                        }.foregroundStyle(.primary)208                    }209                } header: {210                    Text("Destination : \(model.destinationName)")211                } footer: {212                    if model.wifiOnlyHold { Text("« Wi-Fi seulement » est activé : les fichiers seront mis en file et envoyés par SP Drive sur un réseau Wi-Fi.") }213                    else if let m = model.message { Text(m) }214                }215            }216        }217    }218}219
Files main
Menu

Theme