-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathCDNClient.swift
More file actions
188 lines (163 loc) · 6.36 KB
/
CDNClient.swift
File metadata and controls
188 lines (163 loc) · 6.36 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
//
// Copyright © 2026 Stream.io Inc. All rights reserved.
//
import Foundation
/// An uploaded file.
public struct UploadedFile: Decodable {
public let fileURL: URL
public let thumbnailURL: URL?
public init(fileURL: URL, thumbnailURL: URL? = nil) {
self.fileURL = fileURL
self.thumbnailURL = thumbnailURL
}
}
/// Default implementation of CDNUploader that uses Stream's API.
final class StreamCDNUploader: CDNUploader, @unchecked Sendable {
static var maxAttachmentSize: Int64 { 100 * 1024 * 1024 }
private let decoder: RequestDecoder
private let encoder: RequestEncoder
private let session: URLSession
@Atomic private var taskProgressObservers: [Int: NSKeyValueObservation] = [:]
init(
encoder: RequestEncoder,
decoder: RequestDecoder,
sessionConfiguration: URLSessionConfiguration
) {
self.encoder = encoder
session = URLSession(configuration: sessionConfiguration)
self.decoder = decoder
}
func uploadAttachment(
_ attachment: AnyChatMessageAttachment,
progress: (@Sendable (Double) -> Void)? = nil,
completion: @escaping @Sendable (Result<UploadedFile, Error>) -> Void
) {
guard
let uploadingState = attachment.uploadingState,
let fileData = try? Data(contentsOf: uploadingState.localFileURL) else {
return completion(.failure(ClientError.AttachmentUploading(id: attachment.id)))
}
let endpoint = Endpoint<FileUploadPayload>.uploadAttachment(with: attachment.id.cid, type: attachment.type)
uploadAttachment(
endpoint: endpoint,
fileData: fileData,
uploadingState: uploadingState,
progress: progress,
completion: completion
)
}
func uploadAttachment(
localUrl: URL,
progress: (@Sendable (Double) -> Void)? = nil,
completion: @escaping @Sendable (Result<UploadedFile, Error>) -> Void
) {
let uploadingState: AttachmentUploadingState
do {
uploadingState = AttachmentUploadingState(
localFileURL: localUrl,
state: .pendingUpload,
file: try .init(url: localUrl)
)
} catch {
completion(.failure(error))
return
}
guard let fileData = try? Data(contentsOf: localUrl) else {
return completion(.failure(ClientError.Unknown()))
}
let isImage = uploadingState.file.type.isImage
let endpoint = Endpoint<FileUploadPayload>.uploadAttachment(type: isImage ? .image : .file)
uploadAttachment(
endpoint: endpoint,
fileData: fileData,
uploadingState: uploadingState,
progress: progress,
completion: completion
)
}
func deleteAttachment(
remoteUrl: URL,
completion: @escaping @Sendable (Error?) -> Void
) {
let isImage = AttachmentFileType(ext: remoteUrl.pathExtension).isImage
let endpoint = Endpoint<EmptyResponse>
.deleteAttachment(
url: remoteUrl,
type: isImage ? .image : .file
)
encoder.encodeRequest(for: endpoint) { [weak self] (requestResult) in
var urlRequest: URLRequest
do {
urlRequest = try requestResult.get()
} catch {
log.error(error, subsystems: .httpRequests)
completion(error)
return
}
guard let self = self else {
return
}
self.session.dataTask(with: urlRequest, completionHandler: { _, _, error in
completion(error)
}).resume()
}
}
private func uploadAttachment<ResponsePayload>(
endpoint: Endpoint<ResponsePayload>,
fileData: Data,
uploadingState: AttachmentUploadingState,
progress: (@Sendable (Double) -> Void)? = nil,
completion: @escaping @Sendable (Result<UploadedFile, Error>) -> Void
) {
let multipartFormData = MultipartFormData(
fileData,
fileName: uploadingState.localFileURL.lastPathComponent,
mimeType: uploadingState.file.type.mimeType
)
encoder.encodeRequest(for: endpoint) { [weak self] (requestResult) in
var urlRequest: URLRequest
do {
urlRequest = try requestResult.get()
} catch {
log.error(error, subsystems: .httpRequests)
completion(.failure(error))
return
}
let data = multipartFormData.getMultipartFormData()
urlRequest.addValue("multipart/form-data; boundary=\(MultipartFormData.boundary)", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = data
guard let self = self else {
log.warning("Callback called while self is nil", subsystems: .httpRequests)
return
}
let task = self.session.dataTask(with: urlRequest) { [decoder = self.decoder] (data, response, error) in
do {
let response: FileUploadPayload = try decoder.decodeRequestResponse(
data: data,
response: response,
error: error
)
let file = UploadedFile(fileURL: response.fileURL, thumbnailURL: response.thumbURL)
completion(.success(file))
} catch {
completion(.failure(error))
}
}
if let progressListener = progress {
let taskID = task.taskIdentifier
self._taskProgressObservers.mutate { observers in
observers[taskID] = task.progress.observe(\.fractionCompleted) { [weak self] progress, _ in
progressListener(progress.fractionCompleted)
if progress.isFinished || progress.isCancelled {
self?._taskProgressObservers.mutate { observers in
observers[taskID]?.invalidate()
observers[taskID] = nil
}
}
}
}
}
task.resume()
}
}
}