-
-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathAttachmentViewModel.swift
More file actions
334 lines (281 loc) · 11.9 KB
/
AttachmentViewModel.swift
File metadata and controls
334 lines (281 loc) · 11.9 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//
// AttachmentViewModel.swift
//
//
// Created by MainasuK on 2021/11/19.
//
import os.log
import UIKit
import Combine
import PhotosUI
import MastodonSDK
import MastodonCore
import MastodonLocalization
import func QuartzCore.CACurrentMediaTime
public protocol AttachmentViewModelDelegate: AnyObject {
func attachmentViewModel(_ viewModel: AttachmentViewModel, uploadStateValueDidChange state: AttachmentViewModel.UploadState)
func attachmentViewModel(_ viewModel: AttachmentViewModel, actionButtonDidPressed action: AttachmentViewModel.Action)
}
final public class AttachmentViewModel: NSObject, ObservableObject, Identifiable {
static let logger = Logger(subsystem: "AttachmentViewModel", category: "ViewModel")
let logger = Logger(subsystem: "AttachmentViewModel", category: "ViewModel")
public let id = UUID()
var disposeBag = Set<AnyCancellable>()
var observations = Set<NSKeyValueObservation>()
weak var delegate: AttachmentViewModelDelegate?
let byteCountFormatter: ByteCountFormatter = {
let formatter = ByteCountFormatter()
formatter.allowsNonnumericFormatting = true
formatter.countStyle = .memory
return formatter
}()
let percentageFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .percent
return formatter
}()
// input
public let api: APIService
public let authContext: AuthContext
public let input: Input
public let sizeLimit: SizeLimit
private let mediaAttachmentSettings: Mastodon.Entity.Instance.Configuration.MediaAttachments?
@Published var caption = ""
@Published public private(set) var isCaptionEditable = true
// output
@Published public private(set) var output: Output?
@Published public private(set) var thumbnail: UIImage? // original size image thumbnail
@Published public private(set) var outputSizeInByte: Int64 = 0
@Published public private(set) var uploadState: UploadState = .none
@Published public private(set) var uploadResult: UploadResult?
@Published var error: Error?
var uploadTask: Task<(), Never>?
@Published var videoCompressProgress: Double = 0
let progress = Progress() // upload progress
@Published var fractionCompleted: Double = 0
private var lastTimestamp: TimeInterval?
private var lastUploadSizeInByte: Int64 = 0
private var averageUploadSpeedInByte: Int64 = 0
private var remainTimeInterval: Double?
@Published var remainTimeLocalizedString: String?
public init(
api: APIService,
authContext: AuthContext,
input: Input,
sizeLimit: SizeLimit,
delegate: AttachmentViewModelDelegate,
mediaAttachmentSettings: Mastodon.Entity.Instance.Configuration.MediaAttachments?
) {
self.api = api
self.authContext = authContext
self.input = input
self.sizeLimit = sizeLimit
self.mediaAttachmentSettings = mediaAttachmentSettings
self.delegate = delegate
super.init()
// end init
Timer.publish(every: 1.0 / 60.0, on: .main, in: .common) // 60 FPS
.autoconnect()
.share()
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self = self else { return }
self.step()
}
.store(in: &disposeBag)
progress
.observe(\.fractionCompleted, options: [.initial, .new]) { [weak self] progress, _ in
guard let self = self else { return }
self.logger.log(level: .debug, "\((#file as NSString).lastPathComponent, privacy: .public)[\(#line, privacy: .public)], \(#function, privacy: .public): publish progress \(progress.fractionCompleted)")
DispatchQueue.main.async {
self.fractionCompleted = progress.fractionCompleted
}
}
.store(in: &observations)
// Note: this observation is redundant if .fractionCompleted listener always emit event when reach 1.0 progress
// progress
// .observe(\.isFinished, options: [.initial, .new]) { [weak self] progress, _ in
// guard let self = self else { return }
// self.logger.log(level: .debug, "\((#file as NSString).lastPathComponent, privacy: .public)[\(#line, privacy: .public)], \(#function, privacy: .public): publish progress \(progress.fractionCompleted)")
// DispatchQueue.main.async {
// self.objectWillChange.send()
// }
// }
// .store(in: &observations)
$output
.map { output -> UIImage? in
switch output {
case .image(let data, _):
return UIImage(data: data)
case .video(let url, _):
return AttachmentViewModel.createThumbnailForVideo(url: url)
case .none:
return nil
}
}
.receive(on: DispatchQueue.main)
.assign(to: &$thumbnail)
let uploadTask = Task { @MainActor in
do {
var output = try await load(input: input)
switch input {
case .mastodonAssetUrl:
self.isCaptionEditable = false
self.uploadState = .finish
self.output = output
self.uploadResult = .exists
return
default:
break
}
switch output {
case .image(let data, _):
self.output = output
self.update(uploadState: .compressing)
let compressedOutput = try await compressImage(data: data, sizeLimit: sizeLimit)
output = compressedOutput
case .video(let fileURL, let mimeType):
self.output = output
self.update(uploadState: .compressing)
guard let compressedFileURL = try await compressVideo(url: fileURL, mediaAttachmentSettings: mediaAttachmentSettings) else {
assertionFailure("Unable to compress video")
return
}
output = .video(compressedFileURL, mimeType: mimeType)
try? FileManager.default.removeItem(at: fileURL) // remove old file
}
self.outputSizeInByte = output.asAttachment.sizeInByte.flatMap { Int64($0) } ?? 0
self.output = output
self.update(uploadState: .ready)
self.delegate?.attachmentViewModel(self, uploadStateValueDidChange: self.uploadState)
} catch {
self.error = error
}
} // end Task
self.uploadTask = uploadTask
Task {
await uploadTask.value
}
}
deinit {
os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s", ((#file as NSString).lastPathComponent), #line, #function)
uploadTask?.cancel()
switch output {
case .image:
// FIXME:
break
case .video(let url, _):
try? FileManager.default.removeItem(at: url)
case nil:
break
}
}
}
// calculate the upload speed
// ref: https://stackoverflow.com/a/3841706/3797903
extension AttachmentViewModel {
static var SpeedSmoothingFactor = 0.4
static let remainsTimeFormatter: RelativeDateTimeFormatter = {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter
}()
@objc private func step() {
let uploadProgress = min(progress.fractionCompleted + 0.1, 1) // the progress split into 9:1 blocks (download : waiting)
guard let lastTimestamp = self.lastTimestamp else {
self.lastTimestamp = CACurrentMediaTime()
self.lastUploadSizeInByte = Int64(Double(outputSizeInByte) * uploadProgress)
return
}
let duration = CACurrentMediaTime() - lastTimestamp
guard duration >= 1.0 else { return } // update every 1 sec
let old = self.lastUploadSizeInByte
self.lastUploadSizeInByte = Int64(Double(outputSizeInByte) * uploadProgress)
let newSpeed = self.lastUploadSizeInByte - old
let lastAverageSpeed = self.averageUploadSpeedInByte
let newAverageSpeed = Int64(AttachmentViewModel.SpeedSmoothingFactor * Double(newSpeed) + (1 - AttachmentViewModel.SpeedSmoothingFactor) * Double(lastAverageSpeed))
let remainSizeInByte = Double(outputSizeInByte) * (1 - uploadProgress)
let speed = Double(newAverageSpeed)
if speed != .zero {
// estimate by speed
let uploadRemainTimeInSecond = remainSizeInByte / speed
// estimate by progress 1s for 10%
let remainPercentage = 1 - uploadProgress
let estimateRemainTimeByProgress = remainPercentage / 0.1
// max estimate
var remainTimeInSecond = max(estimateRemainTimeByProgress, uploadRemainTimeInSecond)
// do not increate timer when < 5 sec
if let remainTimeInterval = self.remainTimeInterval, remainTimeInSecond < 5 {
remainTimeInSecond = min(remainTimeInterval, remainTimeInSecond)
self.remainTimeInterval = remainTimeInSecond
} else {
self.remainTimeInterval = remainTimeInSecond
}
let string = AttachmentViewModel.remainsTimeFormatter.localizedString(fromTimeInterval: remainTimeInSecond)
remainTimeLocalizedString = string
// print("remains: \(remainSizeInByte), speed: \(newAverageSpeed), \(string)")
} else {
remainTimeLocalizedString = nil
}
self.lastTimestamp = CACurrentMediaTime()
self.averageUploadSpeedInByte = newAverageSpeed
}
}
extension AttachmentViewModel {
public enum Input: Hashable {
case image(UIImage)
case url(URL)
case mastodonAssetUrl(URL, String)
case pickerResult(PHPickerResult)
case itemProvider(NSItemProvider)
}
public enum Output {
case image(Data, imageKind: ImageKind)
// case gif(Data)
case video(URL, mimeType: String) // assert use file for video only
public enum ImageKind {
case png
case jpg
}
}
public struct SizeLimit {
public let image: Int?
public let video: Int?
public init(
image: Int?,
video: Int?
) {
self.image = image
self.video = video
}
}
public enum AttachmentError: Error, LocalizedError {
case invalidAttachmentType
case attachmentTooLarge
public var errorDescription: String? {
switch self {
case .invalidAttachmentType:
return L10n.Scene.Compose.Attachment.canNotRecognizeThisMediaAttachment
case .attachmentTooLarge:
return L10n.Scene.Compose.Attachment.attachmentTooLarge
}
}
}
}
extension AttachmentViewModel {
public enum Action: Hashable {
case remove
case retry
}
}
extension AttachmentViewModel {
@MainActor
func update(uploadState: UploadState) {
self.uploadState = uploadState
self.delegate?.attachmentViewModel(self, uploadStateValueDidChange: self.uploadState)
}
@MainActor
func update(uploadResult: UploadResult) {
self.uploadResult = uploadResult
}
}