NCMainCommon.swift 47 KB

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