NCMainCommon.swift 32 KB

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