NCMainCommon.swift 49 KB

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