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