NCMainCommon.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. //
  2. // NCMainCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/07/18.
  6. // Copyright © 2018 Marino Faggiana. 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: "folderAutomaticUpload"), 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. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  205. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  206. // Local image: offline
  207. if tableDirectory != nil && tableDirectory!.offline {
  208. cell.local.image = UIImage.init(named: "offlineFlag")
  209. }
  210. // Status image: passcode
  211. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  212. cell.status.image = UIImage.init(named: "passcode")
  213. }
  214. } else {
  215. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  216. // Lable Info
  217. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  218. // File Image
  219. if iconFileExists {
  220. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  221. } else {
  222. if metadata.iconName.count > 0 {
  223. cell.file.image = UIImage.init(named: metadata.iconName)
  224. } else {
  225. cell.file.image = UIImage.init(named: "file")
  226. }
  227. }
  228. // Local Image - Offline
  229. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  230. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  231. if tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  232. else { cell.local.image = UIImage.init(named: "local") }
  233. }
  234. // Status image: encrypted
  235. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  236. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  237. cell.status.image = UIImage.init(named: "encrypted")
  238. }
  239. // Share
  240. if (isShare) {
  241. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  242. } else if (isMounted) {
  243. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  244. } else if (sharesLink != nil) {
  245. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  246. } else if (sharesUserAndGroup != nil) {
  247. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  248. }
  249. }
  250. //
  251. // File & Directory
  252. //
  253. // Favorite
  254. if metadata.favorite {
  255. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  256. }
  257. // More Image
  258. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 1, color: NCBrandColor.sharedInstance.optionItem)
  259. return cell
  260. } else {
  261. // TRASNFER
  262. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  263. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  264. cell.accessoryType = UITableViewCell.AccessoryType.none
  265. cell.file.image = nil
  266. cell.status.image = nil
  267. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  268. cell.labelTitle.textColor = UIColor.black
  269. cell.labelTitle.text = metadata.fileNameView
  270. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  271. var progress: CGFloat = 0.0
  272. var totalBytes: Double = 0.0
  273. //var totalBytesExpected : Double = 0
  274. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  275. if progressArray != nil && progressArray?.count == 3 {
  276. progress = progressArray?.object(at: 0) as! CGFloat
  277. totalBytes = progressArray?.object(at: 1) as! Double
  278. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  279. }
  280. // Write status on Label Info
  281. switch metadata.status {
  282. case Int(k_metadataStatusWaitDownload):
  283. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  284. progress = 0.0
  285. break
  286. case Int(k_metadataStatusInDownload):
  287. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  288. progress = 0.0
  289. break
  290. case Int(k_metadataStatusDownloading):
  291. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  292. break
  293. case Int(k_metadataStatusWaitUpload):
  294. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  295. progress = 0.0
  296. break
  297. case Int(k_metadataStatusInUpload):
  298. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  299. progress = 0.0
  300. break
  301. case Int(k_metadataStatusUploading):
  302. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  303. break
  304. default:
  305. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  306. progress = 0.0
  307. }
  308. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  309. if iconFileExists {
  310. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  311. } else {
  312. if metadata.iconName.count > 0 {
  313. cell.file.image = UIImage.init(named: metadata.iconName)
  314. } else {
  315. cell.file.image = UIImage.init(named: "file")
  316. }
  317. }
  318. // Session Upload Extension
  319. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  320. cell.labelTitle.isEnabled = false
  321. cell.labelInfoFile.isEnabled = false
  322. } else {
  323. cell.labelTitle.isEnabled = true
  324. cell.labelInfoFile.isEnabled = true
  325. }
  326. // downloadFile
  327. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  328. //
  329. }
  330. // downloadFile Error
  331. if metadata.status == k_metadataStatusDownloadError {
  332. cell.status.image = UIImage.init(named: "statuserror")
  333. if metadata.sessionError.count == 0 {
  334. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  335. } else {
  336. cell.labelInfoFile.text = metadata.sessionError
  337. }
  338. }
  339. // uploadFile
  340. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  341. if (!iconFileExists) {
  342. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  343. }
  344. cell.labelTitle.isEnabled = false
  345. }
  346. // uploadFileError
  347. if metadata.status == k_metadataStatusUploadError {
  348. cell.labelTitle.isEnabled = false
  349. cell.status.image = UIImage.init(named: "statuserror")
  350. if !iconFileExists {
  351. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  352. }
  353. if metadata.sessionError.count == 0 {
  354. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  355. } else {
  356. cell.labelInfoFile.text = metadata.sessionError
  357. }
  358. }
  359. // Progress
  360. cell.transferButton.progress = progress
  361. return cell
  362. }
  363. }
  364. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  365. guard let indexPath = indexPath else {
  366. return nil
  367. }
  368. guard let sectionDataSource = sectionDataSource else {
  369. return nil
  370. }
  371. let section = indexPath.section + 1
  372. let row = indexPath.row + 1
  373. let totSections = sectionDataSource.sections.count
  374. if totSections < section || section > totSections {
  375. return nil
  376. }
  377. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  378. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  379. return nil
  380. }
  381. let totRows = filesID.count
  382. if totRows < row || row > totRows {
  383. return nil
  384. }
  385. let fileID = filesID.object(at: indexPath.row)
  386. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  387. return metadata
  388. }
  389. @objc func reloadDatasource(ServerUrl: String?, fileID: String?, action: Int32) {
  390. DispatchQueue.main.async {
  391. if self.appDelegate.activeMain != nil {
  392. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  393. }
  394. if self.appDelegate.activeFavorites != nil {
  395. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  396. }
  397. if self.appDelegate.activeTransfers != nil {
  398. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  399. }
  400. }
  401. }
  402. @objc func isValidIndexPath(_ indexPath: IndexPath, tableView: UITableView) -> Bool {
  403. return indexPath.section < tableView.numberOfSections && indexPath.row < tableView.numberOfRows(inSection: indexPath.section)
  404. }
  405. //MARK: -
  406. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  407. var copyMetadatas = [tableMetadata]()
  408. for metadata in metadatas {
  409. copyMetadatas.append(tableMetadata.init(value: metadata))
  410. }
  411. if e2ee {
  412. DispatchQueue.global().async {
  413. 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)
  414. DispatchQueue.main.async {
  415. if error == nil {
  416. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  417. } else {
  418. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  419. return
  420. }
  421. }
  422. }
  423. } else {
  424. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  425. }
  426. }
  427. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  428. var count: Int = 0
  429. var completionErrorCode: Int = 0
  430. var completionMessage = ""
  431. let ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  432. for metadata in metadatas {
  433. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  434. continue
  435. }
  436. self.appDelegate.filterFileID.add(metadata.fileID)
  437. let path = serverUrl + "/" + metadata.fileName
  438. ocNetworking?.deleteFileOrFolder(path, completion: { (message, errorCode) in
  439. count += 1
  440. if errorCode == 0 || errorCode == 404 {
  441. do {
  442. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  443. } catch { }
  444. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  445. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  446. NCManageDatabase.sharedInstance.deletePhotos(fileID: metadata.fileID)
  447. if metadata.directory {
  448. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName))
  449. }
  450. if (e2ee) {
  451. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  452. }
  453. self.appDelegate.filterFileID.remove(metadata.fileID)
  454. } else {
  455. completionErrorCode = errorCode
  456. completionMessage = ""
  457. if message != nil {
  458. completionMessage = message!
  459. }
  460. self.appDelegate.filterFileID.remove(metadata.fileID)
  461. }
  462. if count == metadatas.count {
  463. if e2ee {
  464. DispatchQueue.global().async {
  465. 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)
  466. DispatchQueue.main.async {
  467. completion(completionErrorCode, completionMessage)
  468. }
  469. }
  470. } else {
  471. completion(completionErrorCode, completionMessage)
  472. }
  473. }
  474. })
  475. }
  476. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  477. self.appDelegate.activeMedia.reloadDatasource(nil, action: Int(k_action_NULL))
  478. }
  479. }
  480. //MARK: -
  481. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  482. override func viewDidLoad() {
  483. super.viewDidLoad()
  484. delegate = self
  485. }
  486. //Delegate methods
  487. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  488. let tabViewControllers = tabBarController.viewControllers!
  489. guard let toIndex = tabViewControllers.index(of: viewController) else {
  490. if let vc = viewController as? UINavigationController {
  491. vc.popToRootViewController(animated: true);
  492. }
  493. return false
  494. }
  495. animateToTab(toIndex: toIndex)
  496. return true
  497. }
  498. func animateToTab(toIndex: Int) {
  499. let tabViewControllers = viewControllers!
  500. let fromView = selectedViewController!.view!
  501. let toView = tabViewControllers[toIndex].view!
  502. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  503. guard fromIndex != toIndex else {return}
  504. // Add the toView to the tab bar view
  505. fromView.superview?.addSubview(toView)
  506. fromView.superview?.backgroundColor = UIColor.white
  507. // Position toView off screen (to the left/right of fromView)
  508. let screenWidth = UIScreen.main.bounds.size.width;
  509. let scrollRight = toIndex > fromIndex!;
  510. let offset = (scrollRight ? screenWidth : -screenWidth)
  511. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  512. // Disable interaction during animation
  513. view.isUserInteractionEnabled = false
  514. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  515. // Slide the views by -offset
  516. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  517. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  518. }, completion: { finished in
  519. // Remove the old view from the tabbar view.
  520. fromView.removeFromSuperview()
  521. self.selectedIndex = toIndex
  522. self.view.isUserInteractionEnabled = true
  523. })
  524. }
  525. }
  526. //
  527. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  528. //
  529. extension UITabBar {
  530. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  531. // the Master view controller shows the UITabBarItem icon next to the text
  532. override open var traitCollection: UITraitCollection {
  533. if UIDevice.current.userInterfaceIdiom == .pad {
  534. return UITraitCollection(horizontalSizeClass: .compact)
  535. }
  536. return super.traitCollection
  537. }
  538. }
  539. //MARK: -
  540. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  541. @objc static let sharedInstance: NCNetworkingMain = {
  542. let instance = NCNetworkingMain()
  543. return instance
  544. }()
  545. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  546. // DOWNLOAD
  547. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  548. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  549. appDelegate.updateApplicationIconBadgeNumber()
  550. }
  551. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  552. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  553. return
  554. }
  555. if errorCode == 0 {
  556. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  557. // Synchronized
  558. if selector == selectorDownloadSynchronize {
  559. //
  560. }
  561. // open View File
  562. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  563. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  564. if appDelegate.activeMain.view.window != nil {
  565. appDelegate.activeMain.open(in: metadata)
  566. }
  567. if appDelegate.activeFavorites.view.window != nil {
  568. appDelegate.activeFavorites.open(in: metadata)
  569. }
  570. } else {
  571. if appDelegate.activeMain.view.window != nil {
  572. appDelegate.activeMain.metadata = metadata;
  573. appDelegate.activeMain.shouldPerformSegue()
  574. }
  575. if appDelegate.activeFavorites.view.window != nil {
  576. appDelegate.activeFavorites.metadata = metadata;
  577. appDelegate.activeFavorites.shouldPerformSegue()
  578. }
  579. }
  580. }
  581. // Open in...
  582. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  583. if appDelegate.activeMain.view.window != nil {
  584. appDelegate.activeMain.open(in: metadata)
  585. }
  586. if appDelegate.activeFavorites.view.window != nil {
  587. appDelegate.activeFavorites.open(in: metadata)
  588. }
  589. }
  590. // Save to Photo Album
  591. if selector == selectorSave {
  592. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  593. }
  594. // Copy File
  595. if selector == selectorLoadCopy {
  596. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  597. }
  598. // Set as available offline
  599. if selector == selectorLoadOffline {
  600. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  601. }
  602. //selectorLoadViewImage
  603. if selector == selectorLoadViewImage {
  604. if appDelegate.activeDetail != nil {
  605. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  606. }
  607. if appDelegate.activeMedia != nil {
  608. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  609. }
  610. }
  611. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  612. } else {
  613. // File do not exists on server, remove in local
  614. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  615. do {
  616. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  617. } catch { }
  618. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  619. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  620. NCManageDatabase.sharedInstance.deletePhotos(fileID: fileID)
  621. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  622. }
  623. if selector == selectorLoadViewImage {
  624. if appDelegate.activeDetail.view.window != nil {
  625. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  626. }
  627. if appDelegate.activeMedia.view.window != nil {
  628. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  629. }
  630. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  631. }
  632. }
  633. }
  634. // UPLOAD
  635. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  636. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  637. appDelegate.updateApplicationIconBadgeNumber()
  638. }
  639. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  640. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  641. if errorCode == 0 {
  642. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  643. } else {
  644. NCManageDatabase.sharedInstance.addActivityClient(fileName, fileID: assetLocalIdentifier, action: k_activityDebugActionUpload, selector: selector, note: errorMessage, type: k_activityTypeFailure, verbose: false, activeUrl: appDelegate.activeUrl)
  645. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  646. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  647. }
  648. }
  649. }
  650. }
  651. //MARK: -
  652. class NCFunctionMain: NSObject {
  653. @objc static let sharedInstance: NCFunctionMain = {
  654. let instance = NCFunctionMain()
  655. return instance
  656. }()
  657. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  658. @objc func synchronizeOffline() {
  659. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  660. if (directories != nil) {
  661. for directory: tableDirectory in directories! {
  662. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload)
  663. }
  664. }
  665. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  666. if (files != nil) {
  667. for file: tableLocalFile in files! {
  668. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  669. continue
  670. }
  671. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  672. continue
  673. }
  674. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: serverUrl, selector: selectorReadFileFolderWithDownload)
  675. }
  676. }
  677. }
  678. }