NCMainCommon.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. //
  2. // NCMainCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/07/18.
  6. // Copyright © 2018 TWS. 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 = UIEdgeInsetsMake(0, 60, 0, 0)
  154. cell.accessoryType = UITableViewCellAccessoryType.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: "folderMedia"), 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. } else {
  211. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  212. // Lable Info
  213. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  214. // File Image
  215. if iconFileExists {
  216. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  217. } else {
  218. if metadata.iconName.count > 0 {
  219. cell.file.image = UIImage.init(named: metadata.iconName)
  220. } else {
  221. cell.file.image = UIImage.init(named: "file")
  222. }
  223. }
  224. // Local Image
  225. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  226. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  227. cell.local.image = UIImage.init(named: "local")
  228. }
  229. // Status Image
  230. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  231. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  232. cell.status.image = UIImage.init(named: "encrypted")
  233. }
  234. // Share
  235. if (isShare) {
  236. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  237. } else if (isMounted) {
  238. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  239. } else if (sharesLink != nil) {
  240. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  241. } else if (sharesUserAndGroup != nil) {
  242. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  243. }
  244. }
  245. //
  246. // File & Directory
  247. //
  248. // Favorite
  249. if metadata.favorite {
  250. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  251. }
  252. // More Image
  253. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  254. return cell
  255. } else {
  256. // TRASNFER
  257. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  258. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  259. cell.accessoryType = UITableViewCellAccessoryType.none
  260. cell.file.image = nil
  261. cell.status.image = nil
  262. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  263. cell.labelTitle.textColor = UIColor.black
  264. cell.labelTitle.text = metadata.fileNameView
  265. cell.transferButton.tintColor = NCBrandColor.sharedInstance.icon
  266. var progress: CGFloat = 0.0
  267. var totalBytes: Double = 0.0
  268. //var totalBytesExpected : Double = 0
  269. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  270. if progressArray != nil && progressArray?.count == 3 {
  271. progress = progressArray?.object(at: 0) as! CGFloat
  272. totalBytes = progressArray?.object(at: 1) as! Double
  273. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  274. }
  275. // Write status on Label Info
  276. switch metadata.status {
  277. case Int(k_metadataStatusWaitDownload):
  278. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  279. progress = 0.0
  280. break
  281. case Int(k_metadataStatusInDownload):
  282. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  283. progress = 0.0
  284. break
  285. case Int(k_metadataStatusDownloading):
  286. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  287. break
  288. case Int(k_metadataStatusWaitUpload):
  289. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  290. progress = 0.0
  291. break
  292. case Int(k_metadataStatusInUpload):
  293. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  294. progress = 0.0
  295. break
  296. case Int(k_metadataStatusUploading):
  297. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  298. break
  299. default:
  300. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  301. progress = 0.0
  302. }
  303. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  304. if iconFileExists {
  305. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  306. } else {
  307. if metadata.iconName.count > 0 {
  308. cell.file.image = UIImage.init(named: metadata.iconName)
  309. } else {
  310. cell.file.image = UIImage.init(named: "file")
  311. }
  312. }
  313. // Session Upload Extension
  314. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  315. cell.labelTitle.isEnabled = false
  316. cell.labelInfoFile.isEnabled = false
  317. } else {
  318. cell.labelTitle.isEnabled = true
  319. cell.labelInfoFile.isEnabled = true
  320. }
  321. // downloadFile
  322. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  323. //
  324. }
  325. // downloadFile Error
  326. if metadata.status == k_metadataStatusDownloadError {
  327. cell.status.image = UIImage.init(named: "statuserror")
  328. if metadata.sessionError.count == 0 {
  329. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  330. } else {
  331. cell.labelInfoFile.text = metadata.sessionError
  332. }
  333. }
  334. // uploadFile
  335. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  336. if (!iconFileExists) {
  337. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  338. }
  339. cell.labelTitle.isEnabled = false
  340. }
  341. // uploadFileError
  342. if metadata.status == k_metadataStatusUploadError {
  343. cell.labelTitle.isEnabled = false
  344. cell.status.image = UIImage.init(named: "statuserror")
  345. if !iconFileExists {
  346. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  347. }
  348. if metadata.sessionError.count == 0 {
  349. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  350. } else {
  351. cell.labelInfoFile.text = metadata.sessionError
  352. }
  353. }
  354. // Progress
  355. cell.transferButton.progress = progress
  356. return cell
  357. }
  358. }
  359. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  360. guard let indexPath = indexPath else {
  361. return nil
  362. }
  363. guard let sectionDataSource = sectionDataSource else {
  364. return nil
  365. }
  366. let section = indexPath.section + 1
  367. let row = indexPath.row + 1
  368. let totSections = sectionDataSource.sections.count
  369. if totSections < section || section > totSections {
  370. return nil
  371. }
  372. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  373. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  374. return nil
  375. }
  376. let totRows = filesID.count
  377. if totRows < row || row > totRows {
  378. return nil
  379. }
  380. let fileID = filesID.object(at: indexPath.row)
  381. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  382. return metadata
  383. }
  384. @objc func reloadDatasource(ServerUrl: String?, fileID: String?, action: Int32) {
  385. DispatchQueue.main.async {
  386. if self.appDelegate.activeMain != nil {
  387. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  388. }
  389. if self.appDelegate.activeFavorites != nil {
  390. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  391. }
  392. if self.appDelegate.activeTransfers != nil {
  393. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  394. }
  395. }
  396. }
  397. @objc func isValidIndexPath(_ indexPath: IndexPath, tableView: UITableView) -> Bool {
  398. return indexPath.section < tableView.numberOfSections && indexPath.row < tableView.numberOfRows(inSection: indexPath.section)
  399. }
  400. //MARK: -
  401. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  402. var copyMetadatas = [tableMetadata]()
  403. for metadata in metadatas {
  404. copyMetadatas.append(tableMetadata.init(value: metadata))
  405. }
  406. if e2ee {
  407. DispatchQueue.global().async {
  408. 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)
  409. DispatchQueue.main.async {
  410. if error == nil {
  411. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  412. } else {
  413. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  414. return
  415. }
  416. }
  417. }
  418. } else {
  419. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  420. }
  421. }
  422. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  423. var count: Int = 0
  424. var completionErrorCode: Int = 0
  425. var completionMessage = ""
  426. let ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  427. for metadata in metadatas {
  428. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  429. continue
  430. }
  431. self.appDelegate.filterFileID.add(metadata.fileID)
  432. ocNetworking?.deleteFileOrFolder(metadata.fileName, serverUrl: serverUrl, completion: { (message, errorCode) in
  433. count += 1
  434. if errorCode == 0 || errorCode == 404 {
  435. do {
  436. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  437. } catch { }
  438. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  439. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  440. NCManageDatabase.sharedInstance.deletePhotos(fileID: metadata.fileID)
  441. if metadata.directory {
  442. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName))
  443. }
  444. if (e2ee) {
  445. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  446. }
  447. } else {
  448. self.appDelegate.filterFileID.remove(metadata.fileID)
  449. completionErrorCode = errorCode
  450. completionMessage = message!
  451. }
  452. if count == metadatas.count {
  453. if e2ee {
  454. DispatchQueue.global().async {
  455. 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)
  456. DispatchQueue.main.async {
  457. completion(completionErrorCode, completionMessage)
  458. }
  459. }
  460. } else {
  461. completion(completionErrorCode, completionMessage)
  462. }
  463. }
  464. })
  465. }
  466. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  467. }
  468. }
  469. //MARK: -
  470. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  471. override func viewDidLoad() {
  472. super.viewDidLoad()
  473. delegate = self
  474. }
  475. //Delegate methods
  476. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  477. let tabViewControllers = tabBarController.viewControllers!
  478. guard let toIndex = tabViewControllers.index(of: viewController) else {
  479. if let vc = viewController as? UINavigationController {
  480. vc.popToRootViewController(animated: true);
  481. }
  482. return false
  483. }
  484. animateToTab(toIndex: toIndex)
  485. return true
  486. }
  487. func animateToTab(toIndex: Int) {
  488. let tabViewControllers = viewControllers!
  489. let fromView = selectedViewController!.view!
  490. let toView = tabViewControllers[toIndex].view!
  491. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  492. guard fromIndex != toIndex else {return}
  493. // Add the toView to the tab bar view
  494. fromView.superview?.addSubview(toView)
  495. fromView.superview?.backgroundColor = UIColor.white
  496. // Position toView off screen (to the left/right of fromView)
  497. let screenWidth = UIScreen.main.bounds.size.width;
  498. let scrollRight = toIndex > fromIndex!;
  499. let offset = (scrollRight ? screenWidth : -screenWidth)
  500. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  501. // Disable interaction during animation
  502. view.isUserInteractionEnabled = false
  503. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
  504. // Slide the views by -offset
  505. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  506. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  507. }, completion: { finished in
  508. // Remove the old view from the tabbar view.
  509. fromView.removeFromSuperview()
  510. self.selectedIndex = toIndex
  511. self.view.isUserInteractionEnabled = true
  512. })
  513. }
  514. }
  515. //
  516. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  517. //
  518. extension UITabBar {
  519. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  520. // the Master view controller shows the UITabBarItem icon next to the text
  521. override open var traitCollection: UITraitCollection {
  522. if UIDevice.current.userInterfaceIdiom == .pad {
  523. return UITraitCollection(horizontalSizeClass: .compact)
  524. }
  525. return super.traitCollection
  526. }
  527. }