NCMainCommon.swift 24 KB

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