2022-10-31 13:41:19 +01:00
|
|
|
//
|
|
|
|
// AttachmentViewModel.swift
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// Created by MainasuK on 2021/11/19.
|
|
|
|
//
|
|
|
|
|
|
|
|
import os.log
|
|
|
|
import UIKit
|
|
|
|
import Combine
|
|
|
|
import PhotosUI
|
|
|
|
import Kingfisher
|
|
|
|
import MastodonCore
|
2022-11-14 12:27:09 +01:00
|
|
|
import MastodonLocalization
|
2022-11-11 14:28:19 +01:00
|
|
|
import func QuartzCore.CACurrentMediaTime
|
2022-10-31 13:41:19 +01:00
|
|
|
|
2022-11-11 11:10:13 +01:00
|
|
|
public protocol AttachmentViewModelDelegate: AnyObject {
|
|
|
|
func attachmentViewModel(_ viewModel: AttachmentViewModel, uploadStateValueDidChange state: AttachmentViewModel.UploadState)
|
|
|
|
func attachmentViewModel(_ viewModel: AttachmentViewModel, actionButtonDidPressed action: AttachmentViewModel.Action)
|
|
|
|
}
|
|
|
|
|
2022-10-31 13:41:19 +01:00
|
|
|
final public class AttachmentViewModel: NSObject, ObservableObject, Identifiable {
|
|
|
|
|
|
|
|
static let logger = Logger(subsystem: "AttachmentViewModel", category: "ViewModel")
|
2022-11-08 12:40:58 +01:00
|
|
|
let logger = Logger(subsystem: "AttachmentViewModel", category: "ViewModel")
|
2022-10-31 13:41:19 +01:00
|
|
|
|
|
|
|
public let id = UUID()
|
|
|
|
|
|
|
|
var disposeBag = Set<AnyCancellable>()
|
|
|
|
var observations = Set<NSKeyValueObservation>()
|
2022-11-11 11:10:13 +01:00
|
|
|
|
|
|
|
weak var delegate: AttachmentViewModelDelegate?
|
|
|
|
|
|
|
|
let byteCountFormatter: ByteCountFormatter = {
|
|
|
|
let formatter = ByteCountFormatter()
|
|
|
|
formatter.allowsNonnumericFormatting = true
|
|
|
|
formatter.countStyle = .memory
|
|
|
|
return formatter
|
|
|
|
}()
|
2022-11-11 14:28:19 +01:00
|
|
|
|
|
|
|
let percentageFormatter: NumberFormatter = {
|
|
|
|
let formatter = NumberFormatter()
|
|
|
|
formatter.numberStyle = .percent
|
|
|
|
return formatter
|
|
|
|
}()
|
2022-10-31 13:41:19 +01:00
|
|
|
|
|
|
|
// input
|
2022-11-08 12:40:58 +01:00
|
|
|
public let api: APIService
|
2022-11-08 09:39:19 +01:00
|
|
|
public let authContext: AuthContext
|
2022-10-31 13:41:19 +01:00
|
|
|
public let input: Input
|
|
|
|
@Published var caption = ""
|
2022-11-14 12:27:09 +01:00
|
|
|
// @Published var sizeLimit = SizeLimit()
|
2022-11-11 12:02:44 +01:00
|
|
|
|
2022-10-31 13:41:19 +01:00
|
|
|
// output
|
|
|
|
@Published public private(set) var output: Output?
|
|
|
|
@Published public private(set) var thumbnail: UIImage? // original size image thumbnail
|
2022-11-10 11:36:36 +01:00
|
|
|
@Published public private(set) var outputSizeInByte: Int64 = 0
|
2022-11-08 12:40:58 +01:00
|
|
|
|
2022-11-11 11:10:13 +01:00
|
|
|
@Published public private(set) var uploadState: UploadState = .none
|
|
|
|
@Published public private(set) var uploadResult: UploadResult?
|
2022-10-31 13:41:19 +01:00
|
|
|
@Published var error: Error?
|
2022-11-11 14:28:19 +01:00
|
|
|
|
|
|
|
var uploadTask: Task<(), Never>?
|
2022-11-08 12:40:58 +01:00
|
|
|
|
2022-11-11 14:28:19 +01:00
|
|
|
@Published var videoCompressProgress: Double = 0
|
|
|
|
|
2022-10-31 13:41:19 +01:00
|
|
|
let progress = Progress() // upload progress
|
2022-11-10 11:36:36 +01:00
|
|
|
@Published var fractionCompleted: Double = 0
|
|
|
|
|
|
|
|
private var lastTimestamp: TimeInterval?
|
|
|
|
private var lastUploadSizeInByte: Int64 = 0
|
|
|
|
private var averageUploadSpeedInByte: Int64 = 0
|
2022-11-11 11:10:13 +01:00
|
|
|
private var remainTimeInterval: Double?
|
2022-11-10 11:36:36 +01:00
|
|
|
@Published var remainTimeLocalizedString: String?
|
2022-10-31 13:41:19 +01:00
|
|
|
|
2022-11-08 09:39:19 +01:00
|
|
|
public init(
|
2022-11-08 12:40:58 +01:00
|
|
|
api: APIService,
|
2022-11-08 09:39:19 +01:00
|
|
|
authContext: AuthContext,
|
2022-11-11 11:10:13 +01:00
|
|
|
input: Input,
|
|
|
|
delegate: AttachmentViewModelDelegate
|
2022-11-08 09:39:19 +01:00
|
|
|
) {
|
2022-11-08 12:40:58 +01:00
|
|
|
self.api = api
|
2022-11-08 09:39:19 +01:00
|
|
|
self.authContext = authContext
|
2022-10-31 13:41:19 +01:00
|
|
|
self.input = input
|
2022-11-11 11:10:13 +01:00
|
|
|
self.delegate = delegate
|
2022-10-31 13:41:19 +01:00
|
|
|
super.init()
|
|
|
|
// end init
|
2022-11-10 11:36:36 +01:00
|
|
|
|
2022-11-11 14:28:19 +01:00
|
|
|
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)
|
2022-11-08 12:40:58 +01:00
|
|
|
|
|
|
|
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 {
|
2022-11-11 11:10:13 +01:00
|
|
|
self.fractionCompleted = progress.fractionCompleted
|
2022-11-08 12:40:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
.store(in: &observations)
|
2022-10-31 13:41:19 +01:00
|
|
|
|
2022-11-10 11:36:36 +01:00
|
|
|
// 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)
|
2022-10-31 13:41:19 +01:00
|
|
|
|
|
|
|
$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
|
|
|
|
}
|
|
|
|
}
|
2022-11-08 09:39:19 +01:00
|
|
|
.receive(on: DispatchQueue.main)
|
2022-10-31 13:41:19 +01:00
|
|
|
.assign(to: &$thumbnail)
|
2022-11-08 12:40:58 +01:00
|
|
|
|
|
|
|
defer {
|
2022-11-11 14:28:19 +01:00
|
|
|
let uploadTask = Task { @MainActor in
|
2022-11-08 12:40:58 +01:00
|
|
|
do {
|
2022-11-11 12:02:44 +01:00
|
|
|
var output = try await load(input: input)
|
|
|
|
|
|
|
|
switch output {
|
|
|
|
case .video(let fileURL, let mimeType):
|
2022-11-11 14:28:19 +01:00
|
|
|
self.output = output
|
|
|
|
self.update(uploadState: .compressing)
|
2022-11-11 12:02:44 +01:00
|
|
|
let compressedFileURL = try await comporessVideo(url: fileURL)
|
|
|
|
output = .video(compressedFileURL, mimeType: mimeType)
|
|
|
|
try? FileManager.default.removeItem(at: fileURL) // remove old file
|
|
|
|
default:
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2022-11-10 11:36:36 +01:00
|
|
|
self.outputSizeInByte = output.asAttachment.sizeInByte.flatMap { Int64($0) } ?? 0
|
2022-11-11 12:02:44 +01:00
|
|
|
self.output = output
|
|
|
|
|
2022-11-11 11:10:13 +01:00
|
|
|
self.update(uploadState: .ready)
|
|
|
|
self.delegate?.attachmentViewModel(self, uploadStateValueDidChange: self.uploadState)
|
2022-11-08 12:40:58 +01:00
|
|
|
} catch {
|
|
|
|
self.error = error
|
|
|
|
}
|
|
|
|
} // end Task
|
2022-11-11 14:28:19 +01:00
|
|
|
self.uploadTask = uploadTask
|
|
|
|
Task {
|
|
|
|
await uploadTask.value
|
|
|
|
}
|
2022-11-08 12:40:58 +01:00
|
|
|
}
|
2022-10-31 13:41:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
deinit {
|
2022-11-11 14:28:19 +01:00
|
|
|
os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s", ((#file as NSString).lastPathComponent), #line, #function)
|
|
|
|
|
|
|
|
uploadTask?.cancel()
|
2022-11-10 11:36:36 +01:00
|
|
|
|
2022-10-31 13:41:19 +01:00
|
|
|
switch output {
|
|
|
|
case .image:
|
|
|
|
// FIXME:
|
|
|
|
break
|
|
|
|
case .video(let url, _):
|
|
|
|
try? FileManager.default.removeItem(at: url)
|
2022-11-11 11:10:13 +01:00
|
|
|
case nil:
|
2022-10-31 13:41:19 +01:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-10 11:36:36 +01:00
|
|
|
// 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()
|
2022-11-11 11:10:13 +01:00
|
|
|
formatter.unitsStyle = .full
|
2022-11-10 11:36:36 +01:00
|
|
|
return formatter
|
|
|
|
}()
|
|
|
|
|
2022-11-11 14:28:19 +01:00
|
|
|
@objc private func step() {
|
|
|
|
|
|
|
|
let uploadProgress = min(progress.fractionCompleted + 0.1, 1) // the progress split into 9:1 blocks (download : waiting)
|
|
|
|
|
2022-11-10 11:36:36 +01:00
|
|
|
guard let lastTimestamp = self.lastTimestamp else {
|
2022-11-11 14:28:19 +01:00
|
|
|
self.lastTimestamp = CACurrentMediaTime()
|
|
|
|
self.lastUploadSizeInByte = Int64(Double(outputSizeInByte) * uploadProgress)
|
2022-11-10 11:36:36 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-11-11 14:28:19 +01:00
|
|
|
let duration = CACurrentMediaTime() - lastTimestamp
|
2022-11-10 11:36:36 +01:00
|
|
|
guard duration >= 1.0 else { return } // update every 1 sec
|
|
|
|
|
|
|
|
let old = self.lastUploadSizeInByte
|
2022-11-11 14:28:19 +01:00
|
|
|
self.lastUploadSizeInByte = Int64(Double(outputSizeInByte) * uploadProgress)
|
2022-11-10 11:36:36 +01:00
|
|
|
|
|
|
|
let newSpeed = self.lastUploadSizeInByte - old
|
|
|
|
let lastAverageSpeed = self.averageUploadSpeedInByte
|
|
|
|
let newAverageSpeed = Int64(AttachmentViewModel.SpeedSmoothingFactor * Double(newSpeed) + (1 - AttachmentViewModel.SpeedSmoothingFactor) * Double(lastAverageSpeed))
|
|
|
|
|
2022-11-11 14:28:19 +01:00
|
|
|
let remainSizeInByte = Double(outputSizeInByte) * (1 - uploadProgress)
|
2022-11-10 11:36:36 +01:00
|
|
|
|
|
|
|
let speed = Double(newAverageSpeed)
|
|
|
|
if speed != .zero {
|
|
|
|
// estimate by speed
|
|
|
|
let uploadRemainTimeInSecond = remainSizeInByte / speed
|
|
|
|
// estimate by progress 1s for 10%
|
2022-11-11 14:28:19 +01:00
|
|
|
let remainPercentage = 1 - uploadProgress
|
2022-11-10 11:36:36 +01:00
|
|
|
let estimateRemainTimeByProgress = remainPercentage / 0.1
|
|
|
|
// max estimate
|
2022-11-11 11:10:13 +01:00
|
|
|
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
|
|
|
|
}
|
2022-11-10 11:36:36 +01:00
|
|
|
|
|
|
|
let string = AttachmentViewModel.remainsTimeFormatter.localizedString(fromTimeInterval: remainTimeInSecond)
|
|
|
|
remainTimeLocalizedString = string
|
|
|
|
// print("remains: \(remainSizeInByte), speed: \(newAverageSpeed), \(string)")
|
|
|
|
} else {
|
|
|
|
remainTimeLocalizedString = nil
|
|
|
|
}
|
|
|
|
|
2022-11-11 14:28:19 +01:00
|
|
|
self.lastTimestamp = CACurrentMediaTime()
|
2022-11-10 11:36:36 +01:00
|
|
|
self.averageUploadSpeedInByte = newAverageSpeed
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-31 13:41:19 +01:00
|
|
|
extension AttachmentViewModel {
|
|
|
|
public enum Input: Hashable {
|
|
|
|
case image(UIImage)
|
|
|
|
case url(URL)
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-14 12:27:09 +01:00
|
|
|
// not in using
|
2022-10-31 13:41:19 +01:00
|
|
|
public struct SizeLimit {
|
|
|
|
public let image: Int
|
|
|
|
public let gif: Int
|
|
|
|
public let video: Int
|
|
|
|
|
|
|
|
public init(
|
2022-11-14 12:27:09 +01:00
|
|
|
image: Int = 10 * 1024 * 1024, // 10 MiB
|
|
|
|
gif: Int = 40 * 1024 * 1024, // 40 MiB
|
|
|
|
video: Int = 40 * 1024 * 1024 // 40 MiB
|
2022-10-31 13:41:19 +01:00
|
|
|
) {
|
|
|
|
self.image = image
|
|
|
|
self.gif = gif
|
|
|
|
self.video = video
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-08 12:40:58 +01:00
|
|
|
public enum AttachmentError: Error, LocalizedError {
|
2022-10-31 13:41:19 +01:00
|
|
|
case invalidAttachmentType
|
|
|
|
case attachmentTooLarge
|
|
|
|
|
2022-11-08 12:40:58 +01:00
|
|
|
public var errorDescription: String? {
|
|
|
|
switch self {
|
|
|
|
case .invalidAttachmentType:
|
2022-11-14 12:27:09 +01:00
|
|
|
return L10n.Scene.Compose.Attachment.canNotRecognizeThisMediaAttachment
|
2022-11-08 12:40:58 +01:00
|
|
|
case .attachmentTooLarge:
|
2022-11-14 12:27:09 +01:00
|
|
|
return L10n.Scene.Compose.Attachment.attachmentTooLarge
|
2022-10-31 13:41:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2022-11-11 11:10:13 +01:00
|
|
|
extension AttachmentViewModel {
|
|
|
|
public enum Action: Hashable {
|
|
|
|
case remove
|
|
|
|
case retry
|
|
|
|
}
|
|
|
|
}
|
2022-10-31 13:41:19 +01:00
|
|
|
|
2022-11-11 11:10:13 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|