NCCollectionViewCommon.swift 79 KB

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