SPB Git

Repository Public

DownloadManager.swift 11.2 KB 267 lines swift

1import AppKit2import WebKit34@MainActor5@Observable6final class DownloadItem: Identifiable {7    enum State: Equatable {8        case inProgress, paused, finished, cancelled9        case failed(String)10    }1112    let id: UUID13    let sourceHost: String14    let isPrivate: Bool15    let startedAt: Date16    var filename: String17    var destination: URL?18    var state: State = .inProgress19    var fraction = 0.020    var bytesReceived: Int64 = 021    var bytesExpected: Int64 = -122    var risk: DownloadRisk = .normal23    @ObservationIgnored var download: WKDownload?24    @ObservationIgnored var resumeData: Data?25    @ObservationIgnored weak var originWebView: WKWebView?26    @ObservationIgnored var observation: NSKeyValueObservation?2728    init(id: UUID = UUID(), filename: String, sourceHost: String, isPrivate: Bool, startedAt: Date = Date()) {29        self.id = id30        self.filename = filename31        self.sourceHost = sourceHost32        self.isPrivate = isPrivate33        self.startedAt = startedAt34    }3536    /// Pausing needs resume data, which WebKit provides only when the server supports range requests.37    var canResume: Bool { state == .paused && resumeData != nil && originWebView != nil }38    var isActive: Bool { state == .inProgress }39    var fileExists: Bool { destination.map { FileManager.default.fileExists(atPath: $0.path) } ?? false }40}4142/// A finished download remembered across launches (never for private windows).43struct DownloadRecord: Codable, Equatable, Identifiable {44    var id: UUID45    var filename: String46    var path: String47    var sourceHost: String48    var date: Date49    var succeeded: Bool50}5152@MainActor53@Observable54final class DownloadManager: NSObject, WKDownloadDelegate {55    private(set) var items: [DownloadItem] = []56    /// Incremented whenever a download starts, so the UI can draw attention to the downloads button.57    private(set) var startCounter = 058    @ObservationIgnored private let records: JSONFileStore<[DownloadRecord]>59    @ObservationIgnored var askWhereToSave: @MainActor () -> Bool = { false }60    @ObservationIgnored var presentingWindow: @MainActor () -> NSWindow? = { NSApp.keyWindow }61    /// Overridable for tests; defaults to the user's Downloads folder.62    @ObservationIgnored var destinationDirectory: @MainActor () -> URL = {63        FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory64    }6566    init(recordsURL: URL?) {67        records = JSONFileStore(url: recordsURL, defaults: [])68        super.init()69        items = records.value.map { record in70            let item = DownloadItem(id: record.id, filename: record.filename, sourceHost: record.sourceHost, isPrivate: false, startedAt: record.date)71            item.destination = URL(fileURLWithPath: record.path)72            item.state = record.succeeded ? .finished : .failed(L("Interrupted"))73            item.fraction = record.succeeded ? 1 : 074            item.risk = DownloadSafety.risk(forFilename: record.filename)75            return item76        }77    }7879    var activeCount: Int { items.filter(\.isActive).count }80    var overallFraction: Double {81        let active = items.filter(\.isActive)82        return active.isEmpty ? 0 : active.reduce(0) { $0 + $1.fraction } / Double(active.count)83    }8485    func adopt(_ download: WKDownload, from webView: WKWebView?, isPrivate: Bool) {86        download.delegate = self87        let host = download.originalRequest?.url?.host ?? webView?.url?.host ?? ""88        let item = DownloadItem(filename: L("Preparing…"), sourceHost: host, isPrivate: isPrivate)89        item.download = download90        item.originWebView = webView91        track(item, download: download)92        items.insert(item, at: 0)93        startCounter += 194    }9596    private func track(_ item: DownloadItem, download: WKDownload) {97        item.observation = download.progress.observe(\.fractionCompleted) { [weak item] progress, _ in98            let fraction = progress.fractionCompleted, done = progress.completedUnitCount, total = progress.totalUnitCount99            Task { @MainActor in100                guard let item, item.state == .inProgress else { return }101                item.fraction = fraction102                item.bytesReceived = done103                item.bytesExpected = total104            }105        }106    }107108    private func item(for download: WKDownload) -> DownloadItem? { items.first { $0.download === download } }109110    // MARK: WKDownloadDelegate111112    func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String) async -> URL? {113        guard let item = item(for: download) else { return nil }114        let safeName = DownloadSafety.sanitize(filename: suggestedFilename)115        item.filename = safeName116        item.risk = DownloadSafety.risk(forFilename: safeName)117        item.bytesExpected = response.expectedContentLength118119        // A resumed download keeps writing to the file it already started.120        if let existing = item.destination, item.resumeData != nil || item.state == .inProgress, item.fraction > 0 { return existing }121122        var destination: URL?123        if askWhereToSave(), let window = presentingWindow() {124            let panel = NSSavePanel()125            panel.nameFieldStringValue = safeName126            panel.directoryURL = destinationDirectory()127            panel.canCreateDirectories = true128            if await panel.beginSheetModal(for: window) == .OK, let chosen = panel.url {129                // WebKit refuses to overwrite: the user already confirmed replacement in the panel.130                try? FileManager.default.removeItem(at: chosen)131                destination = chosen132            }133        } else {134            let directory = destinationDirectory()135            try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)136            destination = DownloadSafety.uniqueURL(in: directory, filename: safeName)137        }138        guard let destination else {139            item.state = .cancelled140            item.observation = nil141            return nil142        }143        item.destination = destination144        item.filename = destination.lastPathComponent145        return destination146    }147148    func downloadDidFinish(_ download: WKDownload) {149        guard let item = item(for: download) else { return }150        // A download can complete in the instant between the user's cancel and WebKit acting on it: the cancel wins.151        if item.state == .cancelled {152            if let destination = item.destination { try? FileManager.default.removeItem(at: destination) }153            finishTracking(item)154            return155        }156        item.state = .finished157        item.fraction = 1158        finishTracking(item)159        if let destination = item.destination {160            // Mark the file as downloaded from the web so Gatekeeper evaluates it when opened.161            try? (destination as NSURL).setResourceValue(162                [kLSQuarantineTypeKey: kLSQuarantineTypeWebDownload, kLSQuarantineAgentNameKey: "SP Browser"] as NSDictionary,163                forKey: .quarantinePropertiesKey)164            NSWorkspace.shared.noteFileSystemChanged(destination.path)165        }166        persist()167    }168169    func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {170        guard let item = item(for: download) else { return }171        item.resumeData = resumeData172        if item.state == .paused || item.state == .cancelled {173            finishTracking(item)174            return175        }176        let ns = error as NSError177        item.state = (ns.domain == NSURLErrorDomain && ns.code == NSURLErrorCancelled) ? .cancelled : .failed(ns.localizedDescription)178        finishTracking(item)179        persist()180    }181182    private func finishTracking(_ item: DownloadItem) {183        item.observation = nil184        item.download = nil185    }186187    // MARK: User actions188189    func cancel(_ item: DownloadItem) {190        guard item.state == .inProgress || item.state == .paused else { return }191        let wasPaused = item.state == .paused192        item.state = .cancelled193        item.resumeData = nil194        if let download = item.download, !wasPaused { download.cancel { _ in } }195        if let destination = item.destination { try? FileManager.default.removeItem(at: destination) }196        finishTracking(item)197    }198199    /// Pauses by cancelling with resume data. If the server gave none, the download is simply stopped.200    func pause(_ item: DownloadItem) {201        guard item.state == .inProgress, let download = item.download else { return }202        item.state = .paused203        download.cancel { [weak item] data in204            Task { @MainActor in205                guard let item else { return }206                item.resumeData = data207                if data == nil { item.state = .failed(L("This server does not support resuming.")) }208            }209        }210    }211212    func resume(_ item: DownloadItem) async {213        guard item.canResume, let data = item.resumeData, let webView = item.originWebView else { return }214        let download = await webView.resumeDownload(fromResumeData: data)215        download.delegate = self216        item.download = download217        item.resumeData = nil218        item.state = .inProgress219        track(item, download: download)220    }221222    func remove(_ item: DownloadItem) {223        if item.isActive || item.state == .paused { cancel(item) }224        items.removeAll { $0.id == item.id }225        persist()226    }227228    func clearInactive() {229        items.removeAll { !$0.isActive && $0.state != .paused }230        persist()231    }232233    /// Removes every trace of downloads made from private windows.234    func forgetPrivateItems() {235        items.filter { $0.isPrivate && ($0.isActive || $0.state == .paused) }.forEach(cancel)236        items.removeAll(where: \.isPrivate)237    }238239    func reveal(_ item: DownloadItem) {240        guard let destination = item.destination, item.fileExists else { return }241        NSWorkspace.shared.activateFileViewerSelecting([destination])242    }243244    /// Opens a finished file. Files that can run code require an explicit confirmation first.245    func open(_ item: DownloadItem) {246        guard item.state == .finished, let destination = item.destination, item.fileExists else { return }247        if item.risk == .executable {248            let alert = NSAlert()249            alert.alertStyle = .warning250            alert.messageText = L("“%@” can run code on your Mac", item.filename)251            alert.informativeText = L("It was downloaded from %@. Open it only if you trust this source.", item.sourceHost.isEmpty ? L("an unknown site") : item.sourceHost)252            alert.addButton(withTitle: L("Cancel"))253            alert.addButton(withTitle: L("Open"))254            guard alert.runModal() == .alertSecondButtonReturn else { return }255        }256        NSWorkspace.shared.open(destination)257    }258259    private func persist() {260        records.value = items.filter { !$0.isPrivate && !$0.isActive && $0.state != .paused && $0.state != .cancelled }.prefix(200).compactMap { item in261            guard let destination = item.destination else { return nil }262            return DownloadRecord(id: item.id, filename: item.filename, path: destination.path, sourceHost: item.sourceHost,263                                  date: item.startedAt, succeeded: item.state == .finished)264        }265    }266}267
Files main
Menu

Theme