NCMainCommon.swift 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 sharedInstance: 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 cellFolderEncryptedImage = UIImage()
  45. static var cellFolderSharedWithMeImage = UIImage()
  46. static var cellFolderPublicImage = UIImage()
  47. static var cellFolderGroupImage = UIImage()
  48. static var cellFolderExternalImage = UIImage()
  49. static var cellFolderAutomaticUploadImage = UIImage()
  50. static var cellFolderImage = UIImage()
  51. static var cellPlayImage = UIImage()
  52. }
  53. @objc func createImagesThemingColor() {
  54. NCMainCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  55. NCMainCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  56. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  57. NCMainCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  58. NCMainCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  59. NCMainCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  60. NCMainCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  61. NCMainCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  62. NCMainCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  63. NCMainCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  64. NCMainCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  65. NCMainCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  66. NCMainCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  67. NCMainCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  68. }
  69. //MARK: -
  70. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  71. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  72. if viewController.viewIfLoaded?.window == nil {
  73. return
  74. }
  75. guard let dic = notification.userInfo else {
  76. return
  77. }
  78. let account = dic["account"] as? NSString ?? ""
  79. let ocId = dic["ocId"] as? NSString ?? ""
  80. let serverUrl = dic["serverUrl"] as? String ?? ""
  81. let status = dic["status"] as? Int ?? Int(k_metadataStatusNormal)
  82. let progress = dic["progress"] as? CGFloat ?? 0
  83. let totalBytes = dic["totalBytes"] as? Double ?? 0
  84. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  85. if (account != appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  86. return
  87. }
  88. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  89. return
  90. }
  91. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  92. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  93. return
  94. }
  95. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  96. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  97. var image = ""
  98. if status == k_metadataStatusInDownload {
  99. image = "↓"
  100. } else if status == k_metadataStatusInUpload {
  101. image = "↑"
  102. }
  103. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  104. cell.transferButton?.progress = progress
  105. }
  106. }
  107. }
  108. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool, uploadStatusForcedStart: Bool) {
  109. if metadata.session.count == 0 {
  110. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  111. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  112. return
  113. }
  114. let metadata = tableMetadata.init(value: metadata)
  115. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  116. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  117. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  118. NCNetworking.shared.cancelUpload(ocId: metadata.ocId)
  119. } else {
  120. var session: URLSession?
  121. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackground {
  122. session = NCCommunicationBackground.shared.sessionManagerTransfer
  123. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan {
  124. session = NCCommunicationBackground.shared.sessionManagerTransferWWan
  125. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierExtension {
  126. session = NCCommunicationBackground.shared.sessionManagerTransferExtension
  127. }
  128. session!.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  129. var cancel = false
  130. if metadata.session.count > 0 && metadata.session.contains("upload") {
  131. for task in uploadTasks {
  132. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  133. if uploadStatusForcedStart {
  134. metadata.status = Int(k_metadataStatusUploadForcedStart)
  135. NCManageDatabase.sharedInstance.addMetadata(metadata)
  136. }
  137. task.cancel()
  138. cancel = true
  139. }
  140. }
  141. if cancel == false {
  142. do {
  143. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  144. }
  145. catch { }
  146. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  147. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  148. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  149. }
  150. }
  151. }
  152. }
  153. }
  154. }
  155. @objc func cancelAllTransfer() {
  156. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  157. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  158. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  159. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  160. let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d", k_metadataStatusNormal), sorted: "fileName", ascending: true)
  161. for metadata in metadatas {
  162. // Modify
  163. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  164. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal))
  165. }
  166. // Cancel Task
  167. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  168. self.cancelTransferMetadata(metadata, reloadDatasource: false, uploadStatusForcedStart: false)
  169. }
  170. }
  171. }
  172. NCOperationQueue.shared.downloadCancelAll()
  173. }
  174. //MARK: -
  175. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectocId: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool, shares: [tableShare]?, source: UIViewController) {
  176. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  177. var tableShare: tableShare?
  178. // Share
  179. if shares != nil {
  180. for share in shares! {
  181. if share.fileName == metadata.fileName {
  182. tableShare = share
  183. break
  184. }
  185. }
  186. }
  187. // Download preview
  188. if downloadThumbnail {
  189. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: appDelegate.activeUrl, view: collectionView, indexPath: indexPath)
  190. }
  191. var isShare = false
  192. var isMounted = false
  193. if metadataFolder != nil {
  194. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  195. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  196. }
  197. if cell is NCListCell {
  198. let cell = cell as! NCListCell
  199. cell.delegate = source as? NCListCellDelegate
  200. cell.objectId = metadata.ocId
  201. cell.indexPath = indexPath
  202. cell.labelTitle.text = metadata.fileNameView
  203. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  204. cell.imageStatus.image = nil
  205. cell.imageLocal.image = nil
  206. cell.imageFavorite.image = nil
  207. cell.shared.image = nil
  208. if metadata.directory {
  209. if metadata.e2eEncrypted {
  210. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  211. } else if isShare {
  212. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  213. } else if (tableShare != nil && tableShare!.shareType != 3) {
  214. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  215. } else if (tableShare != nil && tableShare!.shareType == 3) {
  216. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  217. } else if metadata.mountType == "group" {
  218. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  219. } else if isMounted {
  220. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  221. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  222. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  223. } else {
  224. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  225. }
  226. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  227. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  228. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  229. // Local image: offline
  230. if tableDirectory != nil && tableDirectory!.offline {
  231. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  232. }
  233. } else {
  234. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  235. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  236. } else if(!metadata.hasPreview) {
  237. if metadata.iconName.count > 0 {
  238. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  239. } else {
  240. cell.imageItem.image = UIImage.init(named: "file")
  241. }
  242. }
  243. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  244. // image local
  245. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  246. if size > 0 {
  247. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  248. if tableLocalFile == nil && size == metadata.size {
  249. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  250. }
  251. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  252. else { cell.imageLocal.image = UIImage.init(named: "local") }
  253. }
  254. }
  255. // image Favorite
  256. if metadata.favorite {
  257. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  258. }
  259. // Share image
  260. if (isShare) {
  261. cell.shared.image = NCMainCommonImages.cellSharedImage
  262. } else if (tableShare != nil && tableShare!.shareType == 3) {
  263. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  264. } else if (tableShare != nil && tableShare!.shareType != 3) {
  265. cell.shared.image = NCMainCommonImages.cellSharedImage
  266. } else {
  267. cell.shared.image = NCMainCommonImages.cellCanShareImage
  268. }
  269. if metadata.ownerId != appDelegate.activeUserID {
  270. // Load avatar
  271. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  272. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  273. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  274. cell.shared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  275. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  276. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  277. } else {
  278. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  279. if errorCode == 0 && account == appDelegate.activeAccount {
  280. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  281. }
  282. }
  283. }
  284. }
  285. if isEditMode {
  286. cell.imageItemLeftConstraint.constant = 45
  287. cell.imageSelect.isHidden = false
  288. if selectocId.contains(metadata.ocId) {
  289. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  290. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  291. } else {
  292. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  293. cell.backgroundView = nil
  294. }
  295. } else {
  296. cell.imageItemLeftConstraint.constant = 10
  297. cell.imageSelect.isHidden = true
  298. cell.backgroundView = nil
  299. }
  300. // Remove last separator
  301. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  302. cell.separator.isHidden = true
  303. } else {
  304. cell.separator.isHidden = false
  305. }
  306. } else if cell is NCGridCell {
  307. let cell = cell as! NCGridCell
  308. cell.delegate = source as? NCGridCellDelegate
  309. cell.objectId = metadata.ocId
  310. cell.indexPath = indexPath
  311. cell.labelTitle.text = metadata.fileNameView
  312. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  313. cell.imageStatus.image = nil
  314. cell.imageLocal.image = nil
  315. cell.imageFavorite.image = nil
  316. if metadata.directory {
  317. if metadata.e2eEncrypted {
  318. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  319. } else if isShare {
  320. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  321. } else if (tableShare != nil && tableShare!.shareType != 3) {
  322. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  323. } else if (tableShare != nil && tableShare!.shareType == 3) {
  324. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  325. } else if metadata.mountType == "group" {
  326. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  327. } else if isMounted {
  328. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  329. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  330. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  331. } else {
  332. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  333. }
  334. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  335. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  336. // Local image: offline
  337. if tableDirectory != nil && tableDirectory!.offline {
  338. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  339. }
  340. } else {
  341. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  342. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  343. } else if(!metadata.hasPreview) {
  344. if metadata.iconName.count > 0 {
  345. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  346. } else {
  347. cell.imageItem.image = UIImage.init(named: "file")
  348. }
  349. }
  350. // image Local
  351. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  352. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  353. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  354. else { cell.imageLocal.image = UIImage.init(named: "local") }
  355. }
  356. }
  357. // image Favorite
  358. if metadata.favorite {
  359. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  360. }
  361. if isEditMode {
  362. cell.imageSelect.isHidden = false
  363. if selectocId.contains(metadata.ocId) {
  364. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  365. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  366. } else {
  367. cell.imageSelect.isHidden = true
  368. cell.backgroundView = nil
  369. }
  370. } else {
  371. cell.imageSelect.isHidden = true
  372. cell.backgroundView = nil
  373. }
  374. }
  375. }
  376. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?) -> UITableViewCell {
  377. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  378. // Create File System
  379. if metadata.directory {
  380. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  381. } else {
  382. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  383. }
  384. // CCCell
  385. if metadata.status == k_metadataStatusNormal || metadata.status == k_metadataStatusDownloadError {
  386. // NORMAL
  387. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  388. cell.labelTitle.text = metadata.fileNameView
  389. cell.filePreviewImageView.image = nil
  390. cell.filePreviewImageView.backgroundColor = UIColor.lightGray
  391. // Download preview
  392. if !(metadataFolder?.e2eEncrypted ?? false) {
  393. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: appDelegate.activeUrl, view: tableView, indexPath: indexPath)
  394. }
  395. // Share
  396. var isShare = false
  397. var isMounted = false
  398. if metadataFolder != nil {
  399. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  400. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  401. }
  402. if metadata.directory {
  403. // lable Info
  404. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  405. cell.file.backgroundColor = nil
  406. // File Image & Image Title Segue
  407. if metadata.e2eEncrypted {
  408. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  409. } else if isShare {
  410. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  411. } else if (tableShare != nil && tableShare!.shareType != 3) {
  412. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  413. } else if (tableShare != nil && tableShare!.shareType == 3) {
  414. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  415. } else if metadata.mountType == "group" {
  416. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  417. } else if isMounted {
  418. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  419. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  420. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  421. } else {
  422. cell.file.image = NCMainCommonImages.cellFolderImage
  423. }
  424. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  425. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  426. // Local image: offline
  427. if tableDirectory != nil && tableDirectory!.offline {
  428. cell.local.image = UIImage.init(named: "offlineFlag")
  429. }
  430. } else {
  431. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  432. // Lable Info
  433. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  434. // File Image
  435. if iconFileExists {
  436. cell.file.backgroundColor = nil
  437. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  438. } else if(!metadata.hasPreview){
  439. cell.file.backgroundColor = nil
  440. if metadata.iconName.count > 0 {
  441. cell.file.image = UIImage.init(named: metadata.iconName)
  442. } else {
  443. cell.file.image = UIImage.init(named: "file")
  444. }
  445. }
  446. // Local Image - Offline
  447. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  448. if size > 0 {
  449. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  450. if tableLocalFile == nil && size == metadata.size {
  451. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  452. }
  453. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  454. else { cell.local.image = UIImage.init(named: "local") }
  455. }
  456. // Status image: encrypted
  457. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  458. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  459. cell.status.image = UIImage.init(named: "encrypted")
  460. }
  461. }
  462. //
  463. // File & Directory
  464. //
  465. // Favorite
  466. if metadata.favorite {
  467. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  468. }
  469. // Share image
  470. if !(metadataFolder?.e2eEncrypted ?? false) && !metadata.e2eEncrypted {
  471. if (isShare) {
  472. cell.shared.image = NCMainCommonImages.cellSharedImage
  473. } else if (tableShare != nil && tableShare!.shareType == 3) {
  474. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  475. } else if (tableShare != nil && tableShare!.shareType != 3) {
  476. cell.shared.image = NCMainCommonImages.cellSharedImage
  477. } else {
  478. cell.shared.image = NCMainCommonImages.cellCanShareImage
  479. }
  480. if metadata.ownerId != appDelegate.activeUserID {
  481. // Load avatar
  482. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  483. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  484. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  485. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  486. cell.shared.image = avatar
  487. }
  488. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  489. if let avatar = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  490. cell.shared.image = avatar
  491. }
  492. } else {
  493. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  494. if errorCode == 0 && account == appDelegate.activeAccount {
  495. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  496. }
  497. }
  498. }
  499. }
  500. }
  501. // Comment
  502. if metadata.commentsUnread {
  503. cell.comment.image = NCMainCommonImages.cellCommentImage
  504. cell.labelTitleTrailingConstraint.constant = 160
  505. } else {
  506. cell.labelTitleTrailingConstraint.constant = 110
  507. }
  508. // More Image
  509. cell.more.image = NCMainCommonImages.cellMoreImage
  510. // downloadFile Error
  511. if metadata.status == k_metadataStatusDownloadError {
  512. cell.status.image = UIImage.init(named: "statuserror")
  513. if metadata.sessionError.count == 0 {
  514. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  515. } else {
  516. cell.labelInfoFile.text = metadata.sessionError
  517. }
  518. }
  519. return cell
  520. } else {
  521. // TRASNFER
  522. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  523. cell.labelTitle.text = metadata.fileNameView
  524. var progress: CGFloat = 0.0
  525. var totalBytes: Double = 0.0
  526. //var totalBytesExpected : Double = 0
  527. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  528. if progressArray != nil && progressArray?.count == 3 {
  529. progress = progressArray?.object(at: 0) as! CGFloat
  530. totalBytes = progressArray?.object(at: 1) as! Double
  531. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  532. }
  533. // Write status on Label Info
  534. switch metadata.status {
  535. case Int(k_metadataStatusWaitDownload):
  536. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  537. progress = 0.0
  538. break
  539. case Int(k_metadataStatusInDownload):
  540. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  541. progress = 0.0
  542. break
  543. case Int(k_metadataStatusDownloading):
  544. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  545. break
  546. case Int(k_metadataStatusWaitUpload):
  547. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  548. progress = 0.0
  549. break
  550. case Int(k_metadataStatusInUpload):
  551. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  552. progress = 0.0
  553. break
  554. case Int(k_metadataStatusUploading):
  555. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  556. break
  557. default:
  558. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  559. progress = 0.0
  560. }
  561. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  562. if iconFileExists {
  563. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  564. } else {
  565. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  566. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudUpload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  567. } else {
  568. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudDownload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  569. }
  570. }
  571. // uploadFileError
  572. if metadata.status == k_metadataStatusUploadError {
  573. cell.status.image = UIImage.init(named: "statuserror")
  574. if metadata.sessionError.count == 0 {
  575. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  576. } else {
  577. cell.labelInfoFile.text = metadata.sessionError
  578. }
  579. }
  580. // Progress
  581. cell.transferButton.progress = progress
  582. // User
  583. if metadata.account != appDelegate.activeAccount {
  584. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  585. if tableAccount != nil {
  586. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  587. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  588. if avatar != nil {
  589. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  590. let imageSize = avatarImageView?.bounds.size
  591. UIGraphicsBeginImageContext(imageSize!)
  592. let context = UIGraphicsGetCurrentContext()
  593. avatarImageView?.layer.render(in: context!)
  594. avatar = UIGraphicsGetImageFromCurrentImageContext()
  595. UIGraphicsEndImageContext()
  596. cell.user.image = avatar
  597. }
  598. }
  599. }
  600. return cell
  601. }
  602. }
  603. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  604. guard let indexPath = indexPath else {
  605. return nil
  606. }
  607. guard let sectionDataSource = sectionDataSource else {
  608. return nil
  609. }
  610. let section = indexPath.section + 1
  611. let row = indexPath.row + 1
  612. let totSections = sectionDataSource.sections.count
  613. if totSections < section || section > totSections {
  614. return nil
  615. }
  616. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  617. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  618. return nil
  619. }
  620. let totRows = filesID.count
  621. if totRows < row || row > totRows {
  622. return nil
  623. }
  624. let ocId = filesID.object(at: indexPath.row)
  625. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  626. return metadata
  627. }
  628. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  629. if view is UICollectionView {
  630. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  631. }
  632. if view is UITableView {
  633. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  634. }
  635. return true
  636. }
  637. //MARK: - download Open Selector
  638. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  639. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  640. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  641. } else {
  642. NCNetworking.shared.download(metadata: metadata, selector: selector) { (_) in }
  643. }
  644. }
  645. //MARK: - OpenIn
  646. func openIn(fileURL: URL, selector: String?) {
  647. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  648. docController = UIDocumentInteractionController(url: fileURL)
  649. docController?.delegate = self
  650. if selector == selectorOpenInDetail {
  651. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  652. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  653. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  654. } else {
  655. guard let splitViewController = appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  656. return }
  657. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  658. }
  659. }
  660. //MARK: - OpenShare
  661. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  662. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  663. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  664. shareViewController.metadata = metadata
  665. shareViewController.indexPage = indexPage
  666. shareNavigationController.modalPresentationStyle = .formSheet
  667. ViewController.present(shareNavigationController, animated: true, completion: nil)
  668. }
  669. //MARK: - NCAudioRecorder
  670. func startAudioRecorder() {
  671. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  672. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  673. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  674. viewController.delegate = self
  675. viewController.createRecorder(fileName: fileName)
  676. viewController.modalTransitionStyle = .crossDissolve
  677. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  678. appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  679. }
  680. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  681. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  682. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  683. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  684. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  685. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  686. appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  687. }
  688. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  689. }
  690. }
  691. //MARK: - Main TabBarController
  692. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  693. override func viewDidLoad() {
  694. super.viewDidLoad()
  695. delegate = self
  696. }
  697. //Delegate methods
  698. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  699. let tabViewControllers = tabBarController.viewControllers!
  700. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  701. if let vc = viewController as? UINavigationController {
  702. vc.popToRootViewController(animated: true);
  703. }
  704. return false
  705. }
  706. animateToTab(toIndex: toIndex)
  707. return true
  708. }
  709. func animateToTab(toIndex: Int) {
  710. let tabViewControllers = viewControllers!
  711. let fromView = selectedViewController!.view!
  712. let toView = tabViewControllers[toIndex].view!
  713. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  714. guard fromIndex != toIndex else {return}
  715. // Add the toView to the tab bar view
  716. fromView.superview?.addSubview(toView)
  717. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  718. // Position toView off screen (to the left/right of fromView)
  719. let screenWidth = UIScreen.main.bounds.size.width;
  720. let scrollRight = toIndex > fromIndex!;
  721. let offset = (scrollRight ? screenWidth : -screenWidth)
  722. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  723. // Disable interaction during animation
  724. view.isUserInteractionEnabled = false
  725. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  726. // Slide the views by -offset
  727. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  728. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  729. }, completion: { finished in
  730. // Remove the old view from the tabbar view.
  731. fromView.removeFromSuperview()
  732. self.selectedIndex = toIndex
  733. self.view.isUserInteractionEnabled = true
  734. })
  735. }
  736. }