NCCollectionViewCommon.swift 78 KB

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