NCMainCommon.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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 <marino.faggiana@nextcloud.com>
  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. import TLPhotoPicker
  25. import ZIPFoundation
  26. import NCCommunication
  27. //MARK: - Main Common
  28. class NCMainCommon: NSObject, NCAudioRecorderViewControllerDelegate, UIDocumentInteractionControllerDelegate, UITextViewDelegate {
  29. @objc static let shared: NCMainCommon = {
  30. let instance = NCMainCommon()
  31. instance.createImagesThemingColor()
  32. return instance
  33. }()
  34. var metadataEditPhoto: tableMetadata?
  35. var docController: UIDocumentInteractionController?
  36. //MARK: -
  37. struct NCMainCommonImages {
  38. static var cellSharedImage = UIImage()
  39. static var cellCanShareImage = UIImage()
  40. static var cellShareByLinkImage = UIImage()
  41. static var cellFavouriteImage = UIImage()
  42. static var cellMoreImage = UIImage()
  43. static var cellCommentImage = UIImage()
  44. static var cellLivePhotoImage = UIImage()
  45. static var cellFolderEncryptedImage = UIImage()
  46. static var cellFolderSharedWithMeImage = UIImage()
  47. static var cellFolderPublicImage = UIImage()
  48. static var cellFolderGroupImage = UIImage()
  49. static var cellFolderExternalImage = UIImage()
  50. static var cellFolderAutomaticUploadImage = UIImage()
  51. static var cellFolderImage = UIImage()
  52. static var cellPlayImage = UIImage()
  53. }
  54. @objc func createImagesThemingColor() {
  55. NCMainCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  56. NCMainCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  57. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  58. NCMainCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  59. NCMainCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  60. NCMainCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  61. NCMainCommonImages.cellLivePhotoImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "livePhoto"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  62. NCMainCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  63. NCMainCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  64. NCMainCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  65. NCMainCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  66. NCMainCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  67. NCMainCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  68. NCMainCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  69. NCMainCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  70. }
  71. // MARK: -
  72. func createFolder() {
  73. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  74. guard let serverUrl = appDelegate.activeServerUrl else { return }
  75. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_on_", comment: ""), message: nil, preferredStyle: .alert)
  76. alertController.addTextField { (textField) in
  77. //[textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  78. textField.autocapitalizationType = UITextAutocapitalizationType.sentences
  79. }
  80. let cancelAction = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil)
  81. let okAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in
  82. if let fileNameFolder = alertController.textFields?.first?.text {
  83. NCNetworking.shared.createFolder(fileName: fileNameFolder, serverUrl: serverUrl, account: appDelegate.account, urlBase: appDelegate.urlBase, overwrite: false) { (errorCode, errorDescription) in
  84. if errorCode != 0 {
  85. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  86. }
  87. }
  88. }
  89. })
  90. //okAction.enabled = NO;
  91. alertController.addAction(cancelAction)
  92. alertController.addAction(okAction)
  93. appDelegate.window.rootViewController?.present(alertController, animated: true, completion: nil)
  94. }
  95. //MARK: -
  96. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  97. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  98. if viewController.viewIfLoaded?.window == nil {
  99. return
  100. }
  101. guard let dic = notification.userInfo else {
  102. return
  103. }
  104. let account = dic["account"] as? NSString ?? ""
  105. let ocId = dic["ocId"] as? NSString ?? ""
  106. let serverUrl = dic["serverUrl"] as? String ?? ""
  107. let status = dic["status"] as? Int ?? Int(k_metadataStatusNormal)
  108. let progress = dic["progress"] as? CGFloat ?? 0
  109. let totalBytes = dic["totalBytes"] as? Double ?? 0
  110. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  111. if (account != appDelegate.account! as NSString) && !(viewController is CCTransfers) {
  112. return
  113. }
  114. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  115. return
  116. }
  117. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  118. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  119. return
  120. }
  121. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  122. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  123. var image = ""
  124. if status == k_metadataStatusInDownload {
  125. image = "↓"
  126. } else if status == k_metadataStatusInUpload {
  127. image = "↑"
  128. }
  129. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  130. cell.transferButton?.progress = progress
  131. }
  132. }
  133. }
  134. @objc func cancelTransferMetadata(_ metadata: tableMetadata, uploadStatusForcedStart: Bool) {
  135. if metadata.session.count == 0 {
  136. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  137. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  138. return
  139. }
  140. let metadata = tableMetadata.init(value: metadata)
  141. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  142. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  143. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  144. NCNetworking.shared.cancelUpload(ocId: metadata.ocId)
  145. } else {
  146. var session: URLSession?
  147. if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
  148. session = NCNetworking.shared.sessionManagerBackground
  149. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  150. session = NCNetworking.shared.sessionManagerBackgroundWWan
  151. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundExtension {
  152. session = NCNetworking.shared.sessionManagerBackgroundExtension
  153. }
  154. session!.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  155. var cancel = false
  156. if metadata.session.count > 0 && metadata.session.contains("upload") {
  157. for task in uploadTasks {
  158. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  159. if uploadStatusForcedStart {
  160. metadata.status = Int(k_metadataStatusUploadForcedStart)
  161. NCManageDatabase.sharedInstance.addMetadata(metadata)
  162. }
  163. task.cancel()
  164. cancel = true
  165. }
  166. }
  167. if cancel == false {
  168. do {
  169. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  170. }
  171. catch { }
  172. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  173. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  174. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  175. }
  176. }
  177. }
  178. }
  179. }
  180. }
  181. @objc func cancelAllTransfer() {
  182. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  183. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  184. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.account, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  185. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  186. let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d", k_metadataStatusNormal), sorted: "fileName", ascending: true)
  187. for metadata in metadatas {
  188. // Modify
  189. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  190. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal))
  191. }
  192. // Cancel Task
  193. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  194. self.cancelTransferMetadata(metadata, uploadStatusForcedStart: false)
  195. }
  196. }
  197. }
  198. NCOperationQueue.shared.downloadCancelAll()
  199. }
  200. //MARK: -
  201. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?, livePhoto: Bool) -> UITableViewCell {
  202. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  203. // Create File System
  204. if metadata.directory {
  205. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  206. } else {
  207. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  208. }
  209. // CCCell
  210. if metadata.status == k_metadataStatusNormal || metadata.status == k_metadataStatusDownloadError {
  211. // NORMAL
  212. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  213. cell.labelTitle.text = metadata.fileNameView
  214. cell.filePreviewImageView.image = nil
  215. cell.filePreviewImageView.backgroundColor = UIColor.lightGray
  216. // Download preview
  217. if !(metadataFolder?.e2eEncrypted ?? false) {
  218. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: tableView, indexPath: indexPath)
  219. }
  220. // Share
  221. var isShare = false
  222. var isMounted = false
  223. if metadataFolder != nil {
  224. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  225. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  226. }
  227. if metadata.directory {
  228. // lable Info
  229. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  230. cell.file.backgroundColor = nil
  231. // File Image & Image Title Segue
  232. if metadata.e2eEncrypted {
  233. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  234. } else if isShare {
  235. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  236. } else if (tableShare != nil && tableShare!.shareType != 3) {
  237. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  238. } else if (tableShare != nil && tableShare!.shareType == 3) {
  239. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  240. } else if metadata.mountType == "group" {
  241. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  242. } else if isMounted {
  243. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  244. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  245. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  246. } else {
  247. cell.file.image = NCMainCommonImages.cellFolderImage
  248. }
  249. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  250. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  251. // Local image: offline
  252. if tableDirectory != nil && tableDirectory!.offline {
  253. cell.local.image = UIImage.init(named: "offlineFlag")
  254. }
  255. } else {
  256. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  257. // Lable Info
  258. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  259. // File Image
  260. if iconFileExists {
  261. cell.file.backgroundColor = nil
  262. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  263. } else if(!metadata.hasPreview){
  264. cell.file.backgroundColor = nil
  265. if metadata.iconName.count > 0 {
  266. cell.file.image = UIImage.init(named: metadata.iconName)
  267. } else {
  268. cell.file.image = UIImage.init(named: "file")
  269. }
  270. }
  271. // Local Image - Offline
  272. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  273. if size > 0 {
  274. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  275. if tableLocalFile == nil && size == metadata.size {
  276. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  277. }
  278. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  279. else { cell.local.image = UIImage.init(named: "local") }
  280. }
  281. // Status image: encrypted
  282. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.account, metadata.fileName))
  283. if tableE2eEncryption != nil && NCUtility.shared.isEncryptedMetadata(metadata) {
  284. cell.status.image = UIImage.init(named: "encrypted")
  285. }
  286. // Live Photo
  287. if metadata.livePhoto && livePhoto {
  288. cell.status.image = NCMainCommonImages.cellLivePhotoImage
  289. }
  290. }
  291. //
  292. // File & Directory
  293. //
  294. // Favorite
  295. if metadata.favorite {
  296. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  297. }
  298. // Share image
  299. if !(metadataFolder?.e2eEncrypted ?? false) && !metadata.e2eEncrypted {
  300. if (isShare) {
  301. cell.shared.image = NCMainCommonImages.cellSharedImage
  302. } else if (tableShare != nil && tableShare!.shareType == 3) {
  303. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  304. } else if (tableShare != nil && tableShare!.shareType != 3) {
  305. cell.shared.image = NCMainCommonImages.cellSharedImage
  306. } else {
  307. cell.shared.image = NCMainCommonImages.cellCanShareImage
  308. }
  309. if metadata.ownerId != appDelegate.userID {
  310. // Load avatar
  311. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  312. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  313. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  314. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  315. cell.shared.image = avatar
  316. }
  317. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  318. if let avatar = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  319. cell.shared.image = avatar
  320. }
  321. } else {
  322. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  323. if errorCode == 0 && account == appDelegate.account {
  324. cell.shared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  325. }
  326. }
  327. }
  328. }
  329. }
  330. // Comment
  331. if metadata.commentsUnread {
  332. cell.comment.image = NCMainCommonImages.cellCommentImage
  333. cell.labelTitleTrailingConstraint.constant = 160
  334. } else {
  335. cell.labelTitleTrailingConstraint.constant = 110
  336. }
  337. // More Image
  338. cell.more.image = NCMainCommonImages.cellMoreImage
  339. // downloadFile Error
  340. if metadata.status == k_metadataStatusDownloadError {
  341. cell.status.image = UIImage.init(named: "statuserror")
  342. if metadata.sessionError.count == 0 {
  343. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  344. } else {
  345. cell.labelInfoFile.text = metadata.sessionError
  346. }
  347. }
  348. return cell
  349. } else {
  350. // TRASNFER
  351. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  352. cell.labelTitle.text = metadata.fileNameView
  353. var progress: CGFloat = 0.0
  354. var totalBytes: Double = 0.0
  355. //var totalBytesExpected : Double = 0
  356. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  357. if progressArray != nil && progressArray?.count == 3 {
  358. progress = progressArray?.object(at: 0) as! CGFloat
  359. totalBytes = progressArray?.object(at: 1) as! Double
  360. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  361. }
  362. // Write status on Label Info
  363. switch metadata.status {
  364. case Int(k_metadataStatusWaitDownload):
  365. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  366. progress = 0.0
  367. break
  368. case Int(k_metadataStatusInDownload):
  369. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  370. progress = 0.0
  371. break
  372. case Int(k_metadataStatusDownloading):
  373. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  374. break
  375. case Int(k_metadataStatusWaitUpload):
  376. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  377. progress = 0.0
  378. break
  379. case Int(k_metadataStatusInUpload):
  380. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  381. progress = 0.0
  382. break
  383. case Int(k_metadataStatusUploading):
  384. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  385. break
  386. default:
  387. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  388. progress = 0.0
  389. }
  390. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  391. if iconFileExists {
  392. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  393. } else {
  394. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  395. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudUpload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  396. } else {
  397. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudDownload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  398. }
  399. }
  400. // uploadFileError
  401. if metadata.status == k_metadataStatusUploadError {
  402. cell.status.image = UIImage.init(named: "statuserror")
  403. if metadata.sessionError.count == 0 {
  404. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  405. } else {
  406. cell.labelInfoFile.text = metadata.sessionError
  407. }
  408. }
  409. // Progress
  410. cell.transferButton.progress = progress
  411. // User
  412. if metadata.account != appDelegate.account {
  413. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  414. if tableAccount != nil {
  415. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, urlBase: tableAccount!.urlBase) + "-" + tableAccount!.user + ".png"
  416. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  417. if avatar != nil {
  418. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  419. let imageSize = avatarImageView?.bounds.size
  420. UIGraphicsBeginImageContext(imageSize!)
  421. let context = UIGraphicsGetCurrentContext()
  422. avatarImageView?.layer.render(in: context!)
  423. avatar = UIGraphicsGetImageFromCurrentImageContext()
  424. UIGraphicsEndImageContext()
  425. cell.user.image = avatar
  426. }
  427. }
  428. }
  429. return cell
  430. }
  431. }
  432. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  433. guard let indexPath = indexPath else {
  434. return nil
  435. }
  436. guard let sectionDataSource = sectionDataSource else {
  437. return nil
  438. }
  439. let section = indexPath.section + 1
  440. let row = indexPath.row + 1
  441. let totSections = sectionDataSource.sections.count
  442. if totSections < section || section > totSections {
  443. return nil
  444. }
  445. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  446. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  447. return nil
  448. }
  449. let totRows = filesID.count
  450. if totRows < row || row > totRows {
  451. return nil
  452. }
  453. let ocId = filesID.object(at: indexPath.row)
  454. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  455. return metadata
  456. }
  457. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  458. if view is UICollectionView {
  459. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  460. }
  461. if view is UITableView {
  462. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  463. }
  464. return true
  465. }
  466. //MARK: - download Open Selector
  467. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  468. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  469. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  470. } else {
  471. NCNetworking.shared.download(metadata: metadata, selector: selector) { (_) in }
  472. }
  473. }
  474. //MARK: - OpenIn
  475. func openIn(fileURL: URL, selector: String?) {
  476. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  477. docController = UIDocumentInteractionController(url: fileURL)
  478. docController?.delegate = self
  479. if selector == selectorOpenInDetail {
  480. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  481. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  482. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  483. } else {
  484. guard let splitViewController = appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  485. return }
  486. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  487. }
  488. }
  489. //MARK: - OpenShare
  490. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  491. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  492. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  493. shareViewController.metadata = metadata
  494. shareViewController.indexPage = indexPage
  495. shareNavigationController.modalPresentationStyle = .formSheet
  496. ViewController.present(shareNavigationController, animated: true, completion: nil)
  497. }
  498. //MARK: - NCAudioRecorder
  499. func startAudioRecorder() {
  500. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  501. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  502. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  503. viewController.delegate = self
  504. viewController.createRecorder(fileName: fileName)
  505. viewController.modalTransitionStyle = .crossDissolve
  506. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  507. appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  508. }
  509. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  510. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  511. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  512. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  513. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  514. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  515. appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  516. }
  517. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  518. }
  519. }
  520. //MARK: - Main TabBarController
  521. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  522. override func viewDidLoad() {
  523. super.viewDidLoad()
  524. delegate = self
  525. }
  526. //Delegate methods
  527. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  528. let tabViewControllers = tabBarController.viewControllers!
  529. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  530. if let vc = viewController as? UINavigationController {
  531. vc.popToRootViewController(animated: true);
  532. }
  533. return false
  534. }
  535. animateToTab(toIndex: toIndex)
  536. return true
  537. }
  538. func animateToTab(toIndex: Int) {
  539. let tabViewControllers = viewControllers!
  540. let fromView = selectedViewController!.view!
  541. let toView = tabViewControllers[toIndex].view!
  542. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  543. guard fromIndex != toIndex else {return}
  544. // Add the toView to the tab bar view
  545. fromView.superview?.addSubview(toView)
  546. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  547. // Position toView off screen (to the left/right of fromView)
  548. let screenWidth = UIScreen.main.bounds.size.width;
  549. let scrollRight = toIndex > fromIndex!;
  550. let offset = (scrollRight ? screenWidth : -screenWidth)
  551. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  552. // Disable interaction during animation
  553. view.isUserInteractionEnabled = false
  554. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  555. // Slide the views by -offset
  556. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  557. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  558. }, completion: { finished in
  559. // Remove the old view from the tabbar view.
  560. fromView.removeFromSuperview()
  561. self.selectedIndex = toIndex
  562. self.view.isUserInteractionEnabled = true
  563. })
  564. }
  565. }