NCMainCommon.swift 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. //
  2. // NCMainCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/07/18.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import TLPhotoPicker
  25. import ZIPFoundation
  26. //MARK: - Main Common
  27. class NCMainCommon: NSObject, PhotoEditorDelegate, NCAudioRecorderViewControllerDelegate, UIDocumentInteractionControllerDelegate {
  28. @objc static let sharedInstance: NCMainCommon = {
  29. let instance = NCMainCommon()
  30. return instance
  31. }()
  32. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. var metadataEditPhoto: tableMetadata?
  34. var docController: UIDocumentInteractionController?
  35. lazy var operationQueueReloadDatasource: OperationQueue = {
  36. let queue = OperationQueue()
  37. queue.name = "Reload main datasource queue"
  38. queue.maxConcurrentOperationCount = 1
  39. return queue
  40. }()
  41. //MARK: -
  42. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  43. if viewController.viewIfLoaded?.window == nil {
  44. return
  45. }
  46. guard let dic = notification.userInfo else {
  47. return
  48. }
  49. let account = dic["account"] as? NSString ?? ""
  50. let ocId = dic["ocId"] as? NSString ?? ""
  51. let serverUrl = dic["serverUrl"] as? String ?? ""
  52. let status = dic["status"] as? Int ?? Int(k_taskIdentifierDone)
  53. let progress = dic["progress"] as? CGFloat ?? 0
  54. let totalBytes = dic["totalBytes"] as? Double ?? 0
  55. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  56. if (account != self.appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  57. return
  58. }
  59. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  60. return
  61. }
  62. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  63. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  64. return
  65. }
  66. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  67. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  68. var image = ""
  69. if status == k_metadataStatusInDownload {
  70. image = "↓"
  71. } else if status == k_metadataStatusInUpload {
  72. image = "↑"
  73. }
  74. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  75. cell.transferButton?.progress = progress
  76. }
  77. }
  78. }
  79. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool, uploadStatusForcedStart: Bool) {
  80. var actionReloadDatasource = k_action_NULL
  81. var metadata = metadata
  82. if metadata.session.count == 0 { return }
  83. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else { return }
  84. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  85. var cancel = false
  86. // DOWNLOAD
  87. if metadata.session.count > 0 && metadata.session.contains("download") {
  88. for task in downloadTasks {
  89. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  90. task.cancel()
  91. cancel = true
  92. }
  93. }
  94. if cancel == false {
  95. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  96. }
  97. actionReloadDatasource = k_action_MOD
  98. }
  99. // UPLOAD
  100. if metadata.session.count > 0 && metadata.session.contains("upload") {
  101. for task in uploadTasks {
  102. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  103. if uploadStatusForcedStart {
  104. metadata.status = Int(k_metadataStatusUploadForcedStart)
  105. metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) ?? metadata
  106. }
  107. task.cancel()
  108. cancel = true
  109. }
  110. }
  111. if cancel == false {
  112. do {
  113. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  114. }
  115. catch { }
  116. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  117. }
  118. actionReloadDatasource = k_action_DEL
  119. }
  120. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  121. self.reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: actionReloadDatasource)
  122. }
  123. }
  124. }
  125. @objc func cancelAllTransfer() {
  126. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  127. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  128. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  129. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d AND status != %d", k_metadataStatusNormal, k_metadataStatusHide), sorted: "fileName", ascending: true) {
  130. for metadata in metadatas {
  131. // Modify
  132. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  133. metadata.session = ""
  134. metadata.sessionSelector = ""
  135. metadata.status = Int(k_metadataStatusNormal)
  136. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  137. }
  138. // Cancel Task
  139. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  140. self.cancelTransferMetadata(metadata, reloadDatasource: false, uploadStatusForcedStart: false)
  141. }
  142. }
  143. }
  144. }
  145. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  146. return
  147. }
  148. }
  149. //MARK: -
  150. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectocId: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool, shares: [tableShare]?, source: UIViewController) {
  151. var image: UIImage?
  152. var isImagePreviewLoaded = false
  153. var tableShare: tableShare?
  154. // Image Preview
  155. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileName)) {
  156. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileName))
  157. isImagePreviewLoaded = true
  158. } else {
  159. if metadata.iconName.count > 0 {
  160. image = UIImage.init(named: metadata.iconName)
  161. } else {
  162. image = UIImage.init(named: "file")
  163. }
  164. }
  165. // Share
  166. if shares != nil {
  167. for share in shares! {
  168. if share.fileName == metadata.fileName {
  169. tableShare = share
  170. break
  171. }
  172. }
  173. }
  174. // Download preview
  175. if downloadThumbnail {
  176. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: collectionView, indexPath: indexPath)
  177. }
  178. var isShare = false
  179. var isMounted = false
  180. if metadataFolder != nil {
  181. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  182. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  183. }
  184. if cell is NCListCell {
  185. let cell = cell as! NCListCell
  186. cell.delegate = source as? NCListCellDelegate
  187. cell.objectId = metadata.ocId
  188. cell.indexPath = indexPath
  189. cell.labelTitle.text = metadata.fileNameView
  190. cell.imageStatus.image = nil
  191. cell.imageLocal.image = nil
  192. cell.imageFavorite.image = nil
  193. cell.shared.image = nil
  194. if metadata.directory {
  195. if metadata.e2eEncrypted {
  196. image = UIImage.init(named: "folderEncrypted")
  197. } else if isShare {
  198. image = UIImage.init(named: "folder_shared_with_me")
  199. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  200. image = UIImage.init(named: "folder_shared_with_me")
  201. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  202. image = UIImage.init(named: "folder_public")
  203. } else if metadata.mountType == "group" {
  204. image = UIImage.init(named: "folder_group")
  205. } else if isMounted {
  206. image = UIImage.init(named: "folder_external")
  207. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  208. image = UIImage.init(named: "folderAutomaticUpload")
  209. } else {
  210. image = UIImage.init(named: "folder")
  211. }
  212. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  213. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  214. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  215. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  216. // Status image: passcode
  217. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  218. cell.imageStatus.image = UIImage.init(named: "passcode")
  219. }
  220. // Local image: offline
  221. if tableDirectory != nil && tableDirectory!.offline {
  222. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  223. }
  224. } else {
  225. cell.imageItem.image = image
  226. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  227. // image Local
  228. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  229. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  230. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  231. else { cell.imageLocal.image = UIImage.init(named: "local") }
  232. }
  233. }
  234. // image Favorite
  235. if metadata.favorite {
  236. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  237. }
  238. // Share image
  239. if (isShare) {
  240. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: .black)
  241. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  242. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: .black)
  243. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  244. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: .black)
  245. } else {
  246. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.graySoft)
  247. }
  248. if metadata.ownerId != appDelegate.activeUserID {
  249. // Load avatar
  250. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  251. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  252. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  253. cell.shared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  254. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  255. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  256. } else {
  257. let url = appDelegate.activeUrl + k_avatar + metadata.ownerId + "/" + k_avatar_size
  258. let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
  259. OCNetworking.sharedManager()?.downloadContents(ofUrl: encodedString, completion: { (data, message, errorCode) in
  260. if errorCode == 0 {
  261. do {
  262. try data!.write(to: NSURL(fileURLWithPath: fileNameSource) as URL, options: .atomic)
  263. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  264. } catch { }
  265. }
  266. })
  267. }
  268. }
  269. if isEditMode {
  270. cell.imageItemLeftConstraint.constant = 45
  271. cell.imageSelect.isHidden = false
  272. if selectocId.contains(metadata.ocId) {
  273. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  274. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  275. } else {
  276. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  277. cell.backgroundView = nil
  278. }
  279. } else {
  280. cell.imageItemLeftConstraint.constant = 10
  281. cell.imageSelect.isHidden = true
  282. cell.backgroundView = nil
  283. }
  284. // Remove last separator
  285. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  286. cell.separator.isHidden = true
  287. } else {
  288. cell.separator.isHidden = false
  289. }
  290. } else if cell is NCGridCell {
  291. let cell = cell as! NCGridCell
  292. cell.delegate = source as? NCGridCellDelegate
  293. cell.objectId = metadata.ocId
  294. cell.indexPath = indexPath
  295. cell.labelTitle.text = metadata.fileNameView
  296. cell.imageStatus.image = nil
  297. cell.imageLocal.image = nil
  298. cell.imageFavorite.image = nil
  299. if metadata.directory {
  300. if metadata.e2eEncrypted {
  301. image = UIImage.init(named: "folderEncrypted")
  302. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  303. image = UIImage.init(named: "folderAutomaticUpload")
  304. } else if isShare {
  305. image = UIImage.init(named: "folder_shared_with_me")
  306. } else if isMounted {
  307. image = UIImage.init(named: "folder_external")
  308. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  309. image = UIImage.init(named: "folder_shared_with_me")
  310. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  311. image = UIImage.init(named: "folder_public")
  312. } else {
  313. image = UIImage.init(named: "folder")
  314. }
  315. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  316. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  317. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  318. // Status image: passcode
  319. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  320. cell.imageStatus.image = UIImage.init(named: "passcode")
  321. }
  322. // Local image: offline
  323. if tableDirectory != nil && tableDirectory!.offline {
  324. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  325. }
  326. } else {
  327. cell.imageItem.image = image
  328. if isImagePreviewLoaded == false {
  329. let width = cell.imageItem.image!.size.width * 2
  330. cell.imageItem.image = NCUtility.sharedInstance.resizeImage(image: image!, newWidth: width)
  331. }
  332. // image Local
  333. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  334. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  335. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  336. else { cell.imageLocal.image = UIImage.init(named: "local") }
  337. }
  338. }
  339. // image Favorite
  340. if metadata.favorite {
  341. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  342. }
  343. if isEditMode {
  344. cell.imageSelect.isHidden = false
  345. if selectocId.contains(metadata.ocId) {
  346. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  347. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  348. } else {
  349. cell.imageSelect.isHidden = true
  350. cell.backgroundView = nil
  351. }
  352. } else {
  353. cell.imageSelect.isHidden = true
  354. cell.backgroundView = nil
  355. }
  356. } else if cell is NCGridMediaCell {
  357. let cell = cell as! NCGridMediaCell
  358. cell.imageStatus.image = nil
  359. cell.imageLocal.image = nil
  360. cell.imageFavorite.image = nil
  361. cell.imageItem.image = image
  362. // image Local
  363. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  364. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  365. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  366. else { cell.imageLocal.image = UIImage.init(named: "local") }
  367. }
  368. // image Favorite
  369. if metadata.favorite {
  370. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  371. }
  372. if isEditMode {
  373. cell.imageSelect.isHidden = false
  374. if selectocId.contains(metadata.ocId) {
  375. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  376. cell.imageVisualEffect.isHidden = false
  377. cell.imageVisualEffect.alpha = 0.4
  378. } else {
  379. cell.imageSelect.isHidden = true
  380. cell.imageVisualEffect.isHidden = true
  381. }
  382. } else {
  383. cell.imageSelect.isHidden = true
  384. cell.imageVisualEffect.isHidden = true
  385. }
  386. }
  387. }
  388. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?) -> UITableViewCell {
  389. var image: UIImage?
  390. // Create File System
  391. if metadata.directory {
  392. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  393. } else {
  394. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  395. }
  396. // CCCell
  397. if metadata.status == k_metadataStatusNormal {
  398. // NORMAL
  399. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  400. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  401. cell.accessoryType = UITableViewCell.AccessoryType.none
  402. cell.file.image = nil
  403. cell.status.image = nil
  404. cell.favorite.image = nil
  405. cell.shared.image = nil
  406. cell.local.image = nil
  407. cell.comment.image = nil
  408. cell.shared.isUserInteractionEnabled = false
  409. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  410. // change color selection
  411. let selectionColor = UIView()
  412. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  413. cell.selectedBackgroundView = selectionColor
  414. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  415. cell.labelTitle.textColor = UIColor.black
  416. cell.labelTitle.text = metadata.fileNameView
  417. // Download preview
  418. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  419. // Share
  420. var isShare = false
  421. var isMounted = false
  422. if metadataFolder != nil {
  423. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  424. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  425. }
  426. if metadata.directory {
  427. // lable Info
  428. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  429. // File Image & Image Title Segue
  430. if metadata.e2eEncrypted {
  431. image = UIImage.init(named: "folderEncrypted")
  432. } else if isShare {
  433. image = UIImage.init(named: "folder_shared_with_me")
  434. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  435. image = UIImage.init(named: "folder_shared_with_me")
  436. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  437. image = UIImage.init(named: "folder_public")
  438. } else if metadata.mountType == "group" {
  439. image = UIImage.init(named: "folder_group")
  440. } else if isMounted {
  441. image = UIImage.init(named: "folder_external")
  442. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  443. image = UIImage.init(named: "folderAutomaticUpload")
  444. } else {
  445. image = UIImage.init(named: "folder")
  446. }
  447. cell.file.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  448. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  449. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  450. // Local image: offline
  451. if tableDirectory != nil && tableDirectory!.offline {
  452. cell.local.image = UIImage.init(named: "offlineFlag")
  453. }
  454. // Status image: passcode
  455. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  456. cell.status.image = UIImage.init(named: "passcode")
  457. }
  458. } else {
  459. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  460. // Lable Info
  461. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  462. // File Image
  463. if iconFileExists {
  464. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  465. } else {
  466. if metadata.iconName.count > 0 {
  467. cell.file.image = UIImage.init(named: metadata.iconName)
  468. } else {
  469. cell.file.image = UIImage.init(named: "file")
  470. }
  471. }
  472. // Local Image - Offline
  473. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  474. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  475. if tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  476. else { cell.local.image = UIImage.init(named: "local") }
  477. }
  478. // Status image: encrypted
  479. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  480. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  481. cell.status.image = UIImage.init(named: "encrypted")
  482. }
  483. }
  484. //
  485. // File & Directory
  486. //
  487. // Favorite
  488. if metadata.favorite {
  489. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  490. }
  491. // Share image
  492. if (isShare) {
  493. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: .black)
  494. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  495. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: .black)
  496. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  497. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: .black)
  498. } else {
  499. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.graySoft)
  500. }
  501. if metadata.ownerId != appDelegate.activeUserID {
  502. // Load avatar
  503. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  504. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  505. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  506. cell.shared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  507. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  508. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  509. } else {
  510. let url = appDelegate.activeUrl + k_avatar + metadata.ownerId + "/" + k_avatar_size
  511. let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
  512. OCNetworking.sharedManager()?.downloadContents(ofUrl: encodedString, completion: { (data, message, errorCode) in
  513. if errorCode == 0 {
  514. do {
  515. try data!.write(to: NSURL(fileURLWithPath: fileNameSource) as URL, options: .atomic)
  516. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  517. } catch { }
  518. }
  519. })
  520. }
  521. }
  522. // Comment
  523. if metadata.commentsUnread {
  524. cell.comment.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  525. cell.labelTitleTrailingConstraint.constant = 160
  526. } else {
  527. cell.labelTitleTrailingConstraint.constant = 110
  528. }
  529. // More Image
  530. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 1, color: NCBrandColor.sharedInstance.optionItem)
  531. return cell
  532. } else {
  533. // TRASNFER
  534. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  535. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  536. cell.accessoryType = UITableViewCell.AccessoryType.none
  537. cell.file.image = nil
  538. cell.status.image = nil
  539. cell.user.image = nil
  540. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  541. cell.labelTitle.textColor = UIColor.black
  542. cell.labelTitle.text = metadata.fileNameView
  543. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  544. var progress: CGFloat = 0.0
  545. var totalBytes: Double = 0.0
  546. //var totalBytesExpected : Double = 0
  547. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  548. if progressArray != nil && progressArray?.count == 3 {
  549. progress = progressArray?.object(at: 0) as! CGFloat
  550. totalBytes = progressArray?.object(at: 1) as! Double
  551. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  552. }
  553. // Write status on Label Info
  554. switch metadata.status {
  555. case Int(k_metadataStatusWaitDownload):
  556. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  557. progress = 0.0
  558. break
  559. case Int(k_metadataStatusInDownload):
  560. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  561. progress = 0.0
  562. break
  563. case Int(k_metadataStatusDownloading):
  564. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  565. break
  566. case Int(k_metadataStatusWaitUpload):
  567. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  568. progress = 0.0
  569. break
  570. case Int(k_metadataStatusInUpload):
  571. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  572. progress = 0.0
  573. break
  574. case Int(k_metadataStatusUploading):
  575. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  576. break
  577. default:
  578. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  579. progress = 0.0
  580. }
  581. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  582. if iconFileExists {
  583. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  584. } else {
  585. if metadata.iconName.count > 0 {
  586. cell.file.image = UIImage.init(named: metadata.iconName)
  587. } else {
  588. cell.file.image = UIImage.init(named: "file")
  589. }
  590. }
  591. // Session Upload Extension
  592. if metadata.session == k_upload_session_extension {
  593. cell.labelTitle.isEnabled = false
  594. cell.labelInfoFile.isEnabled = false
  595. } else {
  596. cell.labelTitle.isEnabled = true
  597. cell.labelInfoFile.isEnabled = true
  598. }
  599. // downloadFile
  600. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  601. //
  602. }
  603. // downloadFile Error
  604. if metadata.status == k_metadataStatusDownloadError {
  605. cell.status.image = UIImage.init(named: "statuserror")
  606. if metadata.sessionError.count == 0 {
  607. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  608. } else {
  609. cell.labelInfoFile.text = metadata.sessionError
  610. }
  611. }
  612. // uploadFile
  613. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  614. if (!iconFileExists) {
  615. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  616. }
  617. cell.labelTitle.isEnabled = false
  618. }
  619. // uploadFileError
  620. if metadata.status == k_metadataStatusUploadError {
  621. cell.labelTitle.isEnabled = false
  622. cell.status.image = UIImage.init(named: "statuserror")
  623. if !iconFileExists {
  624. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  625. }
  626. if metadata.sessionError.count == 0 {
  627. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  628. } else {
  629. cell.labelInfoFile.text = metadata.sessionError
  630. }
  631. }
  632. // Progress
  633. cell.transferButton.progress = progress
  634. // User
  635. if metadata.account != appDelegate.activeAccount {
  636. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  637. if tableAccount != nil {
  638. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  639. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  640. if avatar != nil {
  641. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  642. let imageSize = avatarImageView?.bounds.size
  643. UIGraphicsBeginImageContext(imageSize!)
  644. let context = UIGraphicsGetCurrentContext()
  645. avatarImageView?.layer.render(in: context!)
  646. avatar = UIGraphicsGetImageFromCurrentImageContext()
  647. UIGraphicsEndImageContext()
  648. cell.user.image = avatar
  649. }
  650. }
  651. }
  652. return cell
  653. }
  654. }
  655. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  656. guard let indexPath = indexPath else {
  657. return nil
  658. }
  659. guard let sectionDataSource = sectionDataSource else {
  660. return nil
  661. }
  662. let section = indexPath.section + 1
  663. let row = indexPath.row + 1
  664. let totSections = sectionDataSource.sections.count
  665. if totSections < section || section > totSections {
  666. return nil
  667. }
  668. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  669. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  670. return nil
  671. }
  672. let totRows = filesID.count
  673. if totRows < row || row > totRows {
  674. return nil
  675. }
  676. let ocId = filesID.object(at: indexPath.row)
  677. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  678. return metadata
  679. }
  680. @objc func reloadDatasource(ServerUrl: String?, ocId: String?, action: Int32) {
  681. if operationQueueReloadDatasource.operationCount > 0 {
  682. return
  683. }
  684. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  685. self.operationQueueReloadDatasource.addOperation {
  686. DispatchQueue.main.async {
  687. self.appDelegate.activeMain.reloadDatasource(ServerUrl, ocId: ocId, action: Int(action))
  688. }
  689. }
  690. }
  691. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  692. self.operationQueueReloadDatasource.addOperation {
  693. DispatchQueue.main.async {
  694. self.appDelegate.activeFavorites.reloadDatasource(ocId, action: Int(action))
  695. }
  696. }
  697. }
  698. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  699. self.operationQueueReloadDatasource.addOperation {
  700. DispatchQueue.main.async {
  701. self.appDelegate.activeTransfers.reloadDatasource(ocId, action: Int(action))
  702. }
  703. }
  704. }
  705. }
  706. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  707. if view is UICollectionView {
  708. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  709. }
  710. if view is UITableView {
  711. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  712. }
  713. return true
  714. }
  715. //MARK: -
  716. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderocId: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  717. var copyMetadatas = [tableMetadata]()
  718. for metadata in metadatas {
  719. copyMetadatas.append(tableMetadata.init(value: metadata))
  720. }
  721. if e2ee {
  722. DispatchQueue.global().async {
  723. let error = NCNetworkingEndToEnd.sharedManager().lockFolderEncrypted(onServerUrl: serverUrl, ocId: folderocId, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl)
  724. DispatchQueue.main.async {
  725. if error == nil {
  726. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  727. } else {
  728. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  729. return
  730. }
  731. }
  732. }
  733. } else {
  734. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  735. }
  736. }
  737. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  738. var count: Int = 0
  739. var completionErrorCode: Int = 0
  740. var completionMessage = ""
  741. for metadata in metadatas {
  742. self.appDelegate.filterocId.add(metadata.ocId)
  743. let path = metadata.serverUrl + "/" + metadata.fileName
  744. OCNetworking.sharedManager().deleteFileOrFolder(withAccount: appDelegate.activeAccount, path: path, completion: { (account, message, errorCode) in
  745. if account == self.appDelegate.activeAccount {
  746. count += 1
  747. if errorCode == 0 || errorCode == kOCErrorServerPathNotFound {
  748. do {
  749. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  750. } catch { }
  751. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  752. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  753. if metadata.directory {
  754. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName), account: metadata.account)
  755. }
  756. if (e2ee) {
  757. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  758. }
  759. self.appDelegate.filterocId.remove(metadata.ocId)
  760. } else {
  761. completionErrorCode = errorCode
  762. completionMessage = ""
  763. if message != nil {
  764. completionMessage = message!
  765. }
  766. self.appDelegate.filterocId.remove(metadata.ocId)
  767. }
  768. if count == metadatas.count {
  769. if e2ee {
  770. DispatchQueue.global().async {
  771. NCNetworkingEndToEnd.sharedManager().rebuildAndSendMetadata(onServerUrl: serverUrl, account: self.appDelegate.activeAccount, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl)
  772. DispatchQueue.main.async {
  773. completion(completionErrorCode, completionMessage)
  774. }
  775. }
  776. } else {
  777. completion(completionErrorCode, completionMessage)
  778. }
  779. }
  780. }
  781. })
  782. }
  783. self.reloadDatasource(ServerUrl: serverUrl, ocId: nil, action: k_action_NULL)
  784. }
  785. @objc func editPhoto(_ metadata: tableMetadata, viewController: UIViewController) {
  786. guard let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  787. return
  788. }
  789. guard let image = UIImage(contentsOfFile: path) else {
  790. return
  791. }
  792. self.metadataEditPhoto = metadata
  793. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  794. photoEditor.image = image
  795. photoEditor.photoEditorDelegate = self
  796. photoEditor.hiddenControls = [.save, .share, .sticker]
  797. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  798. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  799. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  800. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  801. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  802. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  803. viewController.present(photoEditor, animated: true, completion: nil)
  804. }
  805. func doneEditing(image: UIImage) {
  806. guard let metadata = self.metadataEditPhoto else {
  807. return
  808. }
  809. guard let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  810. return
  811. }
  812. guard let filetype = NCUtility.sharedInstance.isEditImage(metadata.fileNameView as NSString) else {
  813. return
  814. }
  815. if filetype == "PNG" {
  816. do {
  817. try image.pngData()?.write(to: NSURL(fileURLWithPath:path) as URL, options: .atomic)
  818. } catch { return }
  819. } else if filetype == "JPG" {
  820. let imageData = image.jpegData(compressionQuality: 1)
  821. do {
  822. try imageData?.write(to: NSURL(fileURLWithPath:path) as URL)
  823. } catch { return }
  824. }
  825. // write icon
  826. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, extension: filetype, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  827. // upload
  828. metadata.session = k_upload_session
  829. metadata.sessionSelector = selectorUploadFile
  830. metadata.status = Int(k_metadataStatusWaitUpload)
  831. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  832. }
  833. func canceledEditing() {
  834. print("Canceled")
  835. }
  836. //MARK: - OpenIn
  837. @objc func downloadOpenIn(metadata: tableMetadata) {
  838. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  839. openIn(metadata: metadata)
  840. } else {
  841. metadata.session = k_download_session
  842. metadata.sessionError = ""
  843. metadata.sessionSelector = selectorOpenIn
  844. metadata.status = Int(k_metadataStatusWaitDownload)
  845. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  846. reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: k_action_MOD)
  847. }
  848. }
  849. func openIn(metadata: tableMetadata) {
  850. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) as URL)
  851. docController?.delegate = self
  852. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController else {
  853. return
  854. }
  855. guard let view = splitViewController.viewControllers.first?.view else {
  856. return
  857. }
  858. guard let frame = splitViewController.viewControllers.first?.view.frame else {
  859. return
  860. }
  861. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  862. }
  863. //MARK: - OpenShare
  864. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  865. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  866. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  867. shareViewController.metadata = metadata
  868. shareViewController.indexPage = indexPage
  869. shareNavigationController.modalPresentationStyle = .formSheet
  870. ViewController.present(shareNavigationController, animated: true, completion: nil)
  871. }
  872. //MARK: - NCAudioRecorder
  873. func startAudioRecorder() {
  874. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  875. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  876. viewController.delegate = self
  877. viewController.createRecorder(fileName: fileName)
  878. viewController.modalTransitionStyle = .crossDissolve
  879. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  880. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  881. }
  882. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  883. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  884. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  885. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  886. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  887. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  888. }
  889. }
  890. //MARK: - Main TabBarController
  891. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  892. override func viewDidLoad() {
  893. super.viewDidLoad()
  894. delegate = self
  895. }
  896. //Delegate methods
  897. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  898. let tabViewControllers = tabBarController.viewControllers!
  899. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  900. if let vc = viewController as? UINavigationController {
  901. vc.popToRootViewController(animated: true);
  902. }
  903. return false
  904. }
  905. animateToTab(toIndex: toIndex)
  906. return true
  907. }
  908. func animateToTab(toIndex: Int) {
  909. let tabViewControllers = viewControllers!
  910. let fromView = selectedViewController!.view!
  911. let toView = tabViewControllers[toIndex].view!
  912. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  913. guard fromIndex != toIndex else {return}
  914. // Add the toView to the tab bar view
  915. fromView.superview?.addSubview(toView)
  916. fromView.superview?.backgroundColor = UIColor.white
  917. // Position toView off screen (to the left/right of fromView)
  918. let screenWidth = UIScreen.main.bounds.size.width;
  919. let scrollRight = toIndex > fromIndex!;
  920. let offset = (scrollRight ? screenWidth : -screenWidth)
  921. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  922. // Disable interaction during animation
  923. view.isUserInteractionEnabled = false
  924. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  925. // Slide the views by -offset
  926. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  927. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  928. }, completion: { finished in
  929. // Remove the old view from the tabbar view.
  930. fromView.removeFromSuperview()
  931. self.selectedIndex = toIndex
  932. self.view.isUserInteractionEnabled = true
  933. })
  934. }
  935. }
  936. //
  937. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  938. //
  939. extension UITabBar {
  940. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  941. // the Master view controller shows the UITabBarItem icon next to the text
  942. override open var traitCollection: UITraitCollection {
  943. if UIDevice.current.userInterfaceIdiom == .pad {
  944. return UITraitCollection(horizontalSizeClass: .compact)
  945. }
  946. return super.traitCollection
  947. }
  948. }
  949. //MARK: - Networking Main
  950. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  951. @objc static let sharedInstance: NCNetworkingMain = {
  952. let instance = NCNetworkingMain()
  953. return instance
  954. }()
  955. lazy var operationQueueNetworkingMain: OperationQueue = {
  956. let queue = OperationQueue()
  957. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  958. queue.maxConcurrentOperationCount = 1
  959. return queue
  960. }()
  961. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  962. // DOWNLOAD
  963. func downloadStart(_ ocId: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  964. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  965. appDelegate.updateApplicationIconBadgeNumber()
  966. }
  967. func downloadFileSuccessFailure(_ fileName: String!, ocId: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  968. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) else {
  969. return
  970. }
  971. if metadata.account != appDelegate.activeAccount {
  972. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  973. return
  974. }
  975. if errorCode == 0 {
  976. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  977. // Synchronized
  978. if selector == selectorDownloadSynchronize {
  979. appDelegate.updateApplicationIconBadgeNumber()
  980. appDelegate.startLoadAutoDownloadUpload()
  981. return
  982. }
  983. // Modify Photo
  984. if selector == selectorDownloadEditPhoto {
  985. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  986. return
  987. }
  988. // open View File
  989. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  990. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  991. if uti == nil {
  992. uti = ""
  993. } else if uti!.contains("opendocument") && !NCUtility.sharedInstance.isRichDocument(metadata) {
  994. metadata.typeFile = k_metadataTypeFile_unknown
  995. }
  996. if metadata.typeFile == k_metadataTypeFile_imagemeter {
  997. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  998. let destination = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  999. try? FileManager().unzipItem(at: source, to: destination)
  1000. let bundleDirectory = IMImagemeter.sharedInstance.getBundleDirectory(metadata: metadata)
  1001. if bundleDirectory.error {
  1002. appDelegate.messageNotification("_error_", description: "Bundle imagemeter error. 🤷‍♂️", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  1003. return
  1004. }
  1005. if let fileHandle = FileHandle(forReadingAtPath: bundleDirectory.immPath) {
  1006. let dataFormat = fileHandle.readData(ofLength: 1)
  1007. if dataFormat.starts(with: [0x01]) {
  1008. appDelegate.messageNotification("_error_", description: "File format binary error, library imagemeter not present. 🤷‍♂️", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  1009. return;
  1010. }
  1011. let dataZip = fileHandle.readData(ofLength: 4)
  1012. if dataZip.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
  1013. try? FileManager().unzipItem(at: NSURL(fileURLWithPath: bundleDirectory.immPath) as URL, to: NSURL(fileURLWithPath: bundleDirectory.bundleDirectory) as URL)
  1014. }
  1015. fileHandle.closeFile()
  1016. }
  1017. }
  1018. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  1019. NCMainCommon.sharedInstance.openIn(metadata: metadata)
  1020. } else {
  1021. if appDelegate.activeMain.view.window != nil {
  1022. appDelegate.activeMain.shouldPerformSegue(metadata)
  1023. }
  1024. if appDelegate.activeFavorites.view.window != nil {
  1025. appDelegate.activeFavorites.shouldPerformSegue(metadata)
  1026. }
  1027. }
  1028. }
  1029. // Open in...
  1030. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  1031. NCMainCommon.sharedInstance.openIn(metadata: metadata)
  1032. }
  1033. // Save to Photo Album
  1034. if selector == selectorSave {
  1035. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  1036. }
  1037. // Copy File
  1038. if selector == selectorLoadCopy {
  1039. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  1040. }
  1041. // Set as available offline
  1042. if selector == selectorLoadOffline {
  1043. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, offline: true)
  1044. }
  1045. //selectorLoadViewImage
  1046. if selector == selectorLoadViewImage {
  1047. if appDelegate.activeDetail != nil {
  1048. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  1049. }
  1050. }
  1051. appDelegate.startLoadAutoDownloadUpload()
  1052. } else {
  1053. // File do not exists on server, remove in local
  1054. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  1055. do {
  1056. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  1057. } catch { }
  1058. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1059. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1060. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_DEL))
  1061. }
  1062. if selector == selectorLoadViewImage {
  1063. if appDelegate.activeDetail.view.window != nil {
  1064. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  1065. }
  1066. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1067. }
  1068. }
  1069. appDelegate.startLoadAutoDownloadUpload()
  1070. }
  1071. // UPLOAD
  1072. func uploadStart(_ ocId: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  1073. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1074. appDelegate.updateApplicationIconBadgeNumber()
  1075. }
  1076. func uploadFileSuccessFailure(_ fileName: String!, ocId: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  1077. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) else {
  1078. return
  1079. }
  1080. if metadata.account != appDelegate.activeAccount {
  1081. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1082. return
  1083. }
  1084. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1085. if errorCode == 0 {
  1086. appDelegate.startLoadAutoDownloadUpload()
  1087. } else {
  1088. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  1089. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  1090. }
  1091. }
  1092. }
  1093. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  1094. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  1095. }
  1096. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  1097. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  1098. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  1099. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  1100. OCNetworking.sharedManager().downloadPreview(withAccount: metadata.account, metadata: metadata, withWidth: width, andHeight: height, completion: { (account, image, message, errorCode) in
  1101. if errorCode == 0 && account == self.appDelegate.activeAccount && !metadata.isInvalidated && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) {
  1102. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1103. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  1104. if cell is NCListCell {
  1105. (cell as! NCListCell).imageItem.image = image
  1106. } else if cell is NCGridCell {
  1107. (cell as! NCGridCell).imageItem.image = image
  1108. } else if cell is NCGridMediaCell {
  1109. (cell as! NCGridMediaCell).imageItem.image = image
  1110. }
  1111. }
  1112. }
  1113. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1114. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1115. if cell is CCCellMainTransfer {
  1116. (cell as! CCCellMainTransfer).file.image = image
  1117. } else if cell is CCCellMain {
  1118. (cell as! CCCellMain).file.image = image
  1119. }
  1120. }
  1121. }
  1122. }
  1123. return closure()
  1124. })
  1125. }
  1126. return closure()
  1127. }
  1128. }
  1129. //MARK: - Operation Networking Main
  1130. class NCOperationNetworkingMain: Operation {
  1131. private var _executing : Bool = false
  1132. override var isExecuting : Bool {
  1133. get { return _executing }
  1134. set {
  1135. guard _executing != newValue else { return }
  1136. willChangeValue(forKey: "isExecuting")
  1137. _executing = newValue
  1138. didChangeValue(forKey: "isExecuting")
  1139. }
  1140. }
  1141. private var _finished : Bool = false
  1142. override var isFinished : Bool {
  1143. get { return _finished }
  1144. set {
  1145. guard _finished != newValue else { return }
  1146. willChangeValue(forKey: "isFinished")
  1147. _finished = newValue
  1148. didChangeValue(forKey: "isFinished")
  1149. }
  1150. }
  1151. private var metadata: tableMetadata?
  1152. private var view: Any?
  1153. private var indexPath: IndexPath?
  1154. private var networkingFunc: String = ""
  1155. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  1156. super.init()
  1157. if metadata != nil { self.metadata = metadata! }
  1158. if view != nil { self.view = view! }
  1159. if indexPath != nil { self.indexPath = indexPath! }
  1160. self.networkingFunc = networkingFunc
  1161. }
  1162. override func start() {
  1163. if !Thread.isMainThread {
  1164. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  1165. } else {
  1166. isExecuting = true
  1167. if isCancelled {
  1168. finish()
  1169. } else {
  1170. poolNetworking()
  1171. }
  1172. }
  1173. }
  1174. func finish() {
  1175. isExecuting = false
  1176. isFinished = true
  1177. }
  1178. override func cancel() {
  1179. super.cancel()
  1180. if isExecuting {
  1181. complete()
  1182. }
  1183. }
  1184. func complete() {
  1185. finish()
  1186. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  1187. }
  1188. func poolNetworking() {
  1189. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  1190. switch networkingFunc {
  1191. case "downloadThumbnail":
  1192. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  1193. self.complete()
  1194. }
  1195. default:
  1196. print("error")
  1197. }
  1198. }
  1199. }
  1200. //MARK: - Function Main
  1201. class NCFunctionMain: NSObject {
  1202. @objc static let sharedInstance: NCFunctionMain = {
  1203. let instance = NCFunctionMain()
  1204. return instance
  1205. }()
  1206. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1207. @objc func synchronizeOffline() {
  1208. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1209. if (directories != nil) {
  1210. for directory: tableDirectory in directories! {
  1211. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  1212. }
  1213. }
  1214. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1215. if (files != nil) {
  1216. for file: tableLocalFile in files! {
  1217. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", file.ocId)) else {
  1218. continue
  1219. }
  1220. CCSynchronize.shared()?.readFile(metadata.ocId, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1221. }
  1222. }
  1223. }
  1224. }