Repository Public License
1import Diagnostics2import Foundation3import NavigatorCore4import Persistence56// MARK: - Public model78/// A download as the list shows it: the stored model plus what only exists while the app runs.9public struct DownloadItem: Sendable, Equatable, Identifiable {10 public var download: Download11 /// Started in a private window: tracked in memory only, gone when that window closes. The file stays.12 public var isGhost: Bool13 public var risk: DownloadRisk14 /// Average speed over the last seconds; `nil` when unknown, 0 when stalled.15 public var bytesPerSecond: Double?16 public var estimatedSecondsRemaining: TimeInterval?17 /// The app stopped (quit, crash, kill) while this download was running. It was not restarted.18 public var wasInterrupted: Bool1920 public var id: DownloadID { download.id }21 /// The transfer can continue from where it stopped (the web layer produced resume data).22 public var canResume: Bool {23 download.resumeData != nil && [.paused, .failed, .cancelled].contains(download.state)24 }25 public var fileURL: URL? { download.destinationPath.map { URL(fileURLWithPath: $0) } }26}2728public enum DownloadUpdate: Sendable, Equatable {29 case added(DownloadItem)30 case changed(DownloadItem)31 case removed(DownloadID)32}3334/// What the UI is asked when a download needs a decision.35public struct DownloadQuestion: Sendable, Equatable {36 public var candidate: DownloadCandidate37 /// Sanitised file name.38 public var filename: String39 public var mimeType: String?40 public var expectedBytes: Int64?41 public var risk: DownloadRisk42 /// Proposed location (default directory + unique name).43 public var suggestedURL: URL44}4546/// Asks the user. Implemented by the UI layer; every method may show a sheet and take as long as the user does.47public protocol DownloadPrompter: Sendable {48 /// "Ask where to save each file": the chosen file URL, or `nil` to cancel the download. If the user chose49 /// to replace an existing file, the manager removes it before the transfer starts.50 func chooseDestination(for question: DownloadQuestion) async -> URL?51 /// A page started a download without a user gesture: allow it?52 func allowAutomaticDownload(_ question: DownloadQuestion) async -> Bool53}5455/// Starts transfers on behalf of the manager. The manager never talks to WebKit: the app implements this on56/// top of the web layer (`WebEngine.resumeDownload(resumeData:id:destination:)`, `startDownload`) and the web57/// layer then reports back through `DownloadSink` with the same `DownloadID`.58public protocol DownloadTransferStarter: Sendable {59 func resumeDownload(id: DownloadID, profileID: ProfileID, resumeData: Data, destination: URL) async throws60 func restartDownload(id: DownloadID, profileID: ProfileID, sourceURL: URL, originURL: URL?) async throws61}6263public enum DownloadError: Error, Sendable, Equatable {64 case notFound65 /// The operation does not apply to the download's current state.66 case invalidState(Download.State)67 /// No resume data: the transfer can only be restarted from the beginning.68 case notResumable69 /// The app did not provide a `DownloadTransferStarter`.70 case noTransferStarter71 case fileMissing72}7374public enum DownloadPauseResult: Sendable, Equatable {75 case paused76 /// The server does not support resuming: the transfer was stopped and can only be restarted.77 case stoppedNotResumable78}7980/// What the UI should do when the user asks to open a finished download.81public enum DownloadOpenDecision: Sendable, Equatable {82 case open(URL)83 /// Executable, installer, script…: show a confirmation naming the risk, then call again with `confirmed: true`.84 case needsConfirmation(URL, DownloadRisk)85 case unavailable(DownloadError)86}8788public enum DownloadSettings {89 /// Ask where to save each file instead of using the downloads directory.90 public static let askEveryTime = SettingKey<Bool>("downloads.ask_every_time", default: false)91 /// Bookmark of a directory the user chose instead of the system Downloads folder (security-scoped on macOS).92 public static let directoryBookmark = SettingKey<Data?>("downloads.directory_bookmark", default: nil)93}9495// MARK: - Manager9697/// The download list and its rules. Implements `DownloadSink`, which the web layer calls for every download.98///99/// - Destination: the downloads directory with a unique name, or the user's choice ("ask every time").100/// File names are derived and sanitised by `DownloadFilename`; the destination is always a direct child of the101/// chosen directory and never an existing file.102/// - Persistence: `database.downloads`, except for private (ghost) profiles, whose downloads exist only in103/// this actor's memory and leave the list with `endGhostSession`. **The downloaded file is not removed**: the104/// UI must say so (`PrivacyText.ghostDownloadKept` in PrivacyEngine).105/// - Progress: speed and remaining time over a sliding window; updates to observers at most every 250 ms and106/// to storage at most every 2 s; state changes are never throttled.107/// - Nothing is restarted behind the user's back: downloads found running at launch are marked failed108/// (`recoverInterrupted`), and resuming or restarting is always an explicit call.109public actor DownloadManager: DownloadSink {110 /// `errorDescription` of a download interrupted by the app stopping. A key, not a sentence: the UI localises it.111 public static let interruptedErrorKey = "download.error.interrupted"112 public static let destinationErrorKey = "download.error.destination_unavailable"113114 private struct Entry {115 var item: DownloadItem116 var meter = DownloadSpeedMeter()117 var uiThrottle = ProgressThrottle(interval: 0.25)118 var storageThrottle = ProgressThrottle(interval: 2)119 var control: (any DownloadControl)?120 var isStored = false121 var pauseRequested = false122 var cancelRequested = false123 }124125 private let database: NavigatorDatabase126 private let now: @Sendable () -> Date127 private let defaultDirectory: URL128 private let permissions: (any PermissionProvider)?129 private var prompter: (any DownloadPrompter)?130 private var starter: (any DownloadTransferStarter)?131132 private var entries: [DownloadID: Entry] = [:]133 private var observers: [UUID: AsyncStream<DownloadUpdate>.Continuation] = [:]134135 /// - Parameters:136 /// - defaultDirectory: where files go by default; `nil` = the user's Downloads folder137 /// (on iOS, `Documents/Downloads` inside the app container).138 /// - permissions: when given, a download the user did not start is subject to the `downloads` permission139 /// of the page's origin.140 public init(database: NavigatorDatabase, defaultDirectory: URL? = nil, permissions: (any PermissionProvider)? = nil,141 prompter: (any DownloadPrompter)? = nil, starter: (any DownloadTransferStarter)? = nil,142 now: @escaping @Sendable () -> Date = { .now }) {143 self.database = database144 self.defaultDirectory = defaultDirectory ?? Self.systemDownloadsDirectory()145 self.permissions = permissions146 self.prompter = prompter147 self.starter = starter148 self.now = now149 }150151 public func setPrompter(_ prompter: (any DownloadPrompter)?) { self.prompter = prompter }152 public func setTransferStarter(_ starter: (any DownloadTransferStarter)?) { self.starter = starter }153154 static func systemDownloadsDirectory() -> URL {155 #if os(macOS)156 return FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first157 ?? FileManager.default.homeDirectoryForCurrentUser.appending(path: "Downloads", directoryHint: .isDirectory)158 #else159 let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory160 return documents.appending(path: "Downloads", directoryHint: .isDirectory)161 #endif162 }163164 // MARK: Observation165166 /// Every change of the list, from now on. Each call returns an independent stream.167 public func updates() -> AsyncStream<DownloadUpdate> {168 let id = UUID()169 let (stream, continuation) = AsyncStream<DownloadUpdate>.makeStream(bufferingPolicy: .bufferingNewest(512))170 observers[id] = continuation171 continuation.onTermination = { [weak self] _ in Task { await self?.removeObserver(id) } }172 return stream173 }174175 private func removeObserver(_ id: UUID) { observers[id] = nil }176 private func emit(_ update: DownloadUpdate) { for observer in observers.values { observer.yield(update) } }177178 // MARK: Directory179180 /// The directory downloads go to: the user's chosen directory when its bookmark still resolves, else the181 /// default. On macOS the returned URL of a custom directory is security-scoped: the manager starts182 /// accessing it for the life of the process.183 public func downloadsDirectory() async -> URL {184 guard let bookmark = (try? await database.settings.value(DownloadSettings.directoryBookmark)) ?? nil else { return defaultDirectory }185 var stale = false186 #if os(macOS)187 let options: URL.BookmarkResolutionOptions = [.withSecurityScope]188 #else189 let options: URL.BookmarkResolutionOptions = []190 #endif191 guard let url = try? URL(resolvingBookmarkData: bookmark, options: options, relativeTo: nil, bookmarkDataIsStale: &stale) else {192 return defaultDirectory193 }194 if scopedDirectory != url {195 scopedDirectory?.stopAccessingSecurityScopedResource()196 _ = url.startAccessingSecurityScopedResource()197 scopedDirectory = url198 }199 return url200 }201202 private var scopedDirectory: URL?203204 /// Remembers a directory the user picked (pass the URL returned by the open panel), or `nil` to return to205 /// the default Downloads folder.206 public func setDownloadsDirectory(_ url: URL?) async throws {207 guard let url else {208 scopedDirectory?.stopAccessingSecurityScopedResource()209 scopedDirectory = nil210 try await database.settings.remove(DownloadSettings.directoryBookmark.name)211 return212 }213 #if os(macOS)214 let options: URL.BookmarkCreationOptions = [.withSecurityScope]215 #else216 let options: URL.BookmarkCreationOptions = []217 #endif218 let bookmark: Data219 do { bookmark = try url.bookmarkData(options: options, includingResourceValuesForKeys: nil, relativeTo: nil) } catch {220 // Outside the sandbox (tests, unsigned builds) a security-scoped bookmark cannot be made: a plain one works.221 bookmark = try url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)222 }223 try await database.settings.set(DownloadSettings.directoryBookmark, to: bookmark, at: now())224 }225226 public func asksEveryTime() async -> Bool { (try? await database.settings.value(DownloadSettings.askEveryTime)) ?? false }227228 public func setAsksEveryTime(_ value: Bool) async throws {229 try await database.settings.set(DownloadSettings.askEveryTime, to: value, at: now())230 }231232 /// A free file URL in `directory`: no existing file, no destination of a transfer in progress.233 private func freeURL(in directory: URL, filename: String, excluding id: DownloadID) -> URL {234 let reserved = Set(entries.values.filter { $0.item.id != id && !$0.item.download.state.isTerminal }235 .compactMap { $0.item.download.destinationPath?.lowercased() })236 return DownloadFilename.uniqueURL(in: directory, filename: filename) { candidate in237 reserved.contains(candidate.path(percentEncoded: false).lowercased())238 || FileManager.default.fileExists(atPath: candidate.path(percentEncoded: false))239 }240 }241242 // MARK: Storage helpers243244 private func store(_ id: DownloadID) async {245 guard var entry = entries[id], !entry.item.isGhost else { return }246 do {247 try await database.downloads.save(entry.item.download)248 entry = entries[id] ?? entry249 entry.isStored = true250 if entries[id] != nil { entries[id] = entry }251 } catch {252 // A profile that is not stored (ended private session, deleted profile) is refused by storage: the253 // download then simply lives in memory. Never retried with another owner.254 Log.downloads.error("Download not stored: \(String(describing: error), privacy: .public)")255 }256 }257258 private func changed(_ id: DownloadID, persist: Bool = true) async {259 guard let entry = entries[id] else { return }260 emit(.changed(entry.item))261 if persist { await store(id) }262 }263264 // MARK: DownloadSink265266 public func downloadWillBegin(_ candidate: DownloadCandidate, control: any DownloadControl) async {267 if var entry = entries[candidate.id] {268 // The same id again: a resume or a restart the user asked for.269 entry.control = control270 entry.pauseRequested = false271 entry.cancelRequested = false272 entry.item.download.state = .running273 entry.item.download.errorDescription = nil274 entry.item.download.finishedAt = nil275 entry.item.wasInterrupted = false276 entry.meter.reset()277 entries[candidate.id] = entry278 await changed(candidate.id)279 return280 }281 // A resume of a download from a previous run: the row exists, the entry does not.282 if !candidate.isGhost, var stored = (try? await database.downloads.download(candidate.id)) ?? nil {283 stored.state = .running284 stored.errorDescription = nil285 stored.finishedAt = nil286 var entry = Entry(item: DownloadItem(download: stored, isGhost: false,287 risk: DownloadRiskClassifier.classify(filename: stored.filename, mimeType: stored.mimeType),288 bytesPerSecond: nil, estimatedSecondsRemaining: nil, wasInterrupted: false))289 entry.control = control290 entry.isStored = true291 entries[candidate.id] = entry292 await changed(candidate.id)293 return294 }295 let provisional = DownloadFilename.derive(url: candidate.sourceURL).name296 let download = Download(id: candidate.id, profileID: candidate.profileID, sourceURL: candidate.sourceURL,297 originURL: candidate.originURL, filename: provisional, state: .pending, startedAt: now())298 var entry = Entry(item: DownloadItem(download: download, isGhost: candidate.isGhost, risk: .safe, bytesPerSecond: nil,299 estimatedSecondsRemaining: nil, wasInterrupted: false))300 entry.control = control301 entries[candidate.id] = entry302 // Not announced and not stored yet: until a destination is chosen there is nothing to show, and a303 // download the user cancels in the save panel must leave no trace.304 }305306 public func destination(for candidate: DownloadCandidate, response: DownloadResponseInfo) async -> DownloadDestination {307 if entries[candidate.id] == nil {308 // The web layer skipped `downloadWillBegin` (it must not, but a sink has to be robust).309 let download = Download(id: candidate.id, profileID: candidate.profileID, sourceURL: candidate.sourceURL,310 originURL: candidate.originURL, filename: DownloadFilename.defaultName, state: .pending, startedAt: now())311 entries[candidate.id] = Entry(item: DownloadItem(download: download, isGhost: candidate.isGhost, risk: .safe,312 bytesPerSecond: nil, estimatedSecondsRemaining: nil, wasInterrupted: false))313 }314 let filename = DownloadFilename.derive(suggested: response.suggestedFilename, url: candidate.sourceURL,315 mimeType: response.mimeType).name316 let risk = DownloadRiskClassifier.classify(filename: filename, mimeType: response.mimeType)317 let directory = await downloadsDirectory()318 let suggestedURL = freeURL(in: directory, filename: filename, excluding: candidate.id)319 let question = DownloadQuestion(candidate: candidate, filename: filename, mimeType: response.mimeType,320 expectedBytes: response.expectedBytes, risk: risk, suggestedURL: suggestedURL)321322 // A download the page started by itself needs the site's permission.323 if !candidate.isUserInitiated, let permissions, let origin = WebOrigin(url: candidate.originURL ?? candidate.sourceURL) {324 switch await permissions.verdict(for: .downloads, origin: origin, profileID: candidate.profileID) {325 case .allow: break326 case .deny: return await abandon(candidate.id)327 case .ask:328 // Without a UI to ask, the download proceeds: refusing would break every download on systems329 // where WebKit cannot tell whether the user started it.330 if let prompter, !(await prompter.allowAutomaticDownload(question)) { return await abandon(candidate.id) }331 }332 }333334 var target = suggestedURL335 if await asksEveryTime(), let prompter {336 guard let chosen = await prompter.chooseDestination(for: question), chosen.isFileURL else { return await abandon(candidate.id) }337 // The name typed in a save panel is the user's, but it still goes through the sanitiser: a338 // panel cannot return a path separator, and control or bidi characters have no business in it.339 let parent = chosen.deletingLastPathComponent()340 let name = DownloadFilename.sanitize(chosen.lastPathComponent) ?? filename341 target = parent.appending(path: name, directoryHint: .notDirectory)342 guard DownloadFilename.isDirectChild(target, of: parent) else { return await abandon(candidate.id) }343 // The user confirmed the replacement in the panel; the web layer needs the path to be free.344 if FileManager.default.fileExists(atPath: target.path(percentEncoded: false)) { try? FileManager.default.removeItem(at: target) }345 }346 do {347 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)348 } catch {349 guard var entry = entries[candidate.id] else { return .cancel }350 entry.item.download.filename = filename351 entry.item.download.mimeType = response.mimeType352 entry.item.download.state = .failed353 entry.item.download.errorDescription = Self.destinationErrorKey354 entry.item.download.finishedAt = now()355 entry.item.risk = risk356 entry.control = nil357 entries[candidate.id] = entry358 emit(.added(entry.item))359 await store(candidate.id)360 return .cancel361 }362363 guard var entry = entries[candidate.id] else { return .cancel }364 let wasAnnounced = entry.item.download.destinationPath != nil365 entry.item.download.filename = target.lastPathComponent366 entry.item.download.destinationPath = target.path(percentEncoded: false)367 entry.item.download.mimeType = response.mimeType368 entry.item.download.totalBytes = response.expectedBytes.flatMap { $0 > 0 ? $0 : nil }369 entry.item.download.state = .running370 entry.item.risk = DownloadRiskClassifier.classify(filename: target.lastPathComponent, mimeType: response.mimeType)371 entries[candidate.id] = entry372 emit(wasAnnounced ? .changed(entry.item) : .added(entry.item))373 await store(candidate.id)374 return .save(target)375 }376377 /// Drops a download that never got a destination.378 private func abandon(_ id: DownloadID) async -> DownloadDestination {379 if let entry = entries.removeValue(forKey: id), entry.isStored {380 try? await database.downloads.delete(id)381 emit(.removed(id))382 }383 return .cancel384 }385386 public func download(_ id: DownloadID, didEmit event: DownloadEvent) async {387 guard var entry = entries[id] else { return }388 let date = now()389 switch event {390 case .progress(let received, let total):391 guard entry.item.download.state == .running || entry.item.download.state == .pending else { return }392 entry.item.download.bytesReceived = max(received, 0)393 if let total, total > 0 { entry.item.download.totalBytes = total }394 entry.meter.record(bytes: max(received, 0), at: date)395 entry.item.bytesPerSecond = entry.meter.bytesPerSecond(at: date)396 entry.item.estimatedSecondsRemaining = entry.meter.estimatedSecondsRemaining(totalBytes: entry.item.download.totalBytes, at: date)397 let showNow = entry.uiThrottle.shouldEmit(at: date)398 let storeNow = entry.isStored && entry.storageThrottle.shouldEmit(at: date)399 entries[id] = entry400 if showNow { emit(.changed(entry.item)) }401 if storeNow {402 try? await database.downloads.updateProgress(id, bytesReceived: entry.item.download.bytesReceived,403 totalBytes: entry.item.download.totalBytes)404 }405406 case .finished(let fileURL):407 entry.item.download.state = .finished408 entry.item.download.finishedAt = date409 entry.item.download.destinationPath = fileURL.path(percentEncoded: false)410 entry.item.download.filename = fileURL.lastPathComponent411 entry.item.download.resumeData = nil412 entry.item.download.errorDescription = nil413 // The file on disk is the truth about the size.414 let size = (try? FileManager.default.attributesOfItem(atPath: fileURL.path(percentEncoded: false))[.size] as? NSNumber)?.int64Value415 if let size { entry.item.download.bytesReceived = size; entry.item.download.totalBytes = size } else if let total = entry.item.download.totalBytes {416 entry.item.download.bytesReceived = total417 }418 entry.item.risk = DownloadRiskClassifier.classify(filename: fileURL.lastPathComponent, mimeType: entry.item.download.mimeType)419 finish(&entry)420 entries[id] = entry421 await changed(id)422423 case .failed(let message, let resumeData):424 entry.item.download.state = .failed425 entry.item.download.finishedAt = date426 entry.item.download.errorDescription = String(message.prefix(500))427 entry.item.download.resumeData = resumeData428 finish(&entry)429 entries[id] = entry430 await changed(id)431432 case .cancelled(let resumeData):433 // Our own pause / cancel already recorded the outcome; the web layer's event confirms it.434 guard entry.item.download.state == .running || entry.item.download.state == .pending else { return }435 apply(cancellationOf: &entry, resumeData: resumeData, at: date)436 entries[id] = entry437 await changed(id)438 }439 }440441 private func finish(_ entry: inout Entry) {442 entry.control = nil443 entry.pauseRequested = false444 entry.cancelRequested = false445 entry.item.bytesPerSecond = nil446 entry.item.estimatedSecondsRemaining = nil447 entry.meter.reset()448 }449450 private func apply(cancellationOf entry: inout Entry, resumeData: Data?, at date: Date) {451 if entry.pauseRequested, let resumeData {452 entry.item.download.state = .paused453 entry.item.download.resumeData = resumeData454 } else {455 entry.item.download.state = .cancelled456 entry.item.download.finishedAt = date457 // A cancelled download is discarded, a pause that could not be honoured is not resumable either way.458 entry.item.download.resumeData = nil459 if !entry.pauseRequested { removePartialFile(of: entry.item.download) }460 }461 finish(&entry)462 }463464 /// Removes what a cancelled transfer left at its destination. Only a regular file at the recorded path.465 private func removePartialFile(of download: Download) {466 guard let path = download.destinationPath else { return }467 var isDirectory: ObjCBool = false468 guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), !isDirectory.boolValue else { return }469 try? FileManager.default.removeItem(atPath: path)470 }471472 // MARK: Control473474 /// Pauses a running download: the transfer is stopped with resume data. When the server does not allow475 /// resuming, the download ends as cancelled and can only be restarted.476 @discardableResult477 public func pause(_ id: DownloadID) async throws -> DownloadPauseResult {478 guard var entry = entries[id] else { throw DownloadError.notFound }479 guard entry.item.download.state == .running, let control = entry.control else { throw DownloadError.invalidState(entry.item.download.state) }480 entry.pauseRequested = true481 entries[id] = entry482 let resumeData = await control.cancel()483 guard var current = entries[id] else { throw DownloadError.notFound }484 if current.item.download.state == .running || current.item.download.state == .pending {485 apply(cancellationOf: ¤t, resumeData: resumeData, at: now())486 entries[id] = current487 await changed(id)488 }489 return entries[id]?.item.download.state == .paused ? .paused : .stoppedNotResumable490 }491492 /// Cancels a download and discards what was received.493 public func cancel(_ id: DownloadID) async throws {494 guard var entry = entries[id] else { throw DownloadError.notFound }495 let state = entry.item.download.state496 guard state == .running || state == .pending || state == .paused else { throw DownloadError.invalidState(state) }497 entry.cancelRequested = true498 entry.pauseRequested = false499 entries[id] = entry500 _ = await entry.control?.cancel()501 guard var current = entries[id] else { return }502 if current.item.download.state != .cancelled {503 current.pauseRequested = false504 current.item.download.state = .running // so that the shared path below applies whatever the state was505 apply(cancellationOf: ¤t, resumeData: nil, at: now())506 entries[id] = current507 await changed(id)508 }509 }510511 /// Continues a paused or failed download from its resume data. The transfer is started by the512 /// `DownloadTransferStarter`; the download is `.pending` until the web layer reports it began.513 public func resume(_ id: DownloadID) async throws {514 var entry = try await loadedEntry(id)515 let download = entry.item.download516 guard [.paused, .failed, .cancelled].contains(download.state) else { throw DownloadError.invalidState(download.state) }517 guard let resumeData = download.resumeData, let path = download.destinationPath else { throw DownloadError.notResumable }518 guard let starter else { throw DownloadError.noTransferStarter }519 entry.item.download.state = .pending520 entry.item.download.errorDescription = nil521 entry.item.download.finishedAt = nil522 entry.item.wasInterrupted = false523 entries[id] = entry524 await changed(id)525 do {526 try await starter.resumeDownload(id: id, profileID: download.profileID, resumeData: resumeData, destination: URL(fileURLWithPath: path))527 } catch {528 await fail(id, message: String(describing: error))529 throw error530 }531 }532533 /// Starts a download again from the beginning (the user asked for it explicitly). What was received is534 /// discarded; the web layer will ask for a destination again.535 public func restart(_ id: DownloadID) async throws {536 var entry = try await loadedEntry(id)537 let download = entry.item.download538 guard download.state.isTerminal || download.state == .paused else { throw DownloadError.invalidState(download.state) }539 guard let starter else { throw DownloadError.noTransferStarter }540 if download.state != .finished { removePartialFile(of: download) }541 entry.item.download.state = .pending542 entry.item.download.bytesReceived = 0543 entry.item.download.resumeData = nil544 entry.item.download.errorDescription = nil545 entry.item.download.finishedAt = nil546 entry.item.download.startedAt = now()547 entry.item.wasInterrupted = false548 entries[id] = entry549 await changed(id)550 do {551 try await starter.restartDownload(id: id, profileID: download.profileID, sourceURL: download.sourceURL, originURL: download.originURL)552 } catch {553 await fail(id, message: String(describing: error))554 throw error555 }556 }557558 private func fail(_ id: DownloadID, message: String) async {559 guard var entry = entries[id] else { return }560 entry.item.download.state = .failed561 entry.item.download.errorDescription = String(message.prefix(500))562 entry.item.download.finishedAt = now()563 finish(&entry)564 entries[id] = entry565 await changed(id)566 }567568 /// The entry of a download, loading it from storage when it belongs to a previous run.569 private func loadedEntry(_ id: DownloadID) async throws -> Entry {570 if let entry = entries[id] { return entry }571 guard let stored = try await database.downloads.download(id) else { throw DownloadError.notFound }572 var entry = Entry(item: DownloadItem(download: stored, isGhost: false,573 risk: DownloadRiskClassifier.classify(filename: stored.filename, mimeType: stored.mimeType),574 bytesPerSecond: nil, estimatedSecondsRemaining: nil,575 wasInterrupted: stored.errorDescription == Self.interruptedErrorKey))576 entry.isStored = true577 entries[id] = entry578 return entry579 }580581 // MARK: Launch582583 /// Call once at launch, before any download starts. Downloads that were pending or running when the app584 /// last stopped are marked failed with `interruptedErrorKey` — resumable when resume data was stored,585 /// restartable otherwise — and **never restarted automatically**. Returns them.586 @discardableResult587 public func recoverInterrupted() async throws -> [DownloadItem] {588 var result: [DownloadItem] = []589 for var download in try await database.downloads.interrupted() where entries[download.id] == nil {590 download.state = .failed591 download.errorDescription = Self.interruptedErrorKey592 download.finishedAt = now()593 try await database.downloads.save(download)594 result.append(DownloadItem(download: download, isGhost: false,595 risk: DownloadRiskClassifier.classify(filename: download.filename, mimeType: download.mimeType),596 bytesPerSecond: nil, estimatedSecondsRemaining: nil, wasInterrupted: true))597 }598 return result599 }600601 // MARK: Queries602603 public func item(_ id: DownloadID) async -> DownloadItem? {604 if let entry = entries[id], entry.item.download.destinationPath != nil { return entry.item }605 return try? await loadedEntry(id).item606 }607608 /// The download list of a profile, most recent first: stored downloads merged with the live state of609 /// those in progress. For a private profile, only what this session holds in memory.610 public func items(profile: ProfileID, limit: Int = 500) async throws -> [DownloadItem] {611 var byID: [DownloadID: DownloadItem] = [:]612 if !database.ghosts.contains(profile.raw) {613 for download in try await database.downloads.downloads(profile: profile, limit: limit) {614 byID[download.id] = DownloadItem(download: download, isGhost: false,615 risk: DownloadRiskClassifier.classify(filename: download.filename, mimeType: download.mimeType),616 bytesPerSecond: nil, estimatedSecondsRemaining: nil,617 wasInterrupted: download.errorDescription == Self.interruptedErrorKey)618 }619 }620 // Downloads still waiting for a destination are not listed.621 for entry in entries.values where entry.item.download.profileID == profile && entry.item.download.destinationPath != nil {622 byID[entry.item.id] = entry.item623 }624 return Array(byID.values.sorted {625 $0.download.startedAt != $1.download.startedAt ? $0.download.startedAt > $1.download.startedAt : $0.id < $1.id626 }.prefix(limit))627 }628629 public func activeCount(profile: ProfileID? = nil) -> Int {630 entries.values.filter { $0.item.download.state.isActive && (profile == nil || $0.item.download.profileID == profile) }.count631 }632633 // MARK: Completion actions634635 /// The file to reveal in Finder / Files, when it still exists.636 public func revealURL(_ id: DownloadID) async -> Result<URL, DownloadError> {637 guard let item = await item(id) else { return .failure(.notFound) }638 guard let url = item.fileURL, FileManager.default.fileExists(atPath: url.path(percentEncoded: false)) else { return .failure(.fileMissing) }639 return .success(url)640 }641642 /// Whether the UI may open the file now. A risky file (executable, installer, script, shortcut,643 /// configuration, disguised extension) is opened only after the user confirmed: call once, show the644 /// confirmation naming `risk.reasons`, call again with `confirmed: true`.645 public func openDecision(_ id: DownloadID, confirmed: Bool = false) async -> DownloadOpenDecision {646 guard let item = await item(id) else { return .unavailable(.notFound) }647 guard item.download.state == .finished else { return .unavailable(.invalidState(item.download.state)) }648 guard let url = item.fileURL, FileManager.default.fileExists(atPath: url.path(percentEncoded: false)) else { return .unavailable(.fileMissing) }649 // Classified again from the name on disk: never from a value cached before the file was written.650 let risk = DownloadRiskClassifier.classify(filename: url.lastPathComponent, mimeType: item.download.mimeType)651 if risk.requiresOpenConfirmation, !confirmed { return .needsConfirmation(url, risk) }652 return .open(url)653 }654655 // MARK: Removing656657 /// Removes a download from the list. An active transfer is cancelled first. With `deletingFile`, the658 /// downloaded file is deleted too (only the regular file at the recorded destination); without it the file659 /// stays where it is. Returns `true` when a file was deleted.660 @discardableResult661 public func remove(_ id: DownloadID, deletingFile: Bool) async throws -> Bool {662 let entry = try await loadedEntry(id)663 if !entry.item.download.state.isTerminal { try? await cancel(id) }664 var deleted = false665 if deletingFile, let path = (entries[id] ?? entry).item.download.destinationPath {666 var isDirectory: ObjCBool = false667 if FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), !isDirectory.boolValue {668 try FileManager.default.removeItem(atPath: path)669 deleted = true670 }671 }672 entries[id] = nil673 if !entry.item.isGhost { try await database.downloads.delete(id) }674 emit(.removed(id))675 return deleted676 }677678 /// Removes finished, failed and cancelled downloads of a profile from the list. Files are not touched.679 @discardableResult680 public func clearInactive(profile: ProfileID) async throws -> Int {681 let gone = entries.values.filter { $0.item.download.profileID == profile && $0.item.download.state.isTerminal }.map(\.item.id)682 for id in gone { entries[id] = nil; emit(.removed(id)) }683 guard !database.ghosts.contains(profile.raw) else { return gone.count }684 let stored = try await database.downloads.clearInactive(profile: profile)685 return max(stored, gone.count)686 }687688 /// A private session ended: its transfers in progress are cancelled (what they had written is removed) and689 /// its downloads leave the list. **Finished files stay on disk**; their URLs are returned so the UI can690 /// tell the user.691 @discardableResult692 public func endGhostSession(profile: ProfileID) async -> [URL] {693 var kept: [URL] = []694 for entry in entries.values where entry.item.isGhost && entry.item.download.profileID == profile {695 let id = entry.item.id696 if !entry.item.download.state.isTerminal { try? await cancel(id) }697 if entry.item.download.state == .finished, let url = entry.item.fileURL { kept.append(url) }698 entries[id] = nil699 emit(.removed(id))700 }701 return kept.sorted { $0.path < $1.path }702 }703}704