NCMainCommon.swift 42 KB

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