NCCollectionViewCommon.swift 80 KB

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