NCMainCommon.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. if metadata.session.count == 0 {
  60. return
  61. }
  62. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else {
  63. return
  64. }
  65. // SESSION EXTENSION
  66. if metadata.session == k_download_session_extension || metadata.session == k_upload_session_extension {
  67. if (metadata.session == k_upload_session_extension) {
  68. do {
  69. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  70. } catch { }
  71. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  72. } else {
  73. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  74. }
  75. self.reloadDatasource(ServerUrl: nil)
  76. return
  77. }
  78. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  79. var cancel = false
  80. // DOWNLOAD
  81. if metadata.session.count > 0 && metadata.session.contains("download") {
  82. for task in downloadTasks {
  83. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  84. task.cancel()
  85. cancel = true
  86. }
  87. }
  88. if cancel == false {
  89. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  90. }
  91. }
  92. // UPLOAD
  93. if metadata.session.count > 0 && metadata.session.contains("upload") {
  94. for task in uploadTasks {
  95. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  96. task.cancel()
  97. cancel = true
  98. }
  99. }
  100. if cancel == false {
  101. do {
  102. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  103. }
  104. catch { }
  105. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  106. }
  107. }
  108. if cancel == false {
  109. self.reloadDatasource(ServerUrl: nil)
  110. }
  111. }
  112. }
  113. @objc func cancelAllTransfer() {
  114. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  115. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND (status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError), clearDateReadDirectoryID: nil)
  116. 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) {
  117. for metadata in metadatas {
  118. // Modify
  119. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  120. metadata.session = ""
  121. metadata.sessionSelector = ""
  122. metadata.status = Int(k_metadataStatusNormal)
  123. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  124. }
  125. // Cancel Task
  126. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  127. cancelTransferMetadata(metadata, reloadDatasource: false)
  128. }
  129. }
  130. }
  131. self.reloadDatasource(ServerUrl: nil)
  132. }
  133. //MARK: -
  134. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String) -> UITableViewCell {
  135. // Create File System
  136. if metadata.directory {
  137. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  138. } else {
  139. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)
  140. }
  141. // CCCell
  142. if metadata.status == k_metadataStatusNormal {
  143. // NORMAL
  144. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  145. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  146. cell.accessoryType = UITableViewCellAccessoryType.none
  147. cell.file.image = nil
  148. cell.status.image = nil
  149. cell.favorite.image = nil
  150. cell.shared.image = nil
  151. cell.local.image = nil
  152. cell.imageTitleSegue = nil
  153. cell.shared.isUserInteractionEnabled = false
  154. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  155. // change color selection
  156. let selectionColor = UIView()
  157. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  158. cell.selectedBackgroundView = selectionColor
  159. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  160. cell.labelTitle.textColor = UIColor.black
  161. cell.labelTitle.text = metadata.fileNameView
  162. // Share
  163. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  164. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  165. var isShare = false
  166. var isMounted = false
  167. if metadataFolder != nil {
  168. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  169. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  170. }
  171. if metadata.directory {
  172. // lable Info
  173. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  174. // File Image & Image Title Segue
  175. if metadata.e2eEncrypted {
  176. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  177. cell.imageTitleSegue = UIImage.init(named: "lock")
  178. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  179. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderMedia"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  180. cell.imageTitleSegue = UIImage.init(named: "media")
  181. } else if isShare {
  182. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  183. cell.imageTitleSegue = UIImage.init(named: "share")
  184. } else if isMounted {
  185. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  186. cell.imageTitleSegue = UIImage.init(named: "shareMounted")
  187. } else if (sharesUserAndGroup != nil) {
  188. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  189. cell.imageTitleSegue = UIImage.init(named: "share")
  190. } else if (sharesLink != nil) {
  191. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  192. cell.imageTitleSegue = UIImage.init(named: "sharebylink")
  193. } else {
  194. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  195. }
  196. // Image Status Lock Passcode
  197. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  198. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  199. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  200. cell.status.image = UIImage.init(named: "passcode")
  201. }
  202. } else {
  203. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  204. // Lable Info
  205. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  206. // File Image
  207. if iconFileExists {
  208. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  209. } else {
  210. if metadata.iconName.count > 0 {
  211. cell.file.image = UIImage.init(named: metadata.iconName)
  212. } else {
  213. cell.file.image = UIImage.init(named: "file")
  214. }
  215. }
  216. // Local Image
  217. if CCUtility.getOptimizedPhoto() && metadata.typeFile == k_metadataTypeFile_image {
  218. if CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) || CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  219. cell.local.image = UIImage.init(named: "local")
  220. }
  221. } else {
  222. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  223. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  224. cell.local.image = UIImage.init(named: "local")
  225. }
  226. }
  227. //![[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]
  228. // Status Image
  229. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  230. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  231. cell.status.image = UIImage.init(named: "encrypted")
  232. }
  233. // Share
  234. if (isShare) {
  235. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  236. } else if (isMounted) {
  237. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  238. } else if (sharesLink != nil) {
  239. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  240. } else if (sharesUserAndGroup != nil) {
  241. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  242. }
  243. }
  244. //
  245. // File & Directory
  246. //
  247. // Favorite
  248. if metadata.favorite {
  249. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  250. }
  251. // More Image
  252. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  253. return cell
  254. } else {
  255. // TRASNFER
  256. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  257. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  258. cell.accessoryType = UITableViewCellAccessoryType.none
  259. cell.file.image = nil
  260. cell.status.image = nil
  261. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  262. cell.labelTitle.textColor = UIColor.black
  263. cell.labelTitle.text = metadata.fileNameView
  264. cell.transferButton.tintColor = NCBrandColor.sharedInstance.icon
  265. var progress: CGFloat = 0.0
  266. var totalBytes: Double = 0.0
  267. //var totalBytesExpected : Double = 0
  268. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  269. if progressArray != nil && progressArray?.count == 3 {
  270. progress = progressArray?.object(at: 0) as! CGFloat
  271. totalBytes = progressArray?.object(at: 1) as! Double
  272. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  273. }
  274. // Write status on Label Info
  275. switch metadata.status {
  276. case Int(k_metadataStatusWaitDownload):
  277. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  278. progress = 0.0
  279. break
  280. case Int(k_metadataStatusInDownload):
  281. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  282. progress = 0.0
  283. break
  284. case Int(k_metadataStatusDownloading):
  285. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  286. break
  287. case Int(k_metadataStatusWaitUpload):
  288. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  289. progress = 0.0
  290. break
  291. case Int(k_metadataStatusInUpload):
  292. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  293. progress = 0.0
  294. break
  295. case Int(k_metadataStatusUploading):
  296. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  297. break
  298. default:
  299. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  300. progress = 0.0
  301. }
  302. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  303. if iconFileExists {
  304. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  305. } else {
  306. if metadata.iconName.count > 0 {
  307. cell.file.image = UIImage.init(named: metadata.iconName)
  308. } else {
  309. cell.file.image = UIImage.init(named: "file")
  310. }
  311. }
  312. // Session Upload Extension
  313. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  314. cell.labelTitle.isEnabled = false
  315. cell.labelInfoFile.isEnabled = false
  316. } else {
  317. cell.labelTitle.isEnabled = true
  318. cell.labelInfoFile.isEnabled = true
  319. }
  320. // downloadFile
  321. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  322. //
  323. }
  324. // downloadFile Error
  325. if metadata.status == k_metadataStatusDownloadError {
  326. cell.status.image = UIImage.init(named: "statuserror")
  327. if metadata.sessionError.count == 0 {
  328. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  329. } else {
  330. cell.labelInfoFile.text = metadata.sessionError
  331. }
  332. }
  333. // uploadFile
  334. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  335. if (!iconFileExists) {
  336. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  337. }
  338. cell.labelTitle.isEnabled = false
  339. }
  340. // uploadFileError
  341. if metadata.status == k_metadataStatusUploadError {
  342. cell.labelTitle.isEnabled = false
  343. cell.status.image = UIImage.init(named: "statuserror")
  344. if !iconFileExists {
  345. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  346. }
  347. if metadata.sessionError.count == 0 {
  348. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  349. } else {
  350. cell.labelInfoFile.text = metadata.sessionError
  351. }
  352. }
  353. // Progress
  354. cell.transferButton.progress = progress
  355. return cell
  356. }
  357. }
  358. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  359. guard let indexPath = indexPath else {
  360. return nil
  361. }
  362. guard let sectionDataSource = sectionDataSource else {
  363. return nil
  364. }
  365. let section = indexPath.section + 1
  366. let row = indexPath.row + 1
  367. let totSections = sectionDataSource.sections.count
  368. if totSections < section || section > totSections {
  369. return nil
  370. }
  371. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  372. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  373. return nil
  374. }
  375. let totRows = filesID.count
  376. if totRows < row || row > totRows {
  377. return nil
  378. }
  379. let fileID = filesID.object(at: indexPath.row)
  380. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  381. return metadata
  382. }
  383. @objc func reloadDatasource(ServerUrl: String?) {
  384. DispatchQueue.main.async {
  385. if self.appDelegate.activeMain != nil {
  386. if ServerUrl == nil {
  387. self.appDelegate.activeMain.reloadDatasource()
  388. } else {
  389. self.appDelegate.activeMain.reloadDatasource(ServerUrl)
  390. }
  391. }
  392. if self.appDelegate.activeFavorites != nil {
  393. self.appDelegate.activeFavorites.reloadDatasource()
  394. }
  395. if self.appDelegate.activeTransfers != nil {
  396. self.appDelegate.activeTransfers.reloadDatasource()
  397. }
  398. }
  399. }
  400. @objc func isValidIndexPath(_ indexPath: IndexPath, tableView: UITableView) -> Bool {
  401. return indexPath.section < tableView.numberOfSections && indexPath.row < tableView.numberOfRows(inSection: indexPath.section)
  402. }
  403. //MARK: -
  404. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  405. var copyMetadatas = [tableMetadata]()
  406. for metadata in metadatas {
  407. copyMetadatas.append(tableMetadata.init(value: metadata))
  408. }
  409. if e2ee {
  410. DispatchQueue.global().async {
  411. 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)
  412. DispatchQueue.main.async {
  413. if error == nil {
  414. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  415. } else {
  416. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  417. return
  418. }
  419. }
  420. }
  421. } else {
  422. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  423. }
  424. }
  425. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  426. var count: Int = 0
  427. var completionErrorCode: Int = 0
  428. var completionMessage = ""
  429. let ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  430. for metadata in metadatas {
  431. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  432. continue
  433. }
  434. self.appDelegate.filterFileID.add(metadata.fileID)
  435. ocNetworking?.deleteFileOrFolder(metadata.fileName, serverUrl: serverUrl, completion: { (message, errorCode) in
  436. count += 1
  437. if errorCode == 0 || errorCode == 404 {
  438. do {
  439. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  440. } catch { }
  441. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  442. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  443. NCManageDatabase.sharedInstance.deletePhotos(fileID: metadata.fileID)
  444. if metadata.directory {
  445. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName))
  446. }
  447. if (e2ee) {
  448. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  449. }
  450. } else {
  451. self.appDelegate.filterFileID.remove(metadata.fileID)
  452. completionErrorCode = errorCode
  453. completionMessage = message!
  454. }
  455. if count == metadatas.count {
  456. if e2ee {
  457. DispatchQueue.global().async {
  458. 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)
  459. DispatchQueue.main.async {
  460. completion(completionErrorCode, completionMessage)
  461. }
  462. }
  463. } else {
  464. completion(completionErrorCode, completionMessage)
  465. }
  466. }
  467. })
  468. }
  469. // reload for filesID
  470. self.appDelegate.activeMain.reloadDatasource()
  471. self.appDelegate.activeMedia.reloadDatasource()
  472. }
  473. }
  474. //MARK: -
  475. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  476. override func viewDidLoad() {
  477. super.viewDidLoad()
  478. delegate = self
  479. }
  480. //Delegate methods
  481. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  482. let tabViewControllers = tabBarController.viewControllers!
  483. guard let toIndex = tabViewControllers.index(of: viewController) else {
  484. if let vc = viewController as? UINavigationController {
  485. vc.popToRootViewController(animated: true);
  486. }
  487. return false
  488. }
  489. animateToTab(toIndex: toIndex)
  490. return true
  491. }
  492. func animateToTab(toIndex: Int) {
  493. let tabViewControllers = viewControllers!
  494. let fromView = selectedViewController!.view!
  495. let toView = tabViewControllers[toIndex].view!
  496. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  497. guard fromIndex != toIndex else {return}
  498. // Add the toView to the tab bar view
  499. fromView.superview?.addSubview(toView)
  500. fromView.superview?.backgroundColor = UIColor.white
  501. // Position toView off screen (to the left/right of fromView)
  502. let screenWidth = UIScreen.main.bounds.size.width;
  503. let scrollRight = toIndex > fromIndex!;
  504. let offset = (scrollRight ? screenWidth : -screenWidth)
  505. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  506. // Disable interaction during animation
  507. view.isUserInteractionEnabled = false
  508. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
  509. // Slide the views by -offset
  510. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  511. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  512. }, completion: { finished in
  513. // Remove the old view from the tabbar view.
  514. fromView.removeFromSuperview()
  515. self.selectedIndex = toIndex
  516. self.view.isUserInteractionEnabled = true
  517. })
  518. }
  519. }
  520. //
  521. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  522. //
  523. extension UITabBar {
  524. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  525. // the Master view controller shows the UITabBarItem icon next to the text
  526. override open var traitCollection: UITraitCollection {
  527. if UIDevice.current.userInterfaceIdiom == .pad {
  528. return UITraitCollection(horizontalSizeClass: .compact)
  529. }
  530. return super.traitCollection
  531. }
  532. }