2024-07-11 13:59:24 +00:00
|
|
|
import Combine
|
2024-07-12 11:43:14 +00:00
|
|
|
import Foundation
|
|
|
|
import UIKit
|
2024-07-11 13:59:24 +00:00
|
|
|
|
|
|
|
final class FileMiddleware {
|
2024-07-12 11:43:14 +00:00
|
|
|
static let shared = FileMiddleware()
|
2024-07-11 13:59:24 +00:00
|
|
|
|
|
|
|
func middleware(state _: AppState, action: AppAction) -> AnyPublisher<AppAction, Never> {
|
|
|
|
switch action {
|
2024-07-13 13:38:15 +00:00
|
|
|
case .conversationAction(.messagesUpdated(let messages)):
|
2024-07-13 01:29:46 +00:00
|
|
|
return Future { promise in
|
2024-07-13 13:38:15 +00:00
|
|
|
for message in messages where message.remotePath != nil && message.localPath == nil {
|
2024-07-13 01:29:46 +00:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
// swiftlint:disable:next force_unwrapping
|
2024-07-13 13:38:15 +00:00
|
|
|
store.dispatch(.fileAction(.downloadAttachmentFile(id: message.id, remotePath: message.remotePath!)))
|
2024-07-12 11:43:14 +00:00
|
|
|
}
|
|
|
|
}
|
2024-07-13 01:29:46 +00:00
|
|
|
promise(.success(.empty))
|
|
|
|
}.eraseToAnyPublisher()
|
2024-07-12 11:43:14 +00:00
|
|
|
|
2024-07-13 01:29:46 +00:00
|
|
|
case .fileAction(.downloadAttachmentFile(let id, let remotePath)):
|
|
|
|
return Future { promise in
|
|
|
|
let localUrl = FileProcessing.fileFolder.appendingPathComponent(id).appendingPathExtension(remotePath.pathExtension)
|
|
|
|
DownloadManager.shared.enqueueDownload(from: remotePath, to: localUrl) { error in
|
|
|
|
DispatchQueue.main.async {
|
|
|
|
if let error {
|
|
|
|
store.dispatch(.fileAction(.downloadingAttachmentFileFailed(id: id, reason: error.localizedDescription)))
|
|
|
|
} else {
|
|
|
|
store.dispatch(.fileAction(.attachmentFileDownloaded(id: id, localUrl: localUrl)))
|
2024-07-12 11:43:14 +00:00
|
|
|
}
|
|
|
|
}
|
2024-07-13 01:29:46 +00:00
|
|
|
}
|
|
|
|
promise(.success(.empty))
|
|
|
|
}.eraseToAnyPublisher()
|
2024-07-12 11:43:14 +00:00
|
|
|
|
2024-07-13 01:29:46 +00:00
|
|
|
case .fileAction(.attachmentFileDownloaded(let id, let localUrl)):
|
|
|
|
return Just(.fileAction(.createAttachmentThumbnail(id: id, localUrl: localUrl)))
|
|
|
|
.eraseToAnyPublisher()
|
2024-07-12 11:43:14 +00:00
|
|
|
|
2024-07-13 01:29:46 +00:00
|
|
|
case .fileAction(.createAttachmentThumbnail(let id, let localUrl)):
|
|
|
|
return Future { promise in
|
|
|
|
if let thumbnailUrl = FileProcessing.shared.createThumbnail(id: id, localUrl: localUrl) {
|
|
|
|
promise(.success(.fileAction(.attachmentThumbnailCreated(id: id, thumbnailUrl: thumbnailUrl))))
|
|
|
|
} else {
|
|
|
|
promise(.success(.empty))
|
2024-07-11 13:59:24 +00:00
|
|
|
}
|
|
|
|
}
|
2024-07-13 01:29:46 +00:00
|
|
|
.eraseToAnyPublisher()
|
2024-07-11 13:59:24 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
return Empty().eraseToAnyPublisher()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|