-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathChatUploader.swift
239 lines (206 loc) · 11.4 KB
/
ChatUploader.swift
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
import ChatRepo
import MEGASDKRepo
protocol ChatUploaderProtocol {
func upload(image: UIImage, chatRoomId: UInt64)
func upload(
filepath: String,
appData: String,
chatRoomId: UInt64,
parentNode: MEGANode,
isSourceTemporary: Bool,
delegate: MEGAStartUploadTransferDelegate
)
}
final class ChatUploader: NSObject, ChatUploaderProtocol {
static let sharedInstance = ChatUploader()
private let store = MEGAStore.shareInstance()
private var isDatabaseCleanupTaskCompleted: Bool?
private let uploaderQueue = DispatchQueue(label: "ChatUploaderQueue")
private override init() { super.init() }
@objc func setup() {
isDatabaseCleanupTaskCompleted = false
MEGASdk.shared.add(self)
}
func upload(image: UIImage, chatRoomId: UInt64) {
MyChatFilesFolderNodeAccess.shared.loadNode { myChatFilesFolderNode, error in
guard let myChatFilesFolderNode = myChatFilesFolderNode else {
if let error = error {
MEGALogWarning("Could not load MyChatFiles target folder due to error \(error.localizedDescription)")
}
return
}
if let data = image.jpegData(compressionQuality: CGFloat(0.7)) {
let fileName = "\(NSDate().mnz_formattedDefaultNameForMedia()).jpg"
let tempPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(fileName)
do {
try data.write(to: URL(fileURLWithPath: tempPath), options: .atomic)
var appData = NSString().mnz_appData(toSaveCoordinates: tempPath.mnz_coordinatesOfPhotoOrVideo() ?? "")
appData = ((appData) as NSString).mnz_appDataToAttach(toChatID: chatRoomId, asVoiceClip: false)
ChatUploader.sharedInstance.upload(filepath: tempPath,
appData: appData,
chatRoomId: chatRoomId,
parentNode: myChatFilesFolderNode,
isSourceTemporary: false,
delegate: MEGAStartUploadTransferDelegate(completion: nil))
} catch {
MEGALogDebug("Could not write to file \(tempPath) with error \(error.localizedDescription)")
}
}
}
}
func upload(filepath: String,
appData: String,
chatRoomId: UInt64,
parentNode: MEGANode,
isSourceTemporary: Bool,
delegate: MEGAStartUploadTransferDelegate) {
MEGALogInfo("[ChatUploader] uploading File path \(filepath)")
cleanupDatabaseIfRequired()
guard let context = store.stack.newBackgroundContext() else { return }
context.performAndWait {
MEGALogInfo("[ChatUploader] inserted new entry File path \(filepath)")
// insert into database only if the duplicate path does not exsist - "allowDuplicateFilePath" parameter
self.store.insertChatUploadTransfer(withFilepath: filepath,
chatRoomId: String(chatRoomId),
transferTag: nil,
allowDuplicateFilePath: false,
context: context)
MEGALogInfo("[ChatUploader] SDK upload started for File path \(filepath)")
MEGASdk.shared.startUploadForChat(withLocalPath: filepath,
parent: parentNode,
appData: appData,
isSourceTemporary: isSourceTemporary,
fileName: nil,
delegate: delegate)
}
}
// MARK: - Private
private func cleanupDatabaseIfRequired() {
if let isDatabaseCleanupTaskCompleted = isDatabaseCleanupTaskCompleted,
!isDatabaseCleanupTaskCompleted {
self.isDatabaseCleanupTaskCompleted = true
cleanupDatabase()
}
}
private func cleanupDatabase() {
guard let context = store.stack.newBackgroundContext() else { return }
context.performAndWait {
let transferList = MEGASdk.shared.transfers
MEGALogDebug("[ChatUploader] transfer list count : \(transferList.size)")
let sdkTransfers = (0..<transferList.size).compactMap { transferList.transfer(at: $0) }
self.store.fetchAllChatUploadTransfer(context: context).forEach { transfer in
if transfer.nodeHandle == nil {
MEGALogDebug("[ChatUploader] transfer task not completed \(transfer.index) : \(transfer.filepath)")
let foundTransfers = sdkTransfers.filter({
return $0.path == transfer.filepath
})
if !foundTransfers.isEmpty {
transfer.transferTag = nil
MEGALogDebug("[ChatUploader] transfer tag set to nil at \(transfer.index) : \(transfer.filepath)")
} else {
context.delete(transfer)
MEGALogDebug("[ChatUploader] Deleted the transfer task \(transfer.index) : \(transfer.filepath)")
}
} else {
MEGALogDebug("[ChatUploader] transfer task is already completed \(transfer.index) : \(transfer.filepath)")
}
}
self.store.save(context)
}
}
private func updateDatabase(withChatRoomIdString chatRoomIdString: String, context: NSManagedObjectContext) {
context.performAndWait {
let allTransfers = store.fetchAllChatUploadTransfer(withChatRoomId: chatRoomIdString, context: context)
allTransfers.forEach { transfer in
MEGALogInfo("[ChatUploader] transfer index \(transfer.index) with file path \(transfer.filepath)")
}
let index = allTransfers.firstIndex(where: { $0.nodeHandle == nil })
MEGALogInfo("[ChatUploader] transfer found at index \(index ?? -1)")
if let totalIndexes = (index == nil) ? allTransfers.count : index {
(0..<totalIndexes).forEach { index in
let transfer = allTransfers[index]
if let handle = transfer.nodeHandle,
let nodeHandle = UInt64(handle),
let chatRoomId = UInt64(chatRoomIdString) {
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let requestDelegate = ChatRequestDelegate { _ in
dispatchGroup.leave()
}
if let appData = transfer.appData, appData.contains("attachVoiceClipToChatID") {
MEGAChatSdk.shared.attachVoiceMessage(toChat: chatRoomId, node: nodeHandle, delegate: requestDelegate)
} else {
MEGAChatSdk.shared.attachNode(toChat: chatRoomId, node: nodeHandle, delegate: requestDelegate)
}
MEGALogInfo("[ChatUploader] attachment complete File path \(transfer.filepath)")
context.delete(transfer)
dispatchGroup.wait()
}
}
guard MEGASdk.isLoggedIn else { return }
store.save(context)
}
}
}
}
extension ChatUploader: MEGATransferDelegate {
func onTransferStart(_ api: MEGASdk, transfer: MEGATransfer) {
uploaderQueue.async {
guard transfer.type == .upload,
let chatRoomIdString = transfer.mnz_extractChatIDFromAppData(),
let context = self.store.stack.newBackgroundContext() else {
return
}
self.cleanupDatabaseIfRequired()
context.performAndWait {
let allTransfers = self.store.fetchAllChatUploadTransfer(withChatRoomId: chatRoomIdString, context: context)
if let transferTask = allTransfers.first(
where: { $0.filepath == transfer.path && ($0.transferTag == nil || $0.transferTag == String(transfer.tag))}
) {
transferTask.transferTag = String(transfer.tag)
MEGALogInfo("[ChatUploader] updating existing row for \(transfer.path ?? "no path") with tag \(transfer.tag)")
} else if let transferPath = transfer.path {
self.store.insertChatUploadTransfer(withFilepath: transferPath,
chatRoomId: chatRoomIdString,
transferTag: String(transfer.tag),
allowDuplicateFilePath: true,
context: context)
MEGALogInfo("[ChatUploader] inserting a new row for \(transfer.path ?? "no path") with tag \(transfer.tag)")
}
self.store.save(context)
}
}
}
func onTransferFinish(_ api: MEGASdk, transfer: MEGATransfer, error: MEGAError) {
uploaderQueue.async {
guard
transfer.type == .upload,
let chatRoomIdString = transfer.mnz_extractChatIDFromAppData(),
let context = self.store.stack.newBackgroundContext(),
let transferPath = transfer.path,
let transferAppData = transfer.appData
else {
return
}
if error.type == .apiEExist {
self.store.deleteChatUploadTransfer(withChatRoomId: chatRoomIdString,
transferTag: String(transfer.tag),
context: context)
let fileName = transfer.fileName ?? "no file"
MEGALogInfo("[ChatUploader] transfer has started with exactly the same data (local path and target parent). File: %@", fileName)
return
}
MEGALogInfo("[ChatUploader] upload complete File path \(transferPath)")
transfer.mnz_moveFileToDestinationIfVoiceClipData()
context.performAndWait {
self.store.updateChatUploadTransfer(filepath: transferPath,
chatRoomId: chatRoomIdString,
nodeHandle: String(transfer.nodeHandle),
transferTag: String(transfer.tag),
appData: transferAppData,
context: context)
self.updateDatabase(withChatRoomIdString: chatRoomIdString, context: context)
}
}
}
}