NCMainCommon.swift 74 KB

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