NCMainCommon.swift 47 KB

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