NCCollectionViewCommon.swift 79 KB

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