NCMainCommon.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, shareLink: String?, shareUserAndGroup: String?, isShare: Bool, isMounted: Bool) -> UITableViewCell {
  31. // Create File System
  32. if metadata.directory {
  33. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  34. } else {
  35. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileName: metadata.fileNameView)
  36. }
  37. // CCCell
  38. if metadata.status == k_metadataStatusNormal {
  39. // NORMAL
  40. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  41. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  42. cell.accessoryType = UITableViewCellAccessoryType.none
  43. cell.file.image = nil
  44. cell.status.image = nil
  45. cell.favorite.image = nil
  46. cell.shared.image = nil
  47. cell.local.image = nil
  48. cell.imageTitleSegue = nil
  49. cell.shared.isUserInteractionEnabled = false
  50. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  51. // change color selection
  52. let selectionColor = UIView()
  53. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  54. cell.selectedBackgroundView = selectionColor
  55. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  56. cell.labelTitle.textColor = UIColor.black
  57. cell.labelTitle.text = metadata.fileNameView;
  58. if metadata.directory {
  59. // lable Info
  60. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  61. // File Image & Image Title Segue
  62. if metadata.e2eEncrypted {
  63. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  64. cell.imageTitleSegue = UIImage.init(named: "lock")
  65. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  66. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderPhotos"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  67. cell.imageTitleSegue = UIImage.init(named: "photos")
  68. } else if isShare {
  69. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  70. cell.imageTitleSegue = UIImage.init(named: "share")
  71. } else if isMounted {
  72. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  73. cell.imageTitleSegue = UIImage.init(named: "shareMounted")
  74. } else if (shareUserAndGroup != nil) {
  75. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  76. cell.imageTitleSegue = UIImage.init(named: "share")
  77. } else if (shareLink != nil) {
  78. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  79. cell.imageTitleSegue = UIImage.init(named: "sharebylink")
  80. } else {
  81. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  82. }
  83. // Image Status Lock Passcode
  84. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  85. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  86. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  87. cell.status.image = UIImage.init(named: "passcode")
  88. }
  89. } else {
  90. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  91. // Lable Info
  92. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  93. // File Image
  94. if iconFileExists {
  95. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  96. } else {
  97. if metadata.iconName.count > 0 {
  98. cell.file.image = UIImage.init(named: metadata.iconName)
  99. } else {
  100. cell.file.image = UIImage.init(named: "file")
  101. }
  102. }
  103. // Local Image
  104. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  105. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileName: metadata.fileNameView) {
  106. cell.local.image = UIImage.init(named: "local")
  107. }
  108. // Status Image
  109. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  110. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  111. cell.status.image = UIImage.init(named: "encrypted")
  112. }
  113. // Share
  114. if (isShare) {
  115. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  116. } else if (isMounted) {
  117. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  118. } else if (shareLink != nil) {
  119. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  120. } else if (shareUserAndGroup != nil) {
  121. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  122. }
  123. }
  124. //
  125. // File & Directory
  126. //
  127. // Favorite
  128. if metadata.favorite {
  129. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  130. }
  131. // More Image
  132. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)
  133. return cell
  134. } else {
  135. // TRASNFER
  136. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  137. cell.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0)
  138. cell.accessoryType = UITableViewCellAccessoryType.none
  139. cell.file.image = nil;
  140. cell.status.image = nil;
  141. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  142. cell.labelTitle.textColor = UIColor.black
  143. cell.labelTitle.text = metadata.fileNameView;
  144. cell.transferButton.tintColor = NCBrandColor.sharedInstance.icon
  145. var progress: CGFloat = 0.0
  146. var totalBytes: Double = 0
  147. var totalBytesExpected : Double = 0
  148. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  149. if progressArray != nil && progressArray?.count == 3 {
  150. progress = progressArray?.object(at: 0) as! CGFloat
  151. totalBytes = progressArray?.object(at: 1) as! Double
  152. totalBytesExpected = progressArray?.object(at: 2) as! Double
  153. }
  154. // Write status on Label Info
  155. switch metadata.status {
  156. case Int(k_metadataStatusWaitDownload):
  157. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " " + NSLocalizedString("_status_wait_download_", comment: "")
  158. break
  159. case Int(k_metadataStatusInDownload):
  160. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " " + NSLocalizedString("_status_in_download_", comment: "")
  161. break
  162. case Int(k_metadataStatusDownloading):
  163. if totalBytes > 0 {
  164. cell.labelInfoFile.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓" + CCUtility.transformedSize(totalBytes)
  165. } else {
  166. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  167. }
  168. break
  169. case Int(k_metadataStatusWaitUpload):
  170. cell.labelInfoFile.text = NSLocalizedString("_status_wait_upload_", comment: "")
  171. break
  172. case Int(k_metadataStatusInUpload):
  173. cell.labelInfoFile.text = NSLocalizedString("_status_in_upload_", comment: "")
  174. break
  175. case Int(k_metadataStatusUploading):
  176. if totalBytes > 0 {
  177. cell.labelInfoFile.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑" + CCUtility.transformedSize(totalBytes)
  178. } else {
  179. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  180. }
  181. break
  182. default:
  183. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  184. }
  185. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  186. if iconFileExists {
  187. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  188. } else {
  189. if metadata.iconName.count > 0 {
  190. cell.file.image = UIImage.init(named: metadata.iconName)
  191. } else {
  192. cell.file.image = UIImage.init(named: "file")
  193. }
  194. }
  195. // Session Upload Extension
  196. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  197. cell.labelTitle.isEnabled = false
  198. cell.labelInfoFile.isEnabled = false
  199. } else {
  200. cell.labelTitle.isEnabled = true
  201. cell.labelInfoFile.isEnabled = true
  202. }
  203. // downloadFile
  204. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  205. //
  206. }
  207. // downloadFile Error
  208. if metadata.status == k_metadataStatusDownloadError {
  209. cell.status.image = UIImage.init(named: "statuserror")
  210. if metadata.sessionError.count == 0 {
  211. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  212. } else {
  213. cell.labelInfoFile.text = metadata.sessionError
  214. }
  215. }
  216. // uploadFile
  217. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  218. if (!iconFileExists) {
  219. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  220. }
  221. cell.labelTitle.isEnabled = false
  222. }
  223. // uploadFileError
  224. if metadata.status == k_metadataStatusUploadError {
  225. cell.labelTitle.isEnabled = false
  226. cell.status.image = UIImage.init(named: "statuserror")
  227. if !iconFileExists {
  228. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  229. }
  230. if metadata.sessionError.count == 0 {
  231. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  232. } else {
  233. cell.labelInfoFile.text = metadata.sessionError
  234. }
  235. }
  236. // Progress
  237. cell.transferButton.progress = progress
  238. return cell
  239. }
  240. }
  241. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceFileIDIndexPath: NSDictionary, tableView: UITableView) {
  242. guard let dic = notification.userInfo else {
  243. return
  244. }
  245. let fileID = dic["fileID"] as! NSString
  246. _ = dic["serverUrl"] as! NSString
  247. let status = dic["status"] as! Int
  248. let progress = dic["progress"] as! CGFloat
  249. let totalBytes = dic["totalBytes"] as! Double
  250. let totalBytesExpected = dic["totalBytesExpected"] as! Double
  251. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: fileID)
  252. guard let indexPath = sectionDataSourceFileIDIndexPath.object(forKey: fileID) else {
  253. return
  254. }
  255. if isValidIndexPath(indexPath as! IndexPath, tableView: tableView) {
  256. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  257. var image = ""
  258. if status == k_metadataStatusInDownload {
  259. image = "↓"
  260. } else if status == k_metadataStatusInUpload {
  261. image = "↑"
  262. }
  263. cell.labelInfoFile.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  264. cell.transferButton.progress = progress
  265. }
  266. }
  267. }
  268. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool) {
  269. let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) as URLSession
  270. // SESSION EXTENSION
  271. if metadata.session == k_download_session_extension || metadata.session == k_upload_session_extension {
  272. if (metadata.session == k_upload_session_extension) {
  273. do {
  274. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  275. } catch { }
  276. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  277. } else {
  278. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  279. }
  280. appDelegate.activeMain.reloadDatasource()
  281. appDelegate.activeFavorites.reloadDatasource()
  282. if (self.appDelegate.activeTransfers != nil) {
  283. self.appDelegate.activeTransfers.reloadDatasource()
  284. }
  285. return
  286. }
  287. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  288. // DOWNLOAD
  289. if metadata.session.count > 0 && metadata.session.contains("download") {
  290. for task in downloadTasks {
  291. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  292. task.cancel()
  293. }
  294. }
  295. }
  296. // UPLOAD
  297. if metadata.session.count > 0 && metadata.session.contains("upload") {
  298. for task in uploadTasks {
  299. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  300. task.cancel()
  301. }
  302. }
  303. }
  304. }
  305. }
  306. @objc func cancelAllTransfer() {
  307. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  308. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND (status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError), clearDateReadDirectoryID: nil)
  309. guard 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) else {
  310. return
  311. }
  312. for metadata in metadatas {
  313. // Modify
  314. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  315. metadata.session = ""
  316. metadata.sessionSelector = ""
  317. metadata.status = Int(k_metadataStatusNormal)
  318. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  319. }
  320. // Cancel Task
  321. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  322. cancelTransferMetadata(metadata, reloadDatasource: false)
  323. }
  324. }
  325. self.appDelegate.activeMain.reloadDatasource()
  326. self.appDelegate.activeFavorites.reloadDatasource()
  327. if (self.appDelegate.activeTransfers != nil) {
  328. self.appDelegate.activeTransfers.reloadDatasource()
  329. }
  330. }
  331. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath, sectionDataSource: CCSectionDataSourceMetadata) -> tableMetadata? {
  332. let section = indexPath.section + 1;
  333. let row = indexPath.row + 1;
  334. let totSections = sectionDataSource.sections.count
  335. if totSections < section || section > totSections {
  336. return nil
  337. }
  338. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  339. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  340. return nil
  341. }
  342. let totRows = filesID.count
  343. if totRows < row || row > totRows {
  344. return nil
  345. }
  346. let fileID = filesID.object(at: indexPath.row)
  347. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  348. return metadata
  349. }
  350. @objc func isValidIndexPath(_ indexPath: IndexPath, tableView: UITableView) -> Bool {
  351. return indexPath.section < tableView.numberOfSections && indexPath.row < tableView.numberOfRows(inSection: indexPath.section)
  352. }
  353. }