-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileDownloaderAsync.swift
More file actions
221 lines (186 loc) · 6.96 KB
/
Copy pathFileDownloaderAsync.swift
File metadata and controls
221 lines (186 loc) · 6.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//
// FileDownloaderAsync.swift
// PlayolaPlayer
//
// Created by Brian D Keane on 8/2/25.
//
import Foundation
import PlayolaCore
import os.log
/// An async/await-based file downloader that eliminates deadlock issues
/// by using Swift Concurrency instead of locks and synchronous operations
public actor FileDownloaderAsync {
private var downloadTask: URLSessionDownloadTask?
private var progressContinuation: AsyncStream<Double>.Continuation?
private var isCancelled = false
private let logger = Logger(subsystem: "fm.playola", category: "FileDownloaderAsync")
/// Result of a successful download
public struct DownloadResult {
public let localURL: URL
public let response: URLResponse
}
/// Download progress events
public enum DownloadEvent {
case progress(Double)
case completed(DownloadResult)
case failed(Error)
}
public func download(from url: URL, to destinationURL: URL) async throws -> DownloadResult {
guard !isCancelled else { throw URLError(.cancelled) }
let configuration = makeTLS12Configuration()
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 300
configuration.waitsForConnectivity = true
let session = URLSession(configuration: configuration)
defer { session.invalidateAndCancel() }
let (tempURL, response) = try await session.download(from: url)
guard !isCancelled else {
try? FileManager.default.removeItem(at: tempURL)
throw URLError(.cancelled)
}
try await moveFile(from: tempURL, to: destinationURL)
return DownloadResult(localURL: destinationURL, response: response)
}
public func downloadWithProgress(from url: URL, to destinationURL: URL) -> AsyncStream<
DownloadEvent
> {
AsyncStream { continuation in
let task = Task {
await self.performDownload(from: url, to: destinationURL, continuation: continuation)
}
continuation.onTermination = { _ in
task.cancel()
}
}
}
private func performDownload(
from url: URL,
to destinationURL: URL,
continuation: AsyncStream<DownloadEvent>.Continuation
) async {
guard !isCancelled && !Task.isCancelled else {
continuation.yield(.failed(URLError(.cancelled)))
continuation.finish()
return
}
do {
let delegate = DownloadDelegate(
progressHandler: { continuation.yield(.progress($0)) },
destinationURL: destinationURL,
logger: logger
)
let configuration = makeTLS12Configuration()
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 300
configuration.waitsForConnectivity = true
let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
defer { session.invalidateAndCancel() }
let task = session.downloadTask(with: url)
self.downloadTask = task
let (finalURL, response) = try await withCheckedThrowingContinuation {
(continuation: CheckedContinuation<(URL, URLResponse), Error>) in
delegate.completionHandler = { result in
switch result {
case .success(let (url, response)): continuation.resume(returning: (url, response))
case .failure(let error): continuation.resume(throwing: error)
}
}
task.resume()
}
guard !isCancelled && !Task.isCancelled else {
try? FileManager.default.removeItem(at: finalURL)
throw URLError(.cancelled)
}
continuation.yield(.completed(DownloadResult(localURL: finalURL, response: response)))
} catch {
continuation.yield(.failed(error))
}
continuation.finish()
}
private func moveFile(from source: URL, to destination: URL) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
Task.detached(priority: .utility) {
do {
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: source.path) else {
throw URLError(.fileDoesNotExist)
}
if fileManager.fileExists(atPath: destination.path) {
try fileManager.removeItem(at: destination)
}
let destinationDirectory = destination.deletingLastPathComponent()
if !fileManager.fileExists(atPath: destinationDirectory.path) {
try fileManager.createDirectory(
at: destinationDirectory, withIntermediateDirectories: true, attributes: nil)
}
try fileManager.moveItem(at: source, to: destination)
continuation.resume()
} catch {
continuation.resume(throwing: error)
}
}
}
}
public func cancel() {
isCancelled = true
downloadTask?.cancel()
}
/// URLSession delegate for handling download progress and completion
private class DownloadDelegate: NSObject, URLSessionDownloadDelegate {
let progressHandler: (Double) -> Void
var completionHandler: ((Result<(URL, URLResponse), Error>) -> Void)?
private var hasCompleted = false
let destinationURL: URL
let logger: Logger
init(progressHandler: @escaping (Double) -> Void, destinationURL: URL, logger: Logger) {
self.progressHandler = progressHandler
self.destinationURL = destinationURL
self.logger = logger
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64
) {
guard totalBytesExpectedToWrite > 0 else { return }
let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
progressHandler(progress)
}
func urlSession(
_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL
) {
guard !hasCompleted else { return }
hasCompleted = true
do {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.destinationURL.path) {
try fileManager.removeItem(at: self.destinationURL)
}
let destinationDirectory = self.destinationURL.deletingLastPathComponent()
if !fileManager.fileExists(atPath: destinationDirectory.path) {
try fileManager.createDirectory(
at: destinationDirectory, withIntermediateDirectories: true, attributes: nil)
}
try fileManager.moveItem(at: location, to: self.destinationURL)
if let response = downloadTask.response {
completionHandler?(.success((self.destinationURL, response)))
} else {
completionHandler?(.failure(URLError(.badServerResponse)))
}
} catch {
completionHandler?(.failure(error))
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
guard !hasCompleted else { return }
if let error = error {
hasCompleted = true
completionHandler?(.failure(error))
}
}
}
}