Repository navigation
Expand file tree
/
Copy pathDownload.swift
More file actions
183 lines (163 loc) · 6.22 KB
/
Copy pathDownload.swift
File metadata and controls
183 lines (163 loc) · 6.22 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
import CoderSDK
import CryptoKit
import Foundation
public func download(
src: URL,
dest: URL,
urlSession: URLSession,
headers: [HTTPHeader] = [],
component: CoderComponent = .app,
progressUpdates: (@Sendable (DownloadProgress) -> Void)? = nil
) async throws(DownloadError) {
try await DownloadManager().download(
src: src,
dest: dest,
urlSession: urlSession,
headers: headers,
component: component,
progressUpdates: progressUpdates.flatMap { throttle(interval: .milliseconds(10), $0) }
)
}
func etag(data: Data) -> String {
let sha1Hash = Insecure.SHA1.hash(data: data)
let etag = sha1Hash.map { String(format: "%02x", $0) }.joined()
return "\"\(etag)\""
}
public enum DownloadError: Error {
case unexpectedStatusCode(Int, url: String)
case invalidResponse
case networkError(any Error, url: String)
case fileOpError(any Error)
public var description: String {
switch self {
case let .unexpectedStatusCode(code, url):
"Unexpected HTTP status code: \(code) - \(url)"
case let .networkError(error, url):
"Network error: \(url) - \(error.localizedDescription)"
case let .fileOpError(error):
"File operation error: \(error.localizedDescription)"
case .invalidResponse:
"Received non-HTTP response"
}
}
public var localizedDescription: String { description }
}
// The async `URLSession.download` api ignores the passed-in delegate, so we
// wrap the older delegate methods in an async adapter with a continuation.
private final class DownloadManager: NSObject, @unchecked Sendable {
private var continuation: CheckedContinuation<Void, Error>!
private var progressHandler: ((DownloadProgress) -> Void)?
private var dest: URL!
func download(
src: URL,
dest: URL,
urlSession: URLSession,
headers: [HTTPHeader] = [],
component: CoderComponent = .app,
progressUpdates: (@Sendable (DownloadProgress) -> Void)?
) async throws(DownloadError) {
var req = URLRequest(url: src)
req.setCoderUserAgent(component, unlessIn: headers)
for header in headers {
req.addValue(header.value, forHTTPHeaderField: header.name)
}
if FileManager.default.fileExists(atPath: dest.path) {
if let existingFileData = try? Data(contentsOf: dest, options: .mappedIfSafe) {
req.setValue(etag(data: existingFileData), forHTTPHeaderField: "If-None-Match")
}
}
let downloadTask = urlSession.downloadTask(with: req)
progressHandler = progressUpdates
self.dest = dest
downloadTask.delegate = self
do {
try await withCheckedThrowingContinuation { continuation in
self.continuation = continuation
downloadTask.resume()
}
} catch let error as DownloadError {
throw error
} catch {
throw .networkError(error, url: src.absoluteString)
}
}
}
extension DownloadManager: URLSessionDownloadDelegate {
// Progress
func urlSession(
_: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData _: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite _: Int64
) {
let maybeLength = (downloadTask.response as? HTTPURLResponse)?
.value(forHTTPHeaderField: "X-Original-Content-Length")
.flatMap(Int64.init)
progressHandler?(.init(totalBytesWritten: totalBytesWritten, totalBytesToWrite: maybeLength))
}
// Completion
func urlSession(_: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let httpResponse = downloadTask.response as? HTTPURLResponse else {
continuation.resume(throwing: DownloadError.invalidResponse)
return
}
guard httpResponse.statusCode != 304 else {
// We already have the latest binary downloaded in dest
continuation.resume()
return
}
guard httpResponse.statusCode == 200 else {
continuation.resume(
throwing: DownloadError.unexpectedStatusCode(
httpResponse.statusCode,
url: httpResponse.url?.absoluteString ?? "Unknown URL"
)
)
return
}
do {
if FileManager.default.fileExists(atPath: dest.path) {
try FileManager.default.removeItem(at: dest)
}
try FileManager.default.moveItem(at: location, to: dest)
} catch {
continuation.resume(throwing: DownloadError.fileOpError(error))
return
}
continuation.resume()
}
// Failure
func urlSession(_: URLSession, task _: URLSessionTask, didCompleteWithError error: Error?) {
if let error {
continuation.resume(throwing: error)
}
}
}
@objc public final class DownloadProgress: NSObject, NSSecureCoding, @unchecked Sendable {
public static var supportsSecureCoding: Bool { true }
public let totalBytesWritten: Int64
public let totalBytesToWrite: Int64?
public init(totalBytesWritten: Int64, totalBytesToWrite: Int64?) {
self.totalBytesWritten = totalBytesWritten
self.totalBytesToWrite = totalBytesToWrite
}
public required convenience init?(coder: NSCoder) {
let written = coder.decodeInt64(forKey: "written")
let total = coder.containsValue(forKey: "total") ? coder.decodeInt64(forKey: "total") : nil
self.init(totalBytesWritten: written, totalBytesToWrite: total)
}
public func encode(with coder: NSCoder) {
coder.encode(totalBytesWritten, forKey: "written")
if let total = totalBytesToWrite {
coder.encode(total, forKey: "total")
}
}
override public var description: String {
let fmt = ByteCountFormatter()
let done = fmt.string(fromByteCount: totalBytesWritten)
.padding(toLength: 7, withPad: " ", startingAt: 0)
let total = totalBytesToWrite.map { fmt.string(fromByteCount: $0) } ?? "Unknown"
return "\(done) / \(total)"
}
}