NCMainCommon.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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 = 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: "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 = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  259. cell.accessoryType = UITableViewCell.AccessoryType.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 = ""
  451. if message != nil {
  452. completionMessage = message!
  453. }
  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. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  470. self.appDelegate.activeMedia.reloadDatasource(nil, action: Int(k_action_NULL))
  471. }
  472. }
  473. //MARK: -
  474. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  475. override func viewDidLoad() {
  476. super.viewDidLoad()
  477. delegate = self
  478. }
  479. //Delegate methods
  480. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  481. let tabViewControllers = tabBarController.viewControllers!
  482. guard let toIndex = tabViewControllers.index(of: viewController) else {
  483. if let vc = viewController as? UINavigationController {
  484. vc.popToRootViewController(animated: true);
  485. }
  486. return false
  487. }
  488. animateToTab(toIndex: toIndex)
  489. return true
  490. }
  491. func animateToTab(toIndex: Int) {
  492. let tabViewControllers = viewControllers!
  493. let fromView = selectedViewController!.view!
  494. let toView = tabViewControllers[toIndex].view!
  495. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  496. guard fromIndex != toIndex else {return}
  497. // Add the toView to the tab bar view
  498. fromView.superview?.addSubview(toView)
  499. fromView.superview?.backgroundColor = UIColor.white
  500. // Position toView off screen (to the left/right of fromView)
  501. let screenWidth = UIScreen.main.bounds.size.width;
  502. let scrollRight = toIndex > fromIndex!;
  503. let offset = (scrollRight ? screenWidth : -screenWidth)
  504. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  505. // Disable interaction during animation
  506. view.isUserInteractionEnabled = false
  507. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  508. // Slide the views by -offset
  509. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  510. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  511. }, completion: { finished in
  512. // Remove the old view from the tabbar view.
  513. fromView.removeFromSuperview()
  514. self.selectedIndex = toIndex
  515. self.view.isUserInteractionEnabled = true
  516. })
  517. }
  518. }
  519. //
  520. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  521. //
  522. extension UITabBar {
  523. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  524. // the Master view controller shows the UITabBarItem icon next to the text
  525. override open var traitCollection: UITraitCollection {
  526. if UIDevice.current.userInterfaceIdiom == .pad {
  527. return UITraitCollection(horizontalSizeClass: .compact)
  528. }
  529. return super.traitCollection
  530. }
  531. }
  532. //MARK: -
  533. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  534. @objc static let sharedInstance: NCNetworkingMain = {
  535. let instance = NCNetworkingMain()
  536. return instance
  537. }()
  538. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  539. // DOWNLOAD
  540. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  541. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  542. appDelegate.updateApplicationIconBadgeNumber()
  543. }
  544. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  545. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  546. return
  547. }
  548. if errorCode == 0 {
  549. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  550. // Synchronized
  551. if selector == selectorDownloadSynchronize {
  552. //
  553. }
  554. // open View File
  555. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  556. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  557. if appDelegate.activeMain.view.window != nil {
  558. appDelegate.activeMain.open(in: metadata)
  559. }
  560. if appDelegate.activeFavorites.view.window != nil {
  561. appDelegate.activeFavorites.open(in: metadata)
  562. }
  563. } else {
  564. if appDelegate.activeMain.view.window != nil {
  565. appDelegate.activeMain.metadata = metadata;
  566. appDelegate.activeMain.shouldPerformSegue()
  567. }
  568. if appDelegate.activeFavorites.view.window != nil {
  569. appDelegate.activeFavorites.metadata = metadata;
  570. appDelegate.activeFavorites.shouldPerformSegue()
  571. }
  572. }
  573. }
  574. // Open in...
  575. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  576. if appDelegate.activeMain.view.window != nil {
  577. appDelegate.activeMain.open(in: metadata)
  578. }
  579. if appDelegate.activeFavorites.view.window != nil {
  580. appDelegate.activeFavorites.open(in: metadata)
  581. }
  582. }
  583. // Save to Photo Album
  584. if selector == selectorSave {
  585. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  586. }
  587. // Copy File
  588. if selector == selectorLoadCopy {
  589. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  590. }
  591. //selectorLoadViewImage
  592. if selector == selectorLoadViewImage {
  593. if appDelegate.activeDetail != nil {
  594. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  595. }
  596. if appDelegate.activeMedia != nil {
  597. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  598. }
  599. }
  600. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  601. } else {
  602. // File do not exists on server, remove in local
  603. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  604. do {
  605. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  606. } catch { }
  607. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  608. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  609. NCManageDatabase.sharedInstance.deletePhotos(fileID: fileID)
  610. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  611. }
  612. if selector == selectorLoadViewImage {
  613. if appDelegate.activeDetail.view.window != nil {
  614. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  615. }
  616. if appDelegate.activeMedia.view.window != nil {
  617. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  618. }
  619. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  620. }
  621. }
  622. }
  623. // UPLOAD
  624. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  625. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  626. appDelegate.updateApplicationIconBadgeNumber()
  627. }
  628. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  629. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  630. if errorCode == 0 {
  631. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  632. } else {
  633. NCManageDatabase.sharedInstance.addActivityClient(fileName, fileID: assetLocalIdentifier, action: k_activityDebugActionUpload, selector: selector, note: errorMessage, type: k_activityTypeFailure, verbose: false, activeUrl: appDelegate.activeUrl)
  634. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  635. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  636. }
  637. }
  638. }
  639. }