NCCollectionViewCommon.swift 79 KB

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