NCMainCommon.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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 <m.faggiana@twsweb.it>
  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. class NCMainCommon: NSObject {
  25. @objc static let sharedInstance: NCMainCommon = {
  26. let instance = NCMainCommon()
  27. return instance
  28. }()
  29. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. //MARK: -
  31. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceFileIDIndexPath: NSDictionary, tableView: UITableView) {
  32. guard let dic = notification.userInfo else {
  33. return
  34. }
  35. let fileID = dic["fileID"] as! NSString
  36. _ = dic["serverUrl"] as! NSString
  37. let status = dic["status"] as! Int
  38. let progress = dic["progress"] as! CGFloat
  39. let totalBytes = dic["totalBytes"] as! Double
  40. let totalBytesExpected = dic["totalBytesExpected"] as! Double
  41. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: fileID)
  42. guard let indexPath = sectionDataSourceFileIDIndexPath.object(forKey: fileID) else {
  43. return
  44. }
  45. if isValidIndexPath(indexPath as! IndexPath, tableView: tableView) {
  46. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  47. var image = ""
  48. if status == k_metadataStatusInDownload {
  49. image = "↓"
  50. } else if status == k_metadataStatusInUpload {
  51. image = "↑"
  52. }
  53. cell.labelInfoFile.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  54. cell.transferButton.progress = progress
  55. }
  56. }
  57. }
  58. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool) {
  59. var actionReloadDatasource = k_action_NULL
  60. if metadata.session.count == 0 {
  61. return
  62. }
  63. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else {
  64. return
  65. }
  66. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  67. return
  68. }
  69. // SESSION EXTENSION
  70. if metadata.session == k_download_session_extension || metadata.session == k_upload_session_extension {
  71. if (metadata.session == k_upload_session_extension) {
  72. do {
  73. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  74. } catch { }
  75. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  76. actionReloadDatasource = k_action_DEL
  77. } else {
  78. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  79. actionReloadDatasource = k_action_MOD
  80. }
  81. self.reloadDatasource(ServerUrl: serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  82. return
  83. }
  84. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  85. var cancel = false
  86. // DOWNLOAD
  87. if metadata.session.count > 0 && metadata.session.contains("download") {
  88. for task in downloadTasks {
  89. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  90. task.cancel()
  91. cancel = true
  92. }
  93. }
  94. if cancel == false {
  95. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  96. }
  97. actionReloadDatasource = k_action_MOD
  98. }
  99. // UPLOAD
  100. if metadata.session.count > 0 && metadata.session.contains("upload") {
  101. for task in uploadTasks {
  102. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  103. task.cancel()
  104. cancel = true
  105. }
  106. }
  107. if cancel == false {
  108. do {
  109. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  110. }
  111. catch { }
  112. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  113. }
  114. actionReloadDatasource = k_action_DEL
  115. }
  116. if cancel == false {
  117. self.reloadDatasource(ServerUrl: serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  118. }
  119. }
  120. }
  121. @objc func cancelAllTransfer() {
  122. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  123. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND (status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError), clearDateReadDirectoryID: nil)
  124. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status != %d AND status != %d", appDelegate.activeAccount, k_metadataStatusNormal, k_metadataStatusHide), sorted: "fileName", ascending: true) {
  125. for metadata in metadatas {
  126. // Modify
  127. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  128. metadata.session = ""
  129. metadata.sessionSelector = ""
  130. metadata.status = Int(k_metadataStatusNormal)
  131. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  132. }
  133. // Cancel Task
  134. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  135. cancelTransferMetadata(metadata, reloadDatasource: false)
  136. }
  137. }
  138. }
  139. self.reloadDatasource(ServerUrl: nil, fileID: nil, action: k_action_NULL)
  140. }
  141. //MARK: -
  142. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String) -> UITableViewCell {
  143. // Create File System
  144. if metadata.directory {
  145. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  146. } else {
  147. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)
  148. }
  149. // CCCell
  150. if metadata.status == k_metadataStatusNormal {
  151. // NORMAL
  152. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  153. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  154. cell.accessoryType = UITableViewCell.AccessoryType.none
  155. cell.file.image = nil
  156. cell.status.image = nil
  157. cell.favorite.image = nil
  158. cell.shared.image = nil
  159. cell.local.image = nil
  160. cell.imageTitleSegue = nil
  161. cell.shared.isUserInteractionEnabled = false
  162. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  163. // change color selection
  164. let selectionColor = UIView()
  165. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  166. cell.selectedBackgroundView = selectionColor
  167. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  168. cell.labelTitle.textColor = UIColor.black
  169. cell.labelTitle.text = metadata.fileNameView
  170. // Share
  171. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  172. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  173. var isShare = false
  174. var isMounted = false
  175. if metadataFolder != nil {
  176. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  177. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  178. }
  179. if metadata.directory {
  180. // lable Info
  181. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  182. // File Image & Image Title Segue
  183. if metadata.e2eEncrypted {
  184. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  185. cell.imageTitleSegue = UIImage.init(named: "lock")
  186. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  187. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  188. cell.imageTitleSegue = UIImage.init(named: "media")
  189. } else if isShare {
  190. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  191. cell.imageTitleSegue = UIImage.init(named: "share")
  192. } else if isMounted {
  193. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  194. cell.imageTitleSegue = UIImage.init(named: "shareMounted")
  195. } else if (sharesUserAndGroup != nil) {
  196. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  197. cell.imageTitleSegue = UIImage.init(named: "share")
  198. } else if (sharesLink != nil) {
  199. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  200. cell.imageTitleSegue = UIImage.init(named: "sharebylink")
  201. } else {
  202. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  203. }
  204. // Image Status Lock Passcode
  205. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  206. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  207. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  208. cell.status.image = UIImage.init(named: "passcode")
  209. }
  210. // Available offline
  211. if tableDirectory != nil && tableDirectory!.onDevice {
  212. cell.favorite.image = UIImage.init(named: "flagOnDevice")
  213. }
  214. } else {
  215. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  216. // Lable Info
  217. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  218. // File Image
  219. if iconFileExists {
  220. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  221. } else {
  222. if metadata.iconName.count > 0 {
  223. cell.file.image = UIImage.init(named: metadata.iconName)
  224. } else {
  225. cell.file.image = UIImage.init(named: "file")
  226. }
  227. }
  228. // Local Image
  229. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  230. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  231. cell.local.image = UIImage.init(named: "local")
  232. }
  233. // Status Image
  234. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  235. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  236. cell.status.image = UIImage.init(named: "encrypted")
  237. }
  238. // Available offline
  239. if tableLocalFile != nil && tableLocalFile!.onDevice {
  240. cell.favorite.image = UIImage.init(named: "flagOnDevice")
  241. }
  242. // Share
  243. if (isShare) {
  244. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  245. } else if (isMounted) {
  246. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  247. } else if (sharesLink != nil) {
  248. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  249. } else if (sharesUserAndGroup != nil) {
  250. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  251. }
  252. }
  253. //
  254. // File & Directory
  255. //
  256. // Favorite
  257. if metadata.favorite {
  258. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  259. }
  260. // More Image
  261. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 1, color: NCBrandColor.sharedInstance.optionItem)
  262. return cell
  263. } else {
  264. // TRASNFER
  265. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  266. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  267. cell.accessoryType = UITableViewCell.AccessoryType.none
  268. cell.file.image = nil
  269. cell.status.image = nil
  270. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  271. cell.labelTitle.textColor = UIColor.black
  272. cell.labelTitle.text = metadata.fileNameView
  273. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  274. var progress: CGFloat = 0.0
  275. var totalBytes: Double = 0.0
  276. //var totalBytesExpected : Double = 0
  277. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  278. if progressArray != nil && progressArray?.count == 3 {
  279. progress = progressArray?.object(at: 0) as! CGFloat
  280. totalBytes = progressArray?.object(at: 1) as! Double
  281. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  282. }
  283. // Write status on Label Info
  284. switch metadata.status {
  285. case Int(k_metadataStatusWaitDownload):
  286. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  287. progress = 0.0
  288. break
  289. case Int(k_metadataStatusInDownload):
  290. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  291. progress = 0.0
  292. break
  293. case Int(k_metadataStatusDownloading):
  294. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  295. break
  296. case Int(k_metadataStatusWaitUpload):
  297. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  298. progress = 0.0
  299. break
  300. case Int(k_metadataStatusInUpload):
  301. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  302. progress = 0.0
  303. break
  304. case Int(k_metadataStatusUploading):
  305. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  306. break
  307. default:
  308. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  309. progress = 0.0
  310. }
  311. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  312. if iconFileExists {
  313. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  314. } else {
  315. if metadata.iconName.count > 0 {
  316. cell.file.image = UIImage.init(named: metadata.iconName)
  317. } else {
  318. cell.file.image = UIImage.init(named: "file")
  319. }
  320. }
  321. // Session Upload Extension
  322. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  323. cell.labelTitle.isEnabled = false
  324. cell.labelInfoFile.isEnabled = false
  325. } else {
  326. cell.labelTitle.isEnabled = true
  327. cell.labelInfoFile.isEnabled = true
  328. }
  329. // downloadFile
  330. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  331. //
  332. }
  333. // downloadFile Error
  334. if metadata.status == k_metadataStatusDownloadError {
  335. cell.status.image = UIImage.init(named: "statuserror")
  336. if metadata.sessionError.count == 0 {
  337. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  338. } else {
  339. cell.labelInfoFile.text = metadata.sessionError
  340. }
  341. }
  342. // uploadFile
  343. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  344. if (!iconFileExists) {
  345. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  346. }
  347. cell.labelTitle.isEnabled = false
  348. }
  349. // uploadFileError
  350. if metadata.status == k_metadataStatusUploadError {
  351. cell.labelTitle.isEnabled = false
  352. cell.status.image = UIImage.init(named: "statuserror")
  353. if !iconFileExists {
  354. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  355. }
  356. if metadata.sessionError.count == 0 {
  357. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  358. } else {
  359. cell.labelInfoFile.text = metadata.sessionError
  360. }
  361. }
  362. // Progress
  363. cell.transferButton.progress = progress
  364. return cell
  365. }
  366. }
  367. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  368. guard let indexPath = indexPath else {
  369. return nil
  370. }
  371. guard let sectionDataSource = sectionDataSource else {
  372. return nil
  373. }
  374. let section = indexPath.section + 1
  375. let row = indexPath.row + 1
  376. let totSections = sectionDataSource.sections.count
  377. if totSections < section || section > totSections {
  378. return nil
  379. }
  380. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  381. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  382. return nil
  383. }
  384. let totRows = filesID.count
  385. if totRows < row || row > totRows {
  386. return nil
  387. }
  388. let fileID = filesID.object(at: indexPath.row)
  389. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  390. return metadata
  391. }
  392. @objc func reloadDatasource(ServerUrl: String?, fileID: String?, action: Int32) {
  393. DispatchQueue.main.async {
  394. if self.appDelegate.activeMain != nil {
  395. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  396. }
  397. if self.appDelegate.activeFavorites != nil {
  398. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  399. }
  400. if self.appDelegate.activeTransfers != nil {
  401. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  402. }
  403. }
  404. }
  405. @objc func isValidIndexPath(_ indexPath: IndexPath, tableView: UITableView) -> Bool {
  406. return indexPath.section < tableView.numberOfSections && indexPath.row < tableView.numberOfRows(inSection: indexPath.section)
  407. }
  408. //MARK: -
  409. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  410. var copyMetadatas = [tableMetadata]()
  411. for metadata in metadatas {
  412. copyMetadatas.append(tableMetadata.init(value: metadata))
  413. }
  414. if e2ee {
  415. DispatchQueue.global().async {
  416. let error = NCNetworkingEndToEnd.sharedManager().lockFolderEncrypted(onServerUrl: serverUrl, fileID: folderFileID, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl)
  417. DispatchQueue.main.async {
  418. if error == nil {
  419. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  420. } else {
  421. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  422. return
  423. }
  424. }
  425. }
  426. } else {
  427. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  428. }
  429. }
  430. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  431. var count: Int = 0
  432. var completionErrorCode: Int = 0
  433. var completionMessage = ""
  434. let ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  435. for metadata in metadatas {
  436. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  437. continue
  438. }
  439. self.appDelegate.filterFileID.add(metadata.fileID)
  440. let path = serverUrl + "/" + metadata.fileName
  441. ocNetworking?.deleteFileOrFolder(path, completion: { (message, errorCode) in
  442. count += 1
  443. if errorCode == 0 || errorCode == 404 {
  444. do {
  445. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  446. } catch { }
  447. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  448. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  449. NCManageDatabase.sharedInstance.deletePhotos(fileID: metadata.fileID)
  450. if metadata.directory {
  451. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName))
  452. }
  453. if (e2ee) {
  454. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  455. }
  456. self.appDelegate.filterFileID.remove(metadata.fileID)
  457. } else {
  458. completionErrorCode = errorCode
  459. completionMessage = ""
  460. if message != nil {
  461. completionMessage = message!
  462. }
  463. self.appDelegate.filterFileID.remove(metadata.fileID)
  464. }
  465. if count == metadatas.count {
  466. if e2ee {
  467. DispatchQueue.global().async {
  468. 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)
  469. DispatchQueue.main.async {
  470. completion(completionErrorCode, completionMessage)
  471. }
  472. }
  473. } else {
  474. completion(completionErrorCode, completionMessage)
  475. }
  476. }
  477. })
  478. }
  479. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  480. self.appDelegate.activeMedia.reloadDatasource(nil, action: Int(k_action_NULL))
  481. }
  482. }
  483. //MARK: -
  484. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  485. override func viewDidLoad() {
  486. super.viewDidLoad()
  487. delegate = self
  488. }
  489. //Delegate methods
  490. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  491. let tabViewControllers = tabBarController.viewControllers!
  492. guard let toIndex = tabViewControllers.index(of: viewController) else {
  493. if let vc = viewController as? UINavigationController {
  494. vc.popToRootViewController(animated: true);
  495. }
  496. return false
  497. }
  498. animateToTab(toIndex: toIndex)
  499. return true
  500. }
  501. func animateToTab(toIndex: Int) {
  502. let tabViewControllers = viewControllers!
  503. let fromView = selectedViewController!.view!
  504. let toView = tabViewControllers[toIndex].view!
  505. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  506. guard fromIndex != toIndex else {return}
  507. // Add the toView to the tab bar view
  508. fromView.superview?.addSubview(toView)
  509. fromView.superview?.backgroundColor = UIColor.white
  510. // Position toView off screen (to the left/right of fromView)
  511. let screenWidth = UIScreen.main.bounds.size.width;
  512. let scrollRight = toIndex > fromIndex!;
  513. let offset = (scrollRight ? screenWidth : -screenWidth)
  514. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  515. // Disable interaction during animation
  516. view.isUserInteractionEnabled = false
  517. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  518. // Slide the views by -offset
  519. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  520. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  521. }, completion: { finished in
  522. // Remove the old view from the tabbar view.
  523. fromView.removeFromSuperview()
  524. self.selectedIndex = toIndex
  525. self.view.isUserInteractionEnabled = true
  526. })
  527. }
  528. }
  529. //
  530. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  531. //
  532. extension UITabBar {
  533. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  534. // the Master view controller shows the UITabBarItem icon next to the text
  535. override open var traitCollection: UITraitCollection {
  536. if UIDevice.current.userInterfaceIdiom == .pad {
  537. return UITraitCollection(horizontalSizeClass: .compact)
  538. }
  539. return super.traitCollection
  540. }
  541. }
  542. //MARK: -
  543. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  544. @objc static let sharedInstance: NCNetworkingMain = {
  545. let instance = NCNetworkingMain()
  546. return instance
  547. }()
  548. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  549. // DOWNLOAD
  550. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  551. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  552. appDelegate.updateApplicationIconBadgeNumber()
  553. }
  554. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  555. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  556. return
  557. }
  558. if errorCode == 0 {
  559. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  560. // Synchronized
  561. if selector == selectorDownloadSynchronize {
  562. //
  563. }
  564. // open View File
  565. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  566. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  567. if appDelegate.activeMain.view.window != nil {
  568. appDelegate.activeMain.open(in: metadata)
  569. }
  570. if appDelegate.activeFavorites.view.window != nil {
  571. appDelegate.activeFavorites.open(in: metadata)
  572. }
  573. } else {
  574. if appDelegate.activeMain.view.window != nil {
  575. appDelegate.activeMain.metadata = metadata;
  576. appDelegate.activeMain.shouldPerformSegue()
  577. }
  578. if appDelegate.activeFavorites.view.window != nil {
  579. appDelegate.activeFavorites.metadata = metadata;
  580. appDelegate.activeFavorites.shouldPerformSegue()
  581. }
  582. }
  583. }
  584. // Open in...
  585. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  586. if appDelegate.activeMain.view.window != nil {
  587. appDelegate.activeMain.open(in: metadata)
  588. }
  589. if appDelegate.activeFavorites.view.window != nil {
  590. appDelegate.activeFavorites.open(in: metadata)
  591. }
  592. }
  593. // Save to Photo Album
  594. if selector == selectorSave {
  595. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  596. }
  597. // Copy File
  598. if selector == selectorLoadCopy {
  599. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  600. }
  601. // Set as available offline
  602. if selector == selectorLoadOnDevice {
  603. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, onDevice: true)
  604. }
  605. //selectorLoadViewImage
  606. if selector == selectorLoadViewImage {
  607. if appDelegate.activeDetail != nil {
  608. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  609. }
  610. if appDelegate.activeMedia != nil {
  611. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  612. }
  613. }
  614. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  615. } else {
  616. // File do not exists on server, remove in local
  617. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  618. do {
  619. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  620. } catch { }
  621. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  622. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  623. NCManageDatabase.sharedInstance.deletePhotos(fileID: fileID)
  624. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  625. }
  626. if selector == selectorLoadViewImage {
  627. if appDelegate.activeDetail.view.window != nil {
  628. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  629. }
  630. if appDelegate.activeMedia.view.window != nil {
  631. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  632. }
  633. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  634. }
  635. }
  636. }
  637. // UPLOAD
  638. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  639. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  640. appDelegate.updateApplicationIconBadgeNumber()
  641. }
  642. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  643. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  644. if errorCode == 0 {
  645. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  646. } else {
  647. NCManageDatabase.sharedInstance.addActivityClient(fileName, fileID: assetLocalIdentifier, action: k_activityDebugActionUpload, selector: selector, note: errorMessage, type: k_activityTypeFailure, verbose: false, activeUrl: appDelegate.activeUrl)
  648. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  649. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  650. }
  651. }
  652. }
  653. }
  654. //MARK: -
  655. class NCFunctionMain: NSObject {
  656. @objc static let sharedInstance: NCFunctionMain = {
  657. let instance = NCFunctionMain()
  658. return instance
  659. }()
  660. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  661. @objc func synchronizeOnDevice() {
  662. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND onDevice == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  663. if (directories != nil) {
  664. for directory: tableDirectory in directories! {
  665. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload)
  666. }
  667. }
  668. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND onDevice == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  669. if (files != nil) {
  670. for file: tableLocalFile in files! {
  671. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  672. continue
  673. }
  674. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  675. continue
  676. }
  677. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: serverUrl, selector: selectorReadFileFolderWithDownload)
  678. }
  679. }
  680. }
  681. }