NCMainCommon.swift 74 KB

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