SPB Git

Repository Public

MobileDownloads.swift 4.9 KB 113 lines swift

1import Foundation2import Observation3import WebKit45struct DownloadItem: Identifiable, Equatable {6    enum State: Equatable { case running, finished, failed(String) }7    let id = UUID()8    var name: String9    var fileURL: URL10    var source: String11    var state: State = .running12    var fraction: Double = 013    var isPrivate = false14}1516/// Saves files chosen by the user into the app's Downloads folder (visible in the Files app) and tracks their progress.17@MainActor18@Observable19final class MobileDownloads: NSObject, WKDownloadDelegate {20    private(set) var items: [DownloadItem] = []21    let directory: URL22    @ObservationIgnored private var active: [ObjectIdentifier: (id: UUID, observation: NSKeyValueObservation, download: WKDownload)] = [:]2324    init(testing: Bool, root: URL) {25        let base = testing ? root : (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first ?? root)26        directory = base.appendingPathComponent("Downloads", isDirectory: true)27        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)28        super.init()29        loadExisting()30    }3132    private func loadExisting() {33        let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []34        items = files.filter { !$0.lastPathComponent.hasPrefix(".") }35            .sorted { (try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast >36                      (try? $1.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast }37            .map { DownloadItem(name: $0.lastPathComponent, fileURL: $0, source: "", state: .finished, fraction: 1) }38    }3940    var activeCount: Int { items.filter { $0.state == .running }.count }4142    func adopt(_ download: WKDownload, isPrivate: Bool) {43        download.delegate = self44        pendingPrivate[ObjectIdentifier(download)] = isPrivate45    }4647    @ObservationIgnored private var pendingPrivate: [ObjectIdentifier: Bool] = [:]4849    /// A free file name in the Downloads folder: "report.pdf", then "report 2.pdf"…50    func destination(for suggested: String) -> URL {51        let safe = DownloadSafety.sanitize(filename: suggested)52        let ext = (safe as NSString).pathExtension, stem = (safe as NSString).deletingPathExtension53        var candidate = directory.appendingPathComponent(safe)54        var n = 255        while FileManager.default.fileExists(atPath: candidate.path) {56            candidate = directory.appendingPathComponent(ext.isEmpty ? "\(stem) \(n)" : "\(stem) \(n).\(ext)")57            n += 158        }59        return candidate60    }6162    func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String) async -> URL? {63        let target = destination(for: suggestedFilename)64        let key = ObjectIdentifier(download)65        var item = DownloadItem(name: target.lastPathComponent, fileURL: target, source: response.url?.host ?? "")66        item.isPrivate = pendingPrivate.removeValue(forKey: key) ?? false67        items.insert(item, at: 0)68        let id = item.id69        let observation = download.progress.observe(\.fractionCompleted) { [weak self] progress, _ in70            let value = progress.fractionCompleted71            Task { @MainActor in self?.update(id) { $0.fraction = value } }72        }73        active[key] = (id, observation, download)74        return target75    }7677    func downloadDidFinish(_ download: WKDownload) {78        finish(download) { $0.state = .finished; $0.fraction = 1 }79    }8081    func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {82        finish(download) { $0.state = .failed(error.localizedDescription) }83    }8485    private func finish(_ download: WKDownload, _ change: (inout DownloadItem) -> Void) {86        guard let entry = active.removeValue(forKey: ObjectIdentifier(download)) else { return }87        entry.observation.invalidate()88        update(entry.id, change)89    }9091    private func update(_ id: UUID, _ change: (inout DownloadItem) -> Void) {92        guard let index = items.firstIndex(where: { $0.id == id }) else { return }93        change(&items[index])94    }9596    func cancel(_ item: DownloadItem) {97        guard let entry = active.first(where: { $0.value.id == item.id }) else { return }98        entry.value.download.cancel { _ in }99        entry.value.observation.invalidate()100        active[entry.key] = nil101        update(item.id) { $0.state = .failed(L("Cancelled")) }102    }103104    func remove(_ item: DownloadItem, deleteFile: Bool) {105        cancel(item)106        if deleteFile { try? FileManager.default.removeItem(at: item.fileURL) }107        items.removeAll { $0.id == item.id }108    }109110    /// Downloads started from private tabs disappear from the list (the files the user saved are kept).111    func forgetPrivateItems() { items.removeAll { $0.isPrivate && $0.state != .running } }112}113
Files main
Menu

Theme