NCMainCommon.swift 34 KB

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