NCCollectionViewCommon.swift 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  1. //
  2. // NCCollectionViewCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/09/2020.
  6. // Copyright © 2020 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 NCCommunication
  25. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. internal let refreshControl = UIRefreshControl()
  29. internal var searchController: UISearchController?
  30. internal var emptyDataSet: NCEmptyDataSet?
  31. internal var serverUrl: String = ""
  32. internal var isEncryptedFolder = false
  33. internal var isEditMode = false
  34. internal var selectOcId: [String] = []
  35. internal var metadatasSource: [tableMetadata] = []
  36. internal var metadataFolder: tableMetadata?
  37. internal var metadataTouch: tableMetadata?
  38. internal var dataSource = NCDataSource()
  39. internal var richWorkspaceText: String?
  40. internal var layout = ""
  41. internal var sort: String = ""
  42. internal var ascending: Bool = true
  43. internal var directoryOnTop: Bool = true
  44. internal var groupBy = ""
  45. internal var titleButton = ""
  46. internal var itemForLine = 0
  47. private var autoUploadFileName = ""
  48. private var autoUploadDirectory = ""
  49. internal var listLayout: NCListLayout!
  50. internal var gridLayout: NCGridLayout!
  51. private let headerHeight: CGFloat = 50
  52. private var headerRichWorkspaceHeight: CGFloat = 0
  53. private let footerHeight: CGFloat = 100
  54. private var timerInputSearch: Timer?
  55. internal var literalSearch: String?
  56. internal var isSearching: Bool = false
  57. internal var isReloadDataSourceNetworkInProgress: Bool = false
  58. var selectedIndexPath: IndexPath!
  59. // DECLARE
  60. internal var layoutKey = ""
  61. internal var titleCurrentFolder = ""
  62. internal var enableSearchBar: Bool = false
  63. internal var emptyImage: UIImage?
  64. internal var emptyTitle: String = ""
  65. internal var emptyDescription: String = ""
  66. required init?(coder aDecoder: NSCoder) {
  67. super.init(coder: aDecoder)
  68. }
  69. override func viewDidLoad() {
  70. super.viewDidLoad()
  71. self.navigationController?.presentationController?.delegate = self
  72. if enableSearchBar {
  73. searchController = UISearchController(searchResultsController: nil)
  74. searchController?.searchResultsUpdater = self
  75. searchController?.obscuresBackgroundDuringPresentation = false
  76. searchController?.delegate = self
  77. searchController?.searchBar.delegate = self
  78. navigationItem.searchController = searchController
  79. navigationItem.hidesSearchBarWhenScrolling = false
  80. }
  81. // Cell
  82. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  83. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  84. collectionView.register(UINib.init(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  85. // Header
  86. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  87. // Footer
  88. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  89. collectionView.alwaysBounceVertical = true
  90. listLayout = NCListLayout()
  91. gridLayout = NCGridLayout()
  92. // Refresh Control
  93. collectionView.addSubview(refreshControl)
  94. refreshControl.tintColor = .gray
  95. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  96. // Empty
  97. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 0, delegate: self)
  98. // Long Press on CollectionView
  99. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  100. longPressedGesture.minimumPressDuration = 0.5
  101. longPressedGesture.delegate = self
  102. longPressedGesture.delaysTouchesBegan = true
  103. collectionView.addGestureRecognizer(longPressedGesture)
  104. // Notification
  105. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterInitializeMain), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterChangeTheming), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterReloadDataSource), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterDeleteFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterMoveFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterCopyFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterRenameFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterCreateFolder), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterFavoriteFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterDownloadedFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterUploadStartFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterUploadedFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterProgressTask), object:nil)
  124. changeTheming()
  125. }
  126. override func viewWillAppear(_ animated: Bool) {
  127. super.viewWillAppear(animated)
  128. appDelegate.activeViewController = self
  129. if serverUrl == "" {
  130. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  131. } else {
  132. appDelegate.activeServerUrl = serverUrl
  133. }
  134. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  135. gridLayout.itemForLine = CGFloat(itemForLine)
  136. if layout == NCBrandGlobal.shared.layoutList {
  137. collectionView?.collectionViewLayout = listLayout
  138. } else {
  139. collectionView?.collectionViewLayout = gridLayout
  140. }
  141. navigationController?.navigationBar.prefersLargeTitles = true
  142. navigationController?.setNavigationBarHidden(false, animated: true)
  143. setNavigationItem()
  144. reloadDataSource()
  145. }
  146. override func viewDidAppear(_ animated: Bool) {
  147. super.viewDidAppear(animated)
  148. reloadDataSourceNetwork()
  149. }
  150. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  151. let viewController = presentationController.presentedViewController
  152. if viewController is NCViewerRichWorkspaceWebView {
  153. closeRichWorkspaceWebView()
  154. } else if viewController is UINavigationController {
  155. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  156. appDelegate.activeFileViewInFolder = nil
  157. }
  158. }
  159. }
  160. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  161. super.viewWillTransition(to: size, with: coordinator)
  162. coordinator.animate(alongsideTransition: nil) { _ in
  163. self.collectionView?.collectionViewLayout.invalidateLayout()
  164. }
  165. }
  166. override var canBecomeFirstResponder: Bool {
  167. return true
  168. }
  169. func setNavigationItem() {
  170. if isEditMode {
  171. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  172. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  173. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  174. } else {
  175. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  176. navigationItem.leftBarButtonItem = nil
  177. navigationItem.title = titleCurrentFolder
  178. }
  179. }
  180. // MARK: - NotificationCenter
  181. @objc func initializeMain() {
  182. if appDelegate.account == nil || appDelegate.account.count == 0 { return }
  183. if searchController?.isActive ?? false {
  184. searchController?.isActive = false
  185. }
  186. // set active serverUrl
  187. if self.view?.window != nil {
  188. if serverUrl == "" {
  189. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  190. } else {
  191. appDelegate.activeServerUrl = serverUrl
  192. }
  193. }
  194. self.navigationController?.popToRootViewController(animated: false)
  195. appDelegate.listFilesVC.removeAllObjects()
  196. appDelegate.listFavoriteVC.removeAllObjects()
  197. appDelegate.listOfflineVC.removeAllObjects()
  198. reloadDataSource()
  199. }
  200. @objc func changeTheming() {
  201. view.backgroundColor = NCBrandColor.shared.backgroundView
  202. collectionView.backgroundColor = NCBrandColor.shared.backgroundView
  203. collectionView.reloadData()
  204. }
  205. @objc func reloadDataSource(_ notification: NSNotification) {
  206. if self.view?.window == nil { return }
  207. reloadDataSource()
  208. }
  209. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  210. if self.view?.window == nil { return }
  211. if let userInfo = notification.userInfo as NSDictionary? {
  212. if let serverUrl = userInfo["serverUrl"] as? String {
  213. if serverUrl == self.serverUrl {
  214. reloadDataSourceNetwork(forced: true)
  215. }
  216. }
  217. } else {
  218. reloadDataSourceNetwork(forced: true)
  219. }
  220. }
  221. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  222. if self.view?.window == nil { return }
  223. reloadDataSource()
  224. }
  225. @objc func closeRichWorkspaceWebView() {
  226. if self.view?.window == nil { return }
  227. reloadDataSourceNetwork()
  228. }
  229. @objc func deleteFile(_ notification: NSNotification) {
  230. if self.view?.window == nil { return }
  231. if let userInfo = notification.userInfo as NSDictionary? {
  232. if let ocId = userInfo["ocId"] as? String, let fileNameView = userInfo["fileNameView"] as? String, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  233. if onlyLocal {
  234. reloadDataSource()
  235. } else if fileNameView.lowercased() == NCBrandGlobal.shared.fileNameRichWorkspace.lowercased() {
  236. reloadDataSourceNetwork(forced: true)
  237. } else {
  238. if let row = dataSource.deleteMetadata(ocId: ocId) {
  239. let indexPath = IndexPath(row: row, section: 0)
  240. collectionView?.performBatchUpdates({
  241. collectionView?.deleteItems(at: [indexPath])
  242. }, completion: { (_) in
  243. self.collectionView?.reloadData()
  244. })
  245. }
  246. }
  247. }
  248. }
  249. }
  250. @objc func moveFile(_ notification: NSNotification) {
  251. if self.view?.window == nil { return }
  252. if let userInfo = notification.userInfo as NSDictionary? {
  253. if let ocId = userInfo["ocId"] as? String, let serverUrlFrom = userInfo["serverUrlFrom"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  254. // DEL
  255. if serverUrlFrom == serverUrl && metadata.account == appDelegate.account {
  256. if let row = dataSource.deleteMetadata(ocId: ocId) {
  257. let indexPath = IndexPath(row: row, section: 0)
  258. collectionView?.performBatchUpdates({
  259. collectionView?.deleteItems(at: [indexPath])
  260. }, completion: { (_) in
  261. self.collectionView?.reloadData()
  262. })
  263. }
  264. // ADD
  265. } else if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  266. if let row = dataSource.addMetadata(metadata) {
  267. let indexPath = IndexPath(row: row, section: 0)
  268. collectionView?.performBatchUpdates({
  269. collectionView?.insertItems(at: [indexPath])
  270. }, completion: { (_) in
  271. self.collectionView?.reloadData()
  272. })
  273. }
  274. }
  275. }
  276. }
  277. }
  278. @objc func copyFile(_ notification: NSNotification) {
  279. if self.view?.window == nil { return }
  280. if let userInfo = notification.userInfo as NSDictionary? {
  281. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  282. if serverUrlTo == self.serverUrl {
  283. reloadDataSource()
  284. }
  285. }
  286. }
  287. }
  288. @objc func renameFile(_ notification: NSNotification) {
  289. if self.view?.window == nil { return }
  290. reloadDataSource()
  291. }
  292. @objc func createFolder(_ notification: NSNotification) {
  293. if self.view?.window == nil { return }
  294. if let userInfo = notification.userInfo as NSDictionary? {
  295. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  296. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  297. if let row = dataSource.addMetadata(metadata) {
  298. let indexPath = IndexPath(row: row, section: 0)
  299. collectionView?.performBatchUpdates({
  300. collectionView?.insertItems(at: [indexPath])
  301. }, completion: { (_) in
  302. self.collectionView?.reloadData()
  303. })
  304. }
  305. }
  306. }
  307. } else {
  308. reloadDataSourceNetwork()
  309. }
  310. }
  311. @objc func favoriteFile(_ notification: NSNotification) {
  312. if self.view?.window == nil { return }
  313. if let userInfo = notification.userInfo as NSDictionary? {
  314. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  315. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  316. reloadDataSource()
  317. }
  318. }
  319. }
  320. }
  321. @objc func downloadStartFile(_ notification: NSNotification) {
  322. if self.view?.window == nil { return }
  323. if let userInfo = notification.userInfo as NSDictionary? {
  324. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  325. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  326. let indexPath = IndexPath(row: row, section: 0)
  327. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  328. collectionView?.reloadItems(at: [indexPath])
  329. }
  330. }
  331. }
  332. }
  333. }
  334. @objc func downloadedFile(_ notification: NSNotification) {
  335. if self.view?.window == nil { return }
  336. if let userInfo = notification.userInfo as NSDictionary? {
  337. if let ocId = userInfo["ocId"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  338. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  339. let indexPath = IndexPath(row: row, section: 0)
  340. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  341. collectionView?.reloadItems(at: [indexPath])
  342. }
  343. }
  344. }
  345. }
  346. }
  347. @objc func downloadCancelFile(_ notification: NSNotification) {
  348. if self.view?.window == nil { return }
  349. if let userInfo = notification.userInfo as NSDictionary? {
  350. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  351. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  352. let indexPath = IndexPath(row: row, section: 0)
  353. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  354. collectionView?.reloadItems(at: [indexPath])
  355. }
  356. }
  357. }
  358. }
  359. }
  360. @objc func uploadStartFile(_ notification: NSNotification) {
  361. if self.view?.window == nil { return }
  362. if let userInfo = notification.userInfo as NSDictionary? {
  363. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  364. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  365. dataSource.addMetadata(metadata)
  366. self.collectionView?.reloadData()
  367. }
  368. }
  369. }
  370. }
  371. @objc func uploadedFile(_ notification: NSNotification) {
  372. if self.view?.window == nil { return }
  373. if let userInfo = notification.userInfo as NSDictionary? {
  374. if let ocId = userInfo["ocId"] as? String, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  375. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  376. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  377. collectionView?.reloadData()
  378. }
  379. }
  380. }
  381. }
  382. @objc func uploadCancelFile(_ notification: NSNotification) {
  383. if self.view?.window == nil { return }
  384. if let userInfo = notification.userInfo as NSDictionary? {
  385. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  386. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  387. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  388. let indexPath = IndexPath(row: row, section: 0)
  389. collectionView?.performBatchUpdates({
  390. collectionView?.deleteItems(at: [indexPath])
  391. }, completion: { (_) in
  392. self.collectionView?.reloadData()
  393. })
  394. } else {
  395. self.reloadDataSource()
  396. }
  397. }
  398. }
  399. }
  400. }
  401. @objc func triggerProgressTask(_ notification: NSNotification) {
  402. if self.view?.window == nil { return }
  403. if let userInfo = notification.userInfo as NSDictionary? {
  404. if let ocId = userInfo["ocId"] as? String {
  405. let _ = userInfo["account"] as? String ?? ""
  406. let _ = userInfo["serverUrl"] as? String ?? ""
  407. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  408. let progress = progressNumber.floatValue
  409. let status = userInfo["status"] as? Int ?? NCBrandGlobal.shared.metadataStatusNormal
  410. let totalBytes = userInfo["totalBytes"] as? Int64 ?? 0
  411. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64 ?? 0
  412. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  413. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  414. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  415. if cell is NCListCell {
  416. let cell = cell as! NCListCell
  417. if progress > 0 {
  418. cell.progressView?.isHidden = false
  419. cell.progressView?.progress = progress
  420. cell.setButtonMore(named: NCBrandGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  421. if status == NCBrandGlobal.shared.metadataStatusInDownload {
  422. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  423. } else if status == NCBrandGlobal.shared.metadataStatusInUpload {
  424. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  425. }
  426. }
  427. } else if cell is NCTransferCell {
  428. let cell = cell as! NCTransferCell
  429. if progress > 0 {
  430. cell.progressView?.isHidden = false
  431. cell.progressView?.progress = progress
  432. cell.setButtonMore(named: NCBrandGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  433. if status == NCBrandGlobal.shared.metadataStatusInDownload {
  434. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  435. } else if status == NCBrandGlobal.shared.metadataStatusInUpload {
  436. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  437. }
  438. }
  439. } else if cell is NCGridCell {
  440. let cell = cell as! NCGridCell
  441. if progress > 0 {
  442. cell.progressView.isHidden = false
  443. cell.progressView.progress = progress
  444. cell.setButtonMore(named: NCBrandGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  445. }
  446. }
  447. }
  448. }
  449. }
  450. }
  451. }
  452. // MARK: - Empty
  453. func emptyDataSetView(_ view: NCEmptyView) {
  454. if searchController?.isActive ?? false {
  455. view.emptyImage.image = UIImage.init(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  456. if isReloadDataSourceNetworkInProgress {
  457. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  458. } else {
  459. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  460. }
  461. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  462. } else if isReloadDataSourceNetworkInProgress {
  463. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  464. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  465. view.emptyDescription.text = ""
  466. } else {
  467. if serverUrl == "" {
  468. view.emptyImage.image = emptyImage
  469. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  470. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  471. } else {
  472. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  473. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  474. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  475. }
  476. }
  477. }
  478. // MARK: - SEARCH
  479. func updateSearchResults(for searchController: UISearchController) {
  480. timerInputSearch?.invalidate()
  481. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  482. literalSearch = searchController.searchBar.text
  483. collectionView?.reloadData()
  484. }
  485. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  486. isSearching = true
  487. metadatasSource.removeAll()
  488. reloadDataSource()
  489. }
  490. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  491. isSearching = false
  492. literalSearch = ""
  493. reloadDataSource()
  494. }
  495. // MARK: - TAP EVENT
  496. @objc func tapSelect(sender: Any) {
  497. isEditMode = !isEditMode
  498. selectOcId.removeAll()
  499. setNavigationItem()
  500. self.collectionView.reloadData()
  501. }
  502. func tapSwitchHeader(sender: Any) {
  503. if collectionView.collectionViewLayout == gridLayout {
  504. // list layout
  505. UIView.animate(withDuration: 0.0, animations: {
  506. self.collectionView.collectionViewLayout.invalidateLayout()
  507. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  508. self.collectionView.reloadData()
  509. })
  510. })
  511. layout = NCBrandGlobal.shared.layoutList
  512. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  513. } else {
  514. // grid layout
  515. UIView.animate(withDuration: 0.0, animations: {
  516. self.collectionView.collectionViewLayout.invalidateLayout()
  517. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  518. self.collectionView.reloadData()
  519. })
  520. })
  521. layout = NCBrandGlobal.shared.layoutGrid
  522. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  523. }
  524. }
  525. func tapOrderHeader(sender: Any) {
  526. let sortMenu = NCSortMenu()
  527. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  528. }
  529. @objc func tapSelectMenu(sender: Any) {
  530. guard let tabBarController = self.tabBarController else { return }
  531. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  532. }
  533. func tapMoreHeader(sender: Any) { }
  534. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  535. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  536. }
  537. func tapShareListItem(with objectId: String, sender: Any) {
  538. if isEditMode { return }
  539. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  540. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  541. }
  542. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  543. if isEditMode { return }
  544. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  545. if namedButtonMore == NCBrandGlobal.shared.buttonMoreMore {
  546. toggleMoreMenu(viewController: self, metadata: metadata)
  547. } else if namedButtonMore == NCBrandGlobal.shared.buttonMoreStop {
  548. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  549. }
  550. }
  551. func tapRichWorkspace(sender: Any) {
  552. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  553. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  554. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  555. viewerRichWorkspace.serverUrl = serverUrl
  556. navigationController.modalPresentationStyle = .fullScreen
  557. self.present(navigationController, animated: true, completion: nil)
  558. }
  559. }
  560. }
  561. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  562. }
  563. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  564. }
  565. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  566. }
  567. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  568. }
  569. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  570. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  571. }
  572. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  573. if gestureRecognizer.state != .began { return }
  574. if serverUrl == "" { return }
  575. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) {
  576. metadataTouch = metadata
  577. } else {
  578. metadataTouch = nil
  579. }
  580. var listMenuItems: [UIMenuItem] = []
  581. let touchPoint = gestureRecognizer.location(in: collectionView)
  582. becomeFirstResponder()
  583. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  584. if listMenuItems.count > 0 {
  585. UIMenuController.shared.menuItems = listMenuItems
  586. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  587. UIMenuController.shared.setMenuVisible(true, animated: true)
  588. }
  589. }
  590. // MARK: - Menu Item
  591. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  592. if (#selector(pasteFilesMenu(_:)) == action) {
  593. if UIPasteboard.general.items.count > 0 {
  594. return true
  595. }
  596. }
  597. return false
  598. }
  599. @objc func copyFileMenu(_ notification: Any) {
  600. var metadatas: [tableMetadata] = []
  601. var items = [[String : Any]]()
  602. if isEditMode {
  603. for ocId in selectOcId {
  604. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  605. metadatas.append(metadata)
  606. }
  607. }
  608. } else {
  609. guard let metadata = metadataTouch else { return }
  610. metadatas.append(metadata)
  611. }
  612. for metadata in metadatas {
  613. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  614. do {
  615. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  616. items.append([NCBrandGlobal.shared.metadataKeyedUnarchiver:etagPasteboard])
  617. } catch {
  618. print("error")
  619. }
  620. } else {
  621. NCNetworking.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorLoadCopy, setFavorite: false) { (_) in }
  622. }
  623. }
  624. UIPasteboard.general.setItems(items, options: [:])
  625. if isEditMode {
  626. tapSelect(sender: self)
  627. }
  628. }
  629. @objc func pasteFilesMenu(_ notification: Any) {
  630. var listData: [String] = []
  631. for item in UIPasteboard.general.items {
  632. for object in item {
  633. let contentType = object.key
  634. let data = object.value
  635. if contentType == NCBrandGlobal.shared.metadataKeyedUnarchiver {
  636. do {
  637. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  638. uploadPasteOcId(ocId)
  639. }
  640. } catch {
  641. print("error")
  642. }
  643. continue
  644. }
  645. if data is String {
  646. if listData.contains(data as! String) {
  647. continue
  648. } else {
  649. listData.append(data as! String)
  650. }
  651. }
  652. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  653. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  654. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  655. }
  656. }
  657. }
  658. }
  659. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  660. do {
  661. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  662. let ocId = UUID().uuidString
  663. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  664. if data is UIImage {
  665. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  666. } else if data is Data {
  667. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  668. } else if data is String {
  669. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  670. } else {
  671. return
  672. }
  673. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  674. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  675. metadataForUpload.sessionSelector = NCBrandGlobal.shared.selectorUploadFile
  676. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  677. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  678. NCManageDatabase.shared.addMetadata(metadataForUpload)
  679. } catch { }
  680. }
  681. private func uploadPasteOcId(_ ocId: String) {
  682. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  683. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  684. let fileNameView = NCUtilityFileSystem.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  685. let ocId = NSUUID().uuidString
  686. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  687. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  688. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  689. metadataForUpload.sessionSelector = NCBrandGlobal.shared.selectorUploadFile
  690. metadataForUpload.size = metadata.size
  691. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  692. NCManageDatabase.shared.addMetadata(metadataForUpload)
  693. }
  694. }
  695. }
  696. @objc func openQuickLookMenu(_ notification: Any) {
  697. guard let metadata = metadataTouch else { return }
  698. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  699. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCBrandGlobal.shared.selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  700. } else {
  701. NCNetworking.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorLoadFileQuickLook) { (_) in }
  702. }
  703. }
  704. @objc func openInMenu(_ notification: Any) {
  705. guard let metadata = metadataTouch else { return }
  706. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  707. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCBrandGlobal.shared.selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  708. } else {
  709. NCNetworking.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorOpenIn) { (_) in }
  710. }
  711. }
  712. // MARK: - DataSource + NC Endpoint
  713. @objc func reloadDataSource() {
  714. if appDelegate.account == nil || appDelegate.account.count == 0 { return }
  715. // Get richWorkspace Text
  716. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  717. richWorkspaceText = directory?.richWorkspace
  718. // E2EE
  719. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  720. // get auto upload folder
  721. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  722. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  723. // get layout for view
  724. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  725. }
  726. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  727. @objc func reloadDataSourceNetworkRefreshControl() {
  728. reloadDataSourceNetwork(forced: true)
  729. }
  730. @objc func networkSearch() {
  731. if appDelegate.account == nil || appDelegate.account.count == 0 { return }
  732. if literalSearch?.count ?? 0 > 1 {
  733. isReloadDataSourceNetworkInProgress = true
  734. collectionView?.reloadData()
  735. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  736. if self.searchController?.isActive ?? false && errorCode == 0 {
  737. self.metadatasSource = metadatas!
  738. }
  739. self.refreshControl.endRefreshing()
  740. self.isReloadDataSourceNetworkInProgress = false
  741. self.reloadDataSource()
  742. }
  743. } else {
  744. self.refreshControl.endRefreshing()
  745. }
  746. }
  747. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  748. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  749. if errorCode == 0 {
  750. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  751. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  752. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  753. if errorCode == 0 {
  754. self.metadataFolder = metadataFolder
  755. // E2EE
  756. if let metadataFolder = metadataFolder {
  757. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  758. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  759. if errorCode == 0 && e2eMetadata != nil {
  760. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  761. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorDecodeMetadata, forced: true)
  762. } else {
  763. self.reloadDataSource()
  764. }
  765. } else if errorCode != NCBrandGlobal.shared.ErrorResourceNotFound {
  766. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorDecodeMetadata, forced: true)
  767. }
  768. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  769. }
  770. } else {
  771. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  772. }
  773. } else {
  774. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  775. }
  776. } else {
  777. completion(nil, nil, errorCode, errorDescription)
  778. }
  779. }
  780. } else {
  781. completion(nil, nil, 0, "")
  782. }
  783. } else {
  784. completion(nil, nil, errorCode, errorDescription)
  785. }
  786. }
  787. }
  788. }
  789. // MARK: - Collection View
  790. extension NCCollectionViewCommon: UICollectionViewDelegate {
  791. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  792. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  793. metadataTouch = metadata
  794. selectedIndexPath = indexPath
  795. if isEditMode {
  796. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  797. selectOcId.remove(at: index)
  798. } else {
  799. selectOcId.append(metadata.ocId)
  800. }
  801. collectionView.reloadItems(at: [indexPath])
  802. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  803. return
  804. }
  805. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  806. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCBrandGlobal.shared.ErrorE2EENotEnabled, forced: true)
  807. return
  808. }
  809. if metadata.directory {
  810. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  811. // FILES
  812. if layoutKey == NCBrandGlobal.shared.layoutViewFiles {
  813. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  814. guard let vcFiles = (viewController as? NCFiles) else { return }
  815. if vcFiles.isViewLoaded {
  816. self.navigationController?.pushViewController(vcFiles, animated: true)
  817. }
  818. } else {
  819. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  820. vcFiles.isRoot = false
  821. vcFiles.serverUrl = serverUrlPush
  822. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  823. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  824. self.navigationController?.pushViewController(vcFiles, animated: true)
  825. }
  826. }
  827. // FAVORITE
  828. if layoutKey == NCBrandGlobal.shared.layoutViewFavorite {
  829. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  830. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  831. if vcFavorite.isViewLoaded {
  832. self.navigationController?.pushViewController(vcFavorite, animated: true)
  833. }
  834. } else {
  835. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  836. vcFavorite.serverUrl = serverUrlPush
  837. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  838. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  839. self.navigationController?.pushViewController(vcFavorite, animated: true)
  840. }
  841. }
  842. // OFFLINE
  843. if layoutKey == NCBrandGlobal.shared.layoutViewOffline {
  844. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  845. guard let vcOffline = (viewController as? NCOffline) else { return }
  846. if vcOffline.isViewLoaded {
  847. self.navigationController?.pushViewController(vcOffline, animated: true)
  848. }
  849. } else {
  850. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  851. vcOffline.serverUrl = serverUrlPush
  852. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  853. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  854. self.navigationController?.pushViewController(vcOffline, animated: true)
  855. }
  856. }
  857. // RECENT ( for push use Files ... he he he )
  858. if layoutKey == NCBrandGlobal.shared.layoutViewRecent {
  859. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  860. guard let vcFiles = (viewController as? NCFiles) else { return }
  861. if vcFiles.isViewLoaded {
  862. self.navigationController?.pushViewController(vcFiles, animated: true)
  863. }
  864. } else {
  865. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  866. vcFiles.isRoot = false
  867. vcFiles.serverUrl = serverUrlPush
  868. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  869. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  870. self.navigationController?.pushViewController(vcFiles, animated: true)
  871. }
  872. }
  873. //VIEW IN FOLDER
  874. if layoutKey == NCBrandGlobal.shared.layoutViewViewInFolder {
  875. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  876. vcFileViewInFolder.serverUrl = serverUrlPush
  877. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  878. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  879. }
  880. // SHARES ( for push use Files ... he he he )
  881. if layoutKey == NCBrandGlobal.shared.layoutViewShares {
  882. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  883. guard let vcFiles = (viewController as? NCFiles) else { return }
  884. if vcFiles.isViewLoaded {
  885. self.navigationController?.pushViewController(vcFiles, animated: true)
  886. }
  887. } else {
  888. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  889. vcFiles.isRoot = false
  890. vcFiles.serverUrl = serverUrlPush
  891. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  892. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  893. self.navigationController?.pushViewController(vcFiles, animated: true)
  894. }
  895. }
  896. } else {
  897. guard let metadataTouch = metadataTouch else { return }
  898. if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileAudio {
  899. var metadatas: [tableMetadata] = []
  900. for metadata in dataSource.metadatas {
  901. if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileAudio {
  902. metadatas.append(metadata)
  903. }
  904. }
  905. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  906. return
  907. }
  908. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  909. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  910. } else if NCCommunication.shared.isNetworkReachable() {
  911. NCNetworking.shared.download(metadata: metadataTouch, selector: NCBrandGlobal.shared.selectorLoadFileView) { (_) in }
  912. } else {
  913. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCBrandGlobal.shared.ErrorOffline, forced: true)
  914. }
  915. }
  916. }
  917. func collectionViewSelectAll() {
  918. selectOcId.removeAll()
  919. for metadata in metadatasSource {
  920. selectOcId.append(metadata.ocId)
  921. }
  922. collectionView.reloadData()
  923. }
  924. @available(iOS 13.0, *)
  925. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  926. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  927. metadataTouch = metadata
  928. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  929. return NCViewerPeekPop(metadata: metadata)
  930. }, actionProvider: { suggestedActions in
  931. let copy = UIAction(title: NSLocalizedString("_copy_file_", comment: ""), image: UIImage(systemName: "doc.on.doc") ) { action in
  932. }
  933. let paste = UIAction(title: NSLocalizedString("_paste_file_", comment: ""), image: UIImage(systemName: "doc.on.clipboard") ) { action in
  934. }
  935. let copyPaste = UIMenu(title: NSLocalizedString("_copy_paste_", comment: ""), image: UIImage(systemName: "doc"), children: [copy, paste])
  936. let detail = UIAction(title: NSLocalizedString("_details_", comment: ""), image: UIImage(systemName: "info") ) { action in
  937. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 0)
  938. }
  939. let save = UIAction(title: NSLocalizedString("_save_selected_files_", comment: ""), image: UIImage(systemName: "square.and.arrow.down")) { action in
  940. NCOperationQueue.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorSaveAlbum, setFavorite: false)
  941. }
  942. let openQuickLook = UIAction(title: NSLocalizedString("_open_quicklook_", comment: ""), image: UIImage(systemName: "eye")) { action in
  943. NCNetworkingNotificationCenter.shared.downloadOpen(metadata: metadata, selector: NCBrandGlobal.shared.selectorLoadFileQuickLook)
  944. }
  945. let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { action in
  946. NCNetworkingNotificationCenter.shared.downloadOpen(metadata: metadata, selector: NCBrandGlobal.shared.selectorOpenIn)
  947. }
  948. let moveCopy = UIAction(title: NSLocalizedString("_move_or_copy_", comment: ""), image: UIImage(systemName: "arrow.up.right.square")) { action in
  949. NCCollectionCommon.shared.openSelectView(items: [metadata])
  950. }
  951. let deleteConfirm = UIAction(title: NSLocalizedString("_delete_", comment: ""), image: UIImage(systemName: "trash"), attributes: .destructive) { action in
  952. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, onlyLocal: false) { (errorCode, errorDescription) in
  953. if errorCode != 0 {
  954. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  955. }
  956. }
  957. }
  958. let delete = UIMenu(title: NSLocalizedString("_delete_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirm])
  959. if metadata.directory {
  960. return UIMenu(title: "", children: [copyPaste, detail, moveCopy, delete])
  961. } else if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileVideo {
  962. return UIMenu(title: "", children: [copyPaste, detail, save, openQuickLook, openIn, moveCopy, delete])
  963. } else {
  964. return UIMenu(title: "", children: [copyPaste, detail, openQuickLook, openIn, moveCopy, delete])
  965. }
  966. })
  967. }
  968. }
  969. extension NCCollectionViewCommon: UICollectionViewDataSource {
  970. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  971. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  972. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  973. }
  974. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  975. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  976. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  977. }
  978. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  979. if kind == UICollectionView.elementKindSectionHeader {
  980. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  981. if collectionView.collectionViewLayout == gridLayout {
  982. header.buttonSwitch.setImage(UIImage.init(named: "switchList")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  983. } else {
  984. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  985. }
  986. header.delegate = self
  987. header.setStatusButton(count: dataSource.metadatas.count)
  988. header.setTitleSorted(datasourceTitleButton: titleButton)
  989. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  990. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  991. return header
  992. } else {
  993. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  994. let info = dataSource.getFilesInformation()
  995. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  996. return footer
  997. }
  998. }
  999. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1000. return 1
  1001. }
  1002. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1003. let numberItems = dataSource.numberOfItems()
  1004. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1005. return numberItems
  1006. }
  1007. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1008. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1009. if layout == NCBrandGlobal.shared.layoutList {
  1010. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1011. } else {
  1012. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1013. }
  1014. }
  1015. var tableShare: tableShare?
  1016. var isShare = false
  1017. var isMounted = false
  1018. if metadataFolder != nil {
  1019. isShare = metadata.permissions.contains(NCBrandGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCBrandGlobal.shared.permissionShared)
  1020. isMounted = metadata.permissions.contains(NCBrandGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCBrandGlobal.shared.permissionMounted)
  1021. }
  1022. if dataSource.metadataShare[metadata.ocId] != nil {
  1023. tableShare = dataSource.metadataShare[metadata.ocId]
  1024. }
  1025. //
  1026. // LAYOUT LIST
  1027. //
  1028. if layout == NCBrandGlobal.shared.layoutList {
  1029. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1030. cell.delegate = self
  1031. cell.objectId = metadata.ocId
  1032. cell.indexPath = indexPath
  1033. cell.labelTitle.text = metadata.fileNameView
  1034. cell.labelTitle.textColor = NCBrandColor.shared.textView
  1035. cell.separator.backgroundColor = NCBrandColor.shared.separator
  1036. cell.imageSelect.image = nil
  1037. cell.imageStatus.image = nil
  1038. cell.imageLocal.image = nil
  1039. cell.imageFavorite.image = nil
  1040. cell.imageShared.image = nil
  1041. cell.imageShared.clearLayerMask()
  1042. cell.imageMore.image = nil
  1043. cell.imageItem.image = nil
  1044. cell.imageItem.backgroundColor = nil
  1045. cell.progressView.progress = 0.0
  1046. if metadata.directory {
  1047. if metadata.e2eEncrypted {
  1048. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1049. } else if isShare {
  1050. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1051. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1052. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1053. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1054. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1055. } else if metadata.mountType == "group" {
  1056. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1057. } else if isMounted {
  1058. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1059. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1060. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1061. } else {
  1062. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1063. }
  1064. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  1065. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1066. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1067. // Local image: offline
  1068. if tableDirectory != nil && tableDirectory!.offline {
  1069. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1070. }
  1071. } else {
  1072. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1073. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1074. } else {
  1075. if metadata.hasPreview {
  1076. cell.imageItem.backgroundColor = .lightGray
  1077. } else {
  1078. if metadata.iconName.count > 0 {
  1079. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1080. } else {
  1081. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1082. }
  1083. }
  1084. }
  1085. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1086. // image local
  1087. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1088. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1089. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1090. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1091. }
  1092. }
  1093. // image Favorite
  1094. if metadata.favorite {
  1095. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1096. }
  1097. // Share image
  1098. if (isShare) {
  1099. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1100. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1101. cell.imageShared.image = NCCollectionCommon.images.cellShareByLinkImage
  1102. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1103. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1104. } else {
  1105. cell.imageShared.image = NCCollectionCommon.images.cellCanShareImage
  1106. }
  1107. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userID {
  1108. let fileNameUser = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  1109. if FileManager.default.fileExists(atPath: fileNameUser) {
  1110. cell.imageShared.avatar()
  1111. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  1112. } else {
  1113. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCBrandGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  1114. if errorCode == 0 && account == self.appDelegate.account {
  1115. cell.imageShared.avatar()
  1116. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  1117. }
  1118. }
  1119. }
  1120. }
  1121. // Transfer
  1122. var progress: Float = 0.0
  1123. var totalBytes: Int64 = 0
  1124. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  1125. if progressArray != nil && progressArray?.count == 3 {
  1126. progress = progressArray?.object(at: 0) as? Float ?? 0
  1127. totalBytes = progressArray?.object(at: 1) as? Int64 ?? 0
  1128. }
  1129. if metadata.status == NCBrandGlobal.shared.metadataStatusInDownload || metadata.status == NCBrandGlobal.shared.metadataStatusDownloading || metadata.status >= NCBrandGlobal.shared.metadataStatusTypeUpload {
  1130. cell.progressView.isHidden = false
  1131. cell.setButtonMore(named: NCBrandGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1132. } else {
  1133. cell.progressView.isHidden = true
  1134. cell.progressView.progress = progress
  1135. cell.setButtonMore(named: NCBrandGlobal.shared.buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1136. }
  1137. // Write status on Label Info
  1138. switch metadata.status {
  1139. case NCBrandGlobal.shared.metadataStatusWaitDownload:
  1140. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1141. break
  1142. case NCBrandGlobal.shared.metadataStatusInDownload:
  1143. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1144. break
  1145. case NCBrandGlobal.shared.metadataStatusDownloading:
  1146. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1147. break
  1148. case NCBrandGlobal.shared.metadataStatusWaitUpload:
  1149. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1150. break
  1151. case NCBrandGlobal.shared.metadataStatusInUpload:
  1152. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1153. break
  1154. case NCBrandGlobal.shared.metadataStatusUploading:
  1155. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1156. break
  1157. default:
  1158. break
  1159. }
  1160. // Live Photo
  1161. if metadata.livePhoto {
  1162. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1163. }
  1164. // E2EE
  1165. if metadata.e2eEncrypted || isEncryptedFolder {
  1166. cell.hideButtonShare(true)
  1167. } else {
  1168. cell.hideButtonShare(false)
  1169. }
  1170. // Remove last separator
  1171. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1172. cell.separator.isHidden = true
  1173. } else {
  1174. cell.separator.isHidden = false
  1175. }
  1176. // Edit mode
  1177. if isEditMode {
  1178. cell.selectMode(true)
  1179. if selectOcId.contains(metadata.ocId) {
  1180. cell.selected(true)
  1181. } else {
  1182. cell.selected(false)
  1183. }
  1184. } else {
  1185. cell.selectMode(false)
  1186. }
  1187. // Disable Share Button
  1188. if appDelegate.disableSharesView {
  1189. cell.hideButtonShare(true)
  1190. }
  1191. return cell
  1192. }
  1193. //
  1194. // LAYOUT GRID
  1195. //
  1196. if layout == NCBrandGlobal.shared.layoutGrid {
  1197. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1198. cell.delegate = self
  1199. cell.objectId = metadata.ocId
  1200. cell.indexPath = indexPath
  1201. cell.labelTitle.text = metadata.fileNameView
  1202. cell.labelTitle.textColor = NCBrandColor.shared.textView
  1203. cell.imageSelect.image = nil
  1204. cell.imageStatus.image = nil
  1205. cell.imageLocal.image = nil
  1206. cell.imageFavorite.image = nil
  1207. cell.imageItem.image = nil
  1208. cell.imageItem.backgroundColor = nil
  1209. cell.progressView.progress = 0.0
  1210. if metadata.directory {
  1211. if metadata.e2eEncrypted {
  1212. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1213. } else if isShare {
  1214. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1215. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1216. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1217. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1218. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1219. } else if metadata.mountType == "group" {
  1220. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1221. } else if isMounted {
  1222. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1223. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1224. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1225. } else {
  1226. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1227. }
  1228. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1229. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1230. // Local image: offline
  1231. if tableDirectory != nil && tableDirectory!.offline {
  1232. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1233. }
  1234. } else {
  1235. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1236. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1237. } else {
  1238. if metadata.hasPreview {
  1239. cell.imageItem.backgroundColor = .lightGray
  1240. } else {
  1241. if metadata.iconName.count > 0 {
  1242. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1243. } else {
  1244. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1245. }
  1246. }
  1247. }
  1248. // image Local
  1249. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1250. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1251. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1252. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1253. }
  1254. }
  1255. // image Favorite
  1256. if metadata.favorite {
  1257. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1258. }
  1259. // Transfer
  1260. if metadata.status == NCBrandGlobal.shared.metadataStatusInDownload || metadata.status == NCBrandGlobal.shared.metadataStatusDownloading || metadata.status >= NCBrandGlobal.shared.metadataStatusTypeUpload {
  1261. cell.progressView.isHidden = false
  1262. cell.setButtonMore(named: NCBrandGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1263. } else {
  1264. cell.progressView.isHidden = true
  1265. cell.progressView.progress = 0.0
  1266. cell.setButtonMore(named: NCBrandGlobal.shared.buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1267. }
  1268. // Live Photo
  1269. if metadata.livePhoto {
  1270. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1271. }
  1272. // Edit mode
  1273. if isEditMode {
  1274. cell.selectMode(true)
  1275. if selectOcId.contains(metadata.ocId) {
  1276. cell.selected(true)
  1277. } else {
  1278. cell.selected(false)
  1279. }
  1280. } else {
  1281. cell.selectMode(false)
  1282. }
  1283. return cell
  1284. }
  1285. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1286. }
  1287. }
  1288. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1289. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1290. headerRichWorkspaceHeight = 0
  1291. if let richWorkspaceText = richWorkspaceText {
  1292. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1293. if trimmed.count > 0 && !isSearching {
  1294. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1295. }
  1296. }
  1297. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1298. }
  1299. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1300. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1301. }
  1302. }