NCCollectionViewCommon.swift 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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, UIContextMenuInteractionDelegate, NCAccountRequestDelegate {
  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 backgroundImageView = UIImageView()
  32. internal let defaultBackgroundColor = NCBrandColor.shared.systemBackground
  33. internal var serverUrl: String = ""
  34. internal var isEncryptedFolder = false
  35. internal var isEditMode = false
  36. internal var selectOcId: [String] = []
  37. internal var metadatasSource: [tableMetadata] = []
  38. internal var metadataFolder: tableMetadata?
  39. internal var metadataTouch: tableMetadata?
  40. internal var dataSource = NCDataSource()
  41. internal var richWorkspaceText: String?
  42. internal var header: UIView?
  43. internal var layoutForView: NCGlobal.layoutForViewType?
  44. private var autoUploadFileName = ""
  45. private var autoUploadDirectory = ""
  46. internal var listLayout: NCListLayout!
  47. internal var gridLayout: NCGridLayout!
  48. private let headerHeight: CGFloat = 50
  49. private var headerRichWorkspaceHeight: CGFloat = 0
  50. private let footerHeight: CGFloat = 100
  51. private var timerInputSearch: Timer?
  52. internal var literalSearch: String?
  53. internal var isSearching: Bool = false
  54. internal var isReloadDataSourceNetworkInProgress: Bool = false
  55. var selectedIndexPath: IndexPath!
  56. private var pushed: Bool = false
  57. // DECLARE
  58. internal var layoutKey = ""
  59. internal var titleCurrentFolder = ""
  60. internal var enableSearchBar: Bool = false
  61. internal var emptyImage: UIImage?
  62. internal var emptyTitle: String = ""
  63. internal var emptyDescription: String = ""
  64. // MARK: - View Life Cycle
  65. required init?(coder aDecoder: NSCoder) {
  66. super.init(coder: aDecoder)
  67. }
  68. override func viewDidLoad() {
  69. super.viewDidLoad()
  70. self.navigationController?.presentationController?.delegate = self
  71. view.backgroundColor = defaultBackgroundColor
  72. collectionView.backgroundColor = defaultBackgroundColor
  73. collectionView.alwaysBounceVertical = true
  74. if enableSearchBar {
  75. searchController = UISearchController(searchResultsController: nil)
  76. searchController?.searchResultsUpdater = self
  77. searchController?.obscuresBackgroundDuringPresentation = false
  78. searchController?.delegate = self
  79. searchController?.searchBar.delegate = self
  80. navigationItem.searchController = searchController
  81. navigationItem.hidesSearchBarWhenScrolling = false
  82. }
  83. // Cell
  84. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  85. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  86. collectionView.register(UINib.init(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  87. // Header
  88. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  89. // Footer
  90. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  91. listLayout = NCListLayout()
  92. gridLayout = NCGridLayout()
  93. // Refresh Control
  94. collectionView.addSubview(refreshControl)
  95. refreshControl.tintColor = .gray
  96. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  97. // Empty
  98. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: headerHeight, delegate: self)
  99. // Long Press on CollectionView
  100. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  101. longPressedGesture.minimumPressDuration = 0.5
  102. longPressedGesture.delegate = self
  103. longPressedGesture.delaysTouchesBegan = true
  104. collectionView.addGestureRecognizer(longPressedGesture)
  105. // Notification
  106. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitializeMain), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  124. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object:nil)
  125. changeTheming()
  126. }
  127. override func viewWillAppear(_ animated: Bool) {
  128. super.viewWillAppear(animated)
  129. appDelegate.activeViewController = self
  130. if serverUrl == "" {
  131. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  132. } else {
  133. appDelegate.activeServerUrl = serverUrl
  134. }
  135. setLayout()
  136. navigationController?.navigationBar.prefersLargeTitles = true
  137. navigationController?.setNavigationBarHidden(false, animated: true)
  138. setNavigationItem()
  139. reloadDataSource()
  140. }
  141. override func viewDidAppear(_ animated: Bool) {
  142. super.viewDidAppear(animated)
  143. reloadDataSourceNetwork()
  144. }
  145. override func viewDidDisappear(_ animated: Bool) {
  146. super.viewDidDisappear(animated)
  147. pushed = false
  148. }
  149. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  150. let viewController = presentationController.presentedViewController
  151. if viewController is NCViewerRichWorkspaceWebView {
  152. closeRichWorkspaceWebView()
  153. } else if viewController is UINavigationController {
  154. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  155. appDelegate.activeFileViewInFolder = nil
  156. }
  157. }
  158. }
  159. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  160. super.viewWillTransition(to: size, with: coordinator)
  161. coordinator.animate(alongsideTransition: nil) { _ in
  162. self.collectionView?.collectionViewLayout.invalidateLayout()
  163. }
  164. }
  165. override var canBecomeFirstResponder: Bool {
  166. return true
  167. }
  168. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  169. super.traitCollectionDidChange(previousTraitCollection)
  170. setLayout()
  171. }
  172. // MARK: - NotificationCenter
  173. @objc func initializeMain() {
  174. if appDelegate.account == "" { return }
  175. if searchController?.isActive ?? false {
  176. searchController?.isActive = false
  177. }
  178. // set active serverUrl
  179. if self.view?.window != nil {
  180. if serverUrl == "" {
  181. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  182. } else {
  183. appDelegate.activeServerUrl = serverUrl
  184. }
  185. }
  186. if self is NCFiles || self is NCFavorite || self is NCOffline {
  187. self.navigationController?.popToRootViewController(animated: false)
  188. }
  189. appDelegate.listFilesVC.removeAll()
  190. appDelegate.listFavoriteVC.removeAll()
  191. appDelegate.listOfflineVC.removeAll()
  192. selectOcId.removeAll()
  193. setNavigationItem()
  194. setLayout()
  195. reloadDataSource()
  196. }
  197. @objc func changeTheming() {
  198. setLayout()
  199. }
  200. @objc func reloadDataSource(_ notification: NSNotification) {
  201. if self.view?.window == nil { return }
  202. reloadDataSource()
  203. }
  204. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  205. if self.view?.window == nil { return }
  206. if let userInfo = notification.userInfo as NSDictionary? {
  207. if let serverUrl = userInfo["serverUrl"] as? String {
  208. if serverUrl == self.serverUrl {
  209. reloadDataSourceNetwork(forced: true)
  210. }
  211. }
  212. } else {
  213. reloadDataSourceNetwork(forced: true)
  214. }
  215. }
  216. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  217. if self.view?.window == nil { return }
  218. reloadDataSource()
  219. }
  220. @objc func closeRichWorkspaceWebView() {
  221. if self.view?.window == nil { return }
  222. reloadDataSourceNetwork()
  223. }
  224. @objc func deleteFile(_ notification: NSNotification) {
  225. if self.view?.window == nil { return }
  226. if let userInfo = notification.userInfo as NSDictionary? {
  227. if let ocId = userInfo["ocId"] as? String, let fileNameView = userInfo["fileNameView"] as? String, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  228. if onlyLocal {
  229. reloadDataSource()
  230. } else if fileNameView.lowercased() == NCGlobal.shared.fileNameRichWorkspace.lowercased() {
  231. reloadDataSourceNetwork(forced: true)
  232. } else {
  233. if let row = dataSource.deleteMetadata(ocId: ocId) {
  234. let indexPath = IndexPath(row: row, section: 0)
  235. collectionView?.performBatchUpdates({
  236. collectionView?.deleteItems(at: [indexPath])
  237. }, completion: { (_) in
  238. self.collectionView?.reloadData()
  239. })
  240. }
  241. }
  242. }
  243. }
  244. }
  245. @objc func moveFile(_ notification: NSNotification) {
  246. if self.view?.window == nil { return }
  247. if let userInfo = notification.userInfo as NSDictionary? {
  248. if let ocId = userInfo["ocId"] as? String, let serverUrlFrom = userInfo["serverUrlFrom"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  249. // DEL
  250. if serverUrlFrom == serverUrl && metadata.account == appDelegate.account {
  251. if let row = dataSource.deleteMetadata(ocId: ocId) {
  252. let indexPath = IndexPath(row: row, section: 0)
  253. collectionView?.performBatchUpdates({
  254. collectionView?.deleteItems(at: [indexPath])
  255. }, completion: { (_) in
  256. self.collectionView?.reloadData()
  257. })
  258. }
  259. // ADD
  260. } else if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  261. if let row = dataSource.addMetadata(metadata) {
  262. let indexPath = IndexPath(row: row, section: 0)
  263. collectionView?.performBatchUpdates({
  264. collectionView?.insertItems(at: [indexPath])
  265. }, completion: { (_) in
  266. self.collectionView?.reloadData()
  267. })
  268. }
  269. }
  270. }
  271. }
  272. }
  273. @objc func copyFile(_ notification: NSNotification) {
  274. if self.view?.window == nil { return }
  275. if let userInfo = notification.userInfo as NSDictionary? {
  276. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  277. if serverUrlTo == self.serverUrl {
  278. reloadDataSource()
  279. }
  280. }
  281. }
  282. }
  283. @objc func renameFile(_ notification: NSNotification) {
  284. if self.view?.window == nil { return }
  285. reloadDataSource()
  286. }
  287. @objc func createFolder(_ notification: NSNotification) {
  288. if self.view?.window == nil { return }
  289. if let userInfo = notification.userInfo as NSDictionary? {
  290. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  291. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  292. if let row = dataSource.addMetadata(metadata) {
  293. let indexPath = IndexPath(row: row, section: 0)
  294. collectionView?.performBatchUpdates({
  295. collectionView?.insertItems(at: [indexPath])
  296. }, completion: { (_) in
  297. self.collectionView?.reloadData()
  298. })
  299. }
  300. }
  301. }
  302. } else {
  303. reloadDataSourceNetwork()
  304. }
  305. }
  306. @objc func favoriteFile(_ notification: NSNotification) {
  307. if self.view?.window == nil { return }
  308. if let userInfo = notification.userInfo as NSDictionary? {
  309. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  310. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  311. reloadDataSource()
  312. }
  313. }
  314. }
  315. }
  316. @objc func downloadStartFile(_ notification: NSNotification) {
  317. if self.view?.window == nil { return }
  318. if let userInfo = notification.userInfo as NSDictionary? {
  319. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  320. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  321. let indexPath = IndexPath(row: row, section: 0)
  322. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  323. collectionView?.reloadItems(at: [indexPath])
  324. }
  325. }
  326. }
  327. }
  328. }
  329. @objc func downloadedFile(_ notification: NSNotification) {
  330. if self.view?.window == nil { return }
  331. if let userInfo = notification.userInfo as NSDictionary? {
  332. if let ocId = userInfo["ocId"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  333. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  334. let indexPath = IndexPath(row: row, section: 0)
  335. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  336. collectionView?.reloadItems(at: [indexPath])
  337. }
  338. }
  339. }
  340. }
  341. }
  342. @objc func downloadCancelFile(_ notification: NSNotification) {
  343. if self.view?.window == nil { return }
  344. if let userInfo = notification.userInfo as NSDictionary? {
  345. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  346. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  347. let indexPath = IndexPath(row: row, section: 0)
  348. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  349. collectionView?.reloadItems(at: [indexPath])
  350. }
  351. }
  352. }
  353. }
  354. }
  355. @objc func uploadStartFile(_ notification: NSNotification) {
  356. if self.view?.window == nil { return }
  357. if let userInfo = notification.userInfo as NSDictionary? {
  358. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  359. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  360. dataSource.addMetadata(metadata)
  361. self.collectionView?.reloadData()
  362. }
  363. }
  364. }
  365. }
  366. @objc func uploadedFile(_ notification: NSNotification) {
  367. if self.view?.window == nil { return }
  368. if let userInfo = notification.userInfo as NSDictionary? {
  369. if let ocId = userInfo["ocId"] as? String, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  370. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  371. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  372. collectionView?.reloadData()
  373. }
  374. }
  375. }
  376. }
  377. @objc func uploadCancelFile(_ notification: NSNotification) {
  378. if self.view?.window == nil { return }
  379. if let userInfo = notification.userInfo as NSDictionary? {
  380. if let ocId = userInfo["ocId"] as? String, let serverUrl = userInfo["serverUrl"] as? String, let account = userInfo["account"] as? String {
  381. if serverUrl == self.serverUrl && account == appDelegate.account {
  382. if let row = dataSource.deleteMetadata(ocId: ocId) {
  383. let indexPath = IndexPath(row: row, section: 0)
  384. collectionView?.performBatchUpdates({
  385. if indexPath.section < (collectionView?.numberOfSections ?? 0) && indexPath.row < (collectionView?.numberOfItems(inSection: indexPath.section) ?? 0) {
  386. collectionView?.deleteItems(at: [indexPath])
  387. }
  388. }, completion: { (_) in
  389. self.collectionView?.reloadData()
  390. })
  391. } else {
  392. self.reloadDataSource()
  393. }
  394. }
  395. }
  396. }
  397. }
  398. @objc func triggerProgressTask(_ notification: NSNotification) {
  399. if self.view?.window == nil { return }
  400. if let userInfo = notification.userInfo as NSDictionary?, let progressNumber = userInfo["progress"] as? NSNumber, let totalBytes = userInfo["totalBytes"] as? Int64, let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64 {
  401. if let ocId = userInfo["ocId"] as? String {
  402. let progress = progressNumber.floatValue
  403. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  404. let progressType = NCGlobal.progressType(progress: progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected)
  405. appDelegate.listProgress[ocId] = progressType
  406. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  407. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  408. if cell is NCListCell {
  409. let cell = cell as! NCListCell
  410. if progress > 0 {
  411. cell.progressView?.isHidden = false
  412. cell.progressView?.progress = progress
  413. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  414. if status == NCGlobal.shared.metadataStatusInDownload {
  415. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  416. } else if status == NCGlobal.shared.metadataStatusInUpload {
  417. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  418. }
  419. }
  420. } else if cell is NCTransferCell {
  421. let cell = cell as! NCTransferCell
  422. if progress > 0 {
  423. cell.progressView?.isHidden = false
  424. cell.progressView?.progress = progress
  425. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  426. if status == NCGlobal.shared.metadataStatusInDownload {
  427. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  428. } else if status == NCGlobal.shared.metadataStatusInUpload {
  429. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  430. }
  431. }
  432. } else if cell is NCGridCell {
  433. let cell = cell as! NCGridCell
  434. if progress > 0 {
  435. cell.progressView.isHidden = false
  436. cell.progressView.progress = progress
  437. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  438. }
  439. }
  440. }
  441. }
  442. }
  443. }
  444. }
  445. // MARK: - Layout
  446. func setNavigationItem() {
  447. if isEditMode {
  448. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  449. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  450. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  451. } else {
  452. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  453. navigationItem.leftBarButtonItem = nil
  454. navigationItem.title = titleCurrentFolder
  455. // PROFILE BUTTON
  456. if layoutKey == NCGlobal.shared.layoutViewFiles {
  457. var image = NCUtility.shared.loadImage(named: "person.crop.circle")
  458. let fileNamePath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + appDelegate.user + ".png"
  459. if let userImage = UIImage(contentsOfFile: fileNamePath) {
  460. image = userImage
  461. }
  462. image = NCUtility.shared.createAvatar(image: image, size: 30)
  463. let button = UIButton(type: .custom)
  464. button.setImage(image, for: .normal)
  465. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) {
  466. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  467. var title = " "
  468. if activeAccount?.alias == "" {
  469. title = title + (activeAccount?.user ?? "")
  470. } else {
  471. title = title + (activeAccount?.alias ?? "")
  472. }
  473. button.setTitle(title, for: .normal)
  474. button.setTitleColor(.systemBlue, for: .normal)
  475. }
  476. button.semanticContentAttribute = .forceLeftToRight
  477. button.sizeToFit()
  478. button.addTarget(self, action: #selector(profileButtonTapped(sender:)), for: .touchUpInside)
  479. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  480. navigationItem.leftItemsSupplementBackButton = true
  481. }
  482. }
  483. }
  484. func setLayout() {
  485. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  486. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  487. if layoutForView?.layout == NCGlobal.shared.layoutList {
  488. collectionView?.collectionViewLayout = listLayout
  489. } else {
  490. collectionView?.collectionViewLayout = gridLayout
  491. }
  492. // IMAGE BACKGROUND
  493. if layoutForView?.imageBackgroud != "" {
  494. let imagePath = CCUtility.getDirectoryGroup().appendingPathComponent(NCGlobal.shared.appBackground).path + "/" + layoutForView!.imageBackgroud
  495. do {
  496. let data = try Data.init(contentsOf: URL(fileURLWithPath: imagePath))
  497. if let image = UIImage.init(data: data) {
  498. backgroundImageView.image = image
  499. backgroundImageView.contentMode = .scaleToFill
  500. collectionView.backgroundView = backgroundImageView
  501. }
  502. } catch { }
  503. } else {
  504. backgroundImageView.image = nil
  505. collectionView.backgroundView = nil
  506. }
  507. // COLOR BACKGROUND
  508. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  509. if traitCollection.userInterfaceStyle == .dark {
  510. if layoutForView?.darkColorBackground != "" {
  511. collectionView.backgroundColor = UIColor.init(hex: layoutForView?.darkColorBackground ?? "")
  512. } else if activeAccount?.darkColorBackground != "" {
  513. collectionView.backgroundColor = UIColor.init(hex: activeAccount?.darkColorBackground ?? "")
  514. } else {
  515. collectionView.backgroundColor = defaultBackgroundColor
  516. }
  517. } else {
  518. if layoutForView?.lightColorBackground != "" {
  519. collectionView.backgroundColor = UIColor.init(hex: layoutForView?.lightColorBackground ?? "")
  520. } else if activeAccount?.lightColorBackground != "" {
  521. collectionView.backgroundColor = UIColor.init(hex: activeAccount?.lightColorBackground ?? "")
  522. } else {
  523. collectionView.backgroundColor = defaultBackgroundColor
  524. }
  525. }
  526. collectionView.reloadData()
  527. }
  528. // MARK: - Empty
  529. func emptyDataSetView(_ view: NCEmptyView) {
  530. if searchController?.isActive ?? false {
  531. view.emptyImage.image = UIImage.init(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  532. if isReloadDataSourceNetworkInProgress {
  533. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  534. } else {
  535. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  536. }
  537. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  538. } else if isReloadDataSourceNetworkInProgress {
  539. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  540. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  541. view.emptyDescription.text = ""
  542. } else {
  543. if serverUrl == "" {
  544. view.emptyImage.image = emptyImage
  545. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  546. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  547. } else {
  548. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  549. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  550. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  551. }
  552. }
  553. }
  554. // MARK: - SEARCH
  555. func updateSearchResults(for searchController: UISearchController) {
  556. timerInputSearch?.invalidate()
  557. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  558. literalSearch = searchController.searchBar.text
  559. collectionView?.reloadData()
  560. }
  561. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  562. isSearching = true
  563. metadatasSource.removeAll()
  564. reloadDataSource()
  565. }
  566. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  567. isSearching = false
  568. literalSearch = ""
  569. reloadDataSource()
  570. }
  571. // MARK: - TAP EVENT
  572. @objc func tapSelect(sender: Any) {
  573. isEditMode = !isEditMode
  574. selectOcId.removeAll()
  575. setNavigationItem()
  576. self.collectionView.reloadData()
  577. }
  578. func changeAccountRequestAddAccount(account: String) {
  579. NCManageDatabase.shared.setAccountActive(account)
  580. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  581. NCOperationQueue.shared.cancelAllQueue()
  582. NCNetworking.shared.cancelAllTask()
  583. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  584. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  585. }
  586. }
  587. func accountRequestAddAccount() {
  588. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  589. }
  590. @objc func profileButtonTapped(sender: Any) {
  591. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  592. if accounts.count > 0 {
  593. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  594. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  595. vcAccountRequest.accounts = accounts
  596. vcAccountRequest.enableTimerProgress = false
  597. vcAccountRequest.enableAddAccount = true
  598. vcAccountRequest.delegate = self
  599. vcAccountRequest.dismissDidEnterBackground = true
  600. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  601. let numberCell = accounts.count + 1
  602. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  603. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  604. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  605. }
  606. }
  607. }
  608. func tapSwitchHeader(sender: Any) {
  609. if collectionView.collectionViewLayout == gridLayout {
  610. // list layout
  611. UIView.animate(withDuration: 0.0, animations: {
  612. self.collectionView.collectionViewLayout.invalidateLayout()
  613. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  614. self.collectionView.reloadData()
  615. })
  616. })
  617. layoutForView?.layout = NCGlobal.shared.layoutList
  618. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  619. } else {
  620. // grid layout
  621. UIView.animate(withDuration: 0.0, animations: {
  622. self.collectionView.collectionViewLayout.invalidateLayout()
  623. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  624. self.collectionView.reloadData()
  625. })
  626. })
  627. layoutForView?.layout = NCGlobal.shared.layoutGrid
  628. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  629. }
  630. }
  631. func tapOrderHeader(sender: Any) {
  632. let sortMenu = NCSortMenu()
  633. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  634. }
  635. @objc func tapSelectMenu(sender: Any) {
  636. guard let tabBarController = self.tabBarController else { return }
  637. toggleMenuSelect(viewController: tabBarController, selectOcId: selectOcId)
  638. }
  639. func tapMoreHeader(sender: Any) { }
  640. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  641. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  642. }
  643. func tapShareListItem(with objectId: String, sender: Any) {
  644. if isEditMode { return }
  645. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  646. NCFunctionCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  647. }
  648. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  649. if isEditMode { return }
  650. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  651. if namedButtonMore == NCGlobal.shared.buttonMoreMore {
  652. toggleMenu(viewController: self, metadata: metadata, image: image)
  653. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  654. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  655. }
  656. }
  657. func tapRichWorkspace(sender: Any) {
  658. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  659. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  660. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  661. viewerRichWorkspace.serverUrl = serverUrl
  662. navigationController.modalPresentationStyle = .fullScreen
  663. self.present(navigationController, animated: true, completion: nil)
  664. }
  665. }
  666. }
  667. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  668. }
  669. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  670. }
  671. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  672. }
  673. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  674. }
  675. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  676. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  677. /*
  678. if #available(iOS 13.0, *) {
  679. let interaction = UIContextMenuInteraction(delegate: self)
  680. self.view.addInteraction(interaction)
  681. }
  682. */
  683. }
  684. @available(iOS 13.0, *)
  685. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  686. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  687. return nil
  688. }, actionProvider: { suggestedActions in
  689. //let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  690. //}
  691. //return UIMenu(title: "Main Menu", children: [share])
  692. return nil
  693. })
  694. }
  695. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  696. if gestureRecognizer.state != .began { return }
  697. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) {
  698. metadataTouch = metadata
  699. } else {
  700. metadataTouch = nil
  701. }
  702. var listMenuItems: [UIMenuItem] = []
  703. let touchPoint = gestureRecognizer.location(in: collectionView)
  704. becomeFirstResponder()
  705. if serverUrl != "" {
  706. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  707. }
  708. if #available(iOS 13.0, *) {
  709. if !NCBrandOptions.shared.disable_background_color {
  710. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_background_", comment: ""), action: #selector(backgroundFilesMenu)))
  711. }
  712. }
  713. if listMenuItems.count > 0 {
  714. UIMenuController.shared.menuItems = listMenuItems
  715. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  716. UIMenuController.shared.setMenuVisible(true, animated: true)
  717. }
  718. }
  719. // MARK: - Menu Item
  720. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  721. if (#selector(pasteFilesMenu) == action) {
  722. if UIPasteboard.general.items.count > 0 {
  723. return true
  724. }
  725. }
  726. if (#selector(backgroundFilesMenu) == action) {
  727. return true
  728. }
  729. return false
  730. }
  731. @objc func pasteFilesMenu() {
  732. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  733. }
  734. @objc func backgroundFilesMenu() {
  735. if let vcBackgroundImageColor = UIStoryboard(name: "NCBackgroundImageColor", bundle: nil).instantiateInitialViewController() as? NCBackgroundImageColor {
  736. vcBackgroundImageColor.collectionViewCommon = self
  737. let popup = NCPopupViewController(contentController: vcBackgroundImageColor, popupWidth: vcBackgroundImageColor.width, popupHeight: vcBackgroundImageColor.height)
  738. popup.backgroundAlpha = 0
  739. self.present(popup, animated: true)
  740. }
  741. }
  742. // MARK: - DataSource + NC Endpoint
  743. @objc func reloadDataSource() {
  744. if appDelegate.account == "" { return }
  745. // Get richWorkspace Text
  746. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  747. richWorkspaceText = directory?.richWorkspace
  748. // E2EE
  749. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  750. // get auto upload folder
  751. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  752. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  753. // get layout for view
  754. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  755. }
  756. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  757. @objc func reloadDataSourceNetworkRefreshControl() {
  758. reloadDataSourceNetwork(forced: true)
  759. }
  760. @objc func networkSearch() {
  761. if appDelegate.account == "" { return }
  762. if literalSearch?.count ?? 0 > 1 {
  763. isReloadDataSourceNetworkInProgress = true
  764. collectionView?.reloadData()
  765. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  766. if self.searchController?.isActive ?? false && errorCode == 0 {
  767. self.metadatasSource = metadatas!
  768. }
  769. self.refreshControl.endRefreshing()
  770. self.isReloadDataSourceNetworkInProgress = false
  771. self.reloadDataSource()
  772. }
  773. } else {
  774. self.refreshControl.endRefreshing()
  775. }
  776. }
  777. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  778. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  779. if errorCode == 0 {
  780. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  781. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  782. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  783. if errorCode == 0 {
  784. self.metadataFolder = metadataFolder
  785. // E2EE
  786. if let metadataFolder = metadataFolder {
  787. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  788. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  789. if errorCode == 0 && e2eMetadata != nil {
  790. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  791. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata, forced: true)
  792. } else {
  793. self.reloadDataSource()
  794. }
  795. } else if errorCode != NCGlobal.shared.errorResourceNotFound {
  796. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata, forced: true)
  797. }
  798. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  799. }
  800. } else {
  801. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  802. }
  803. } else {
  804. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  805. }
  806. } else {
  807. completion(nil, nil, errorCode, errorDescription)
  808. }
  809. }
  810. } else {
  811. completion(nil, nil, 0, "")
  812. }
  813. } else {
  814. completion(nil, nil, errorCode, errorDescription)
  815. }
  816. }
  817. }
  818. }
  819. // MARK: - Collection View
  820. extension NCCollectionViewCommon: UICollectionViewDelegate {
  821. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  822. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  823. metadataTouch = metadata
  824. selectedIndexPath = indexPath
  825. if isEditMode {
  826. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  827. selectOcId.remove(at: index)
  828. } else {
  829. selectOcId.append(metadata.ocId)
  830. }
  831. collectionView.reloadItems(at: [indexPath])
  832. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  833. return
  834. }
  835. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  836. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorE2EENotEnabled, forced: true)
  837. return
  838. }
  839. if metadata.directory {
  840. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  841. // FILES
  842. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  843. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  844. if viewController.isViewLoaded {
  845. pushViewController(viewController: viewController)
  846. }
  847. } else {
  848. if let viewController:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  849. viewController.isRoot = false
  850. viewController.serverUrl = serverUrlPush
  851. viewController.titleCurrentFolder = metadataTouch!.fileNameView
  852. appDelegate.listFilesVC[serverUrlPush] = viewController
  853. pushViewController(viewController: viewController)
  854. }
  855. }
  856. }
  857. // FAVORITE
  858. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  859. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  860. if viewController.isViewLoaded {
  861. pushViewController(viewController: viewController)
  862. }
  863. } else {
  864. if let viewController:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  865. viewController.serverUrl = serverUrlPush
  866. viewController.titleCurrentFolder = metadataTouch!.fileNameView
  867. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  868. pushViewController(viewController: viewController)
  869. }
  870. }
  871. }
  872. // OFFLINE
  873. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  874. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  875. if viewController.isViewLoaded {
  876. pushViewController(viewController: viewController)
  877. }
  878. } else {
  879. if let viewController:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  880. viewController.serverUrl = serverUrlPush
  881. viewController.titleCurrentFolder = metadataTouch!.fileNameView
  882. appDelegate.listOfflineVC[serverUrlPush] = viewController
  883. pushViewController(viewController: viewController)
  884. }
  885. }
  886. }
  887. // RECENT ( for push use Files ... he he he )
  888. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  889. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  890. if viewController.isViewLoaded {
  891. pushViewController(viewController: viewController)
  892. }
  893. } else {
  894. if let viewController:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  895. viewController.isRoot = false
  896. viewController.serverUrl = serverUrlPush
  897. viewController.titleCurrentFolder = metadataTouch!.fileNameView
  898. appDelegate.listFilesVC[serverUrlPush] = viewController
  899. pushViewController(viewController: viewController)
  900. }
  901. }
  902. }
  903. //VIEW IN FOLDER
  904. if layoutKey == NCGlobal.shared.layoutViewViewInFolder && !pushed {
  905. if let viewController:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder {
  906. viewController.serverUrl = serverUrlPush
  907. viewController.titleCurrentFolder = metadataTouch!.fileNameView
  908. pushViewController(viewController: viewController)
  909. }
  910. }
  911. // SHARES ( for push use Files ... he he he )
  912. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  913. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  914. if viewController.isViewLoaded {
  915. pushViewController(viewController: viewController)
  916. }
  917. } else {
  918. if let viewController:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  919. viewController.isRoot = false
  920. viewController.serverUrl = serverUrlPush
  921. viewController.titleCurrentFolder = metadataTouch!.fileNameView
  922. appDelegate.listFilesVC[serverUrlPush] = viewController
  923. pushViewController(viewController: viewController)
  924. }
  925. }
  926. }
  927. } else {
  928. guard let metadataTouch = metadataTouch else { return }
  929. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  930. var metadatas: [tableMetadata] = []
  931. for metadata in dataSource.metadatas {
  932. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  933. metadatas.append(metadata)
  934. }
  935. }
  936. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  937. return
  938. }
  939. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  940. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  941. } else if NCCommunication.shared.isNetworkReachable() {
  942. NCNetworking.shared.download(metadata: metadataTouch, selector: NCGlobal.shared.selectorLoadFileView) { (_) in }
  943. } else {
  944. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorOffline, forced: true)
  945. }
  946. }
  947. }
  948. func pushViewController(viewController: UIViewController) {
  949. if pushed { return }
  950. pushed = true
  951. navigationController?.pushViewController(viewController, animated: true)
  952. }
  953. func collectionViewSelectAll() {
  954. selectOcId.removeAll()
  955. for metadata in metadatasSource {
  956. selectOcId.append(metadata.ocId)
  957. }
  958. collectionView.reloadData()
  959. }
  960. @available(iOS 13.0, *)
  961. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  962. if isEditMode { return nil }
  963. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  964. metadataTouch = metadata
  965. let identifier = indexPath as NSCopying
  966. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  967. return NCViewerProviderContextMenu(metadata: metadata)
  968. }, actionProvider: { suggestedActions in
  969. return NCFunctionCenter.shared.contextMenuConfiguration(metadata: metadata, viewController: self, enableDeleteLocal: true, enableViewInFolder: false)
  970. })
  971. }
  972. @available(iOS 13.0, *)
  973. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  974. animator.addCompletion {
  975. if let indexPath = configuration.identifier as? IndexPath {
  976. self.collectionView(collectionView, didSelectItemAt: indexPath)
  977. }
  978. }
  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. self.header = header
  994. if collectionView.collectionViewLayout == gridLayout {
  995. header.buttonSwitch.setImage(UIImage.init(named: "switchList")!.image(color: NCBrandColor.shared.gray, size: 50), for: .normal)
  996. } else {
  997. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")!.image(color: NCBrandColor.shared.gray, size: 50), for: .normal)
  998. }
  999. header.delegate = self
  1000. header.setStatusButton(count: dataSource.metadatas.count)
  1001. header.setTitleSorted(datasourceTitleButton: layoutForView?.titleButtonHeader ?? "")
  1002. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  1003. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  1004. return header
  1005. } else {
  1006. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1007. let info = dataSource.getFilesInformation()
  1008. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  1009. return footer
  1010. }
  1011. }
  1012. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1013. return 1
  1014. }
  1015. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1016. let numberItems = dataSource.numberOfItems()
  1017. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1018. return numberItems
  1019. }
  1020. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1021. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1022. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1023. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1024. } else {
  1025. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1026. }
  1027. }
  1028. var tableShare: tableShare?
  1029. var isShare = false
  1030. var isMounted = false
  1031. if metadataFolder != nil {
  1032. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1033. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1034. }
  1035. if dataSource.metadataShare[metadata.ocId] != nil {
  1036. tableShare = dataSource.metadataShare[metadata.ocId]
  1037. }
  1038. //
  1039. // LAYOUT LIST
  1040. //
  1041. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1042. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1043. cell.delegate = self
  1044. cell.objectId = metadata.ocId
  1045. cell.indexPath = indexPath
  1046. cell.labelTitle.text = metadata.fileNameView
  1047. cell.labelTitle.textColor = NCBrandColor.shared.label
  1048. cell.imageSelect.image = nil
  1049. cell.imageStatus.image = nil
  1050. cell.imageLocal.image = nil
  1051. cell.imageFavorite.image = nil
  1052. cell.imageShared.image = nil
  1053. cell.imageMore.image = nil
  1054. cell.imageItem.image = nil
  1055. cell.imageItem.backgroundColor = nil
  1056. cell.progressView.progress = 0.0
  1057. if metadata.directory {
  1058. if metadata.e2eEncrypted {
  1059. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1060. } else if isShare {
  1061. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1062. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1063. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1064. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1065. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1066. } else if metadata.mountType == "group" {
  1067. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1068. } else if isMounted {
  1069. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1070. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1071. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1072. } else {
  1073. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1074. }
  1075. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  1076. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1077. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1078. // Local image: offline
  1079. if tableDirectory != nil && tableDirectory!.offline {
  1080. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1081. }
  1082. } else {
  1083. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1084. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1085. } else {
  1086. if metadata.hasPreview {
  1087. cell.imageItem.backgroundColor = .lightGray
  1088. } else {
  1089. if metadata.iconName.count > 0 {
  1090. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1091. } else {
  1092. cell.imageItem.image = NCBrandColor.cacheImages.file
  1093. }
  1094. }
  1095. }
  1096. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1097. // image local
  1098. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1099. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1100. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1101. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1102. }
  1103. }
  1104. // image Favorite
  1105. if metadata.favorite {
  1106. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1107. }
  1108. // Share image
  1109. if (isShare) {
  1110. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1111. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1112. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  1113. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1114. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1115. } else {
  1116. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  1117. }
  1118. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userId {
  1119. cell.imageShared.image = UIImage(named: "avatar")
  1120. let fileNameUser = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + metadata.ownerId + ".png"
  1121. if FileManager.default.fileExists(atPath: fileNameUser) {
  1122. if let image = UIImage(contentsOfFile: fileNameUser) {
  1123. cell.imageShared.image = NCUtility.shared.createAvatar(image: image, size: 30)
  1124. }
  1125. } else {
  1126. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  1127. if errorCode == 0 && account == self.appDelegate.account {
  1128. if let image = UIImage(contentsOfFile: fileNameUser) {
  1129. cell.imageShared.image = NCUtility.shared.createAvatar(image: image, size: 30)
  1130. }
  1131. }
  1132. }
  1133. }
  1134. }
  1135. // Transfer
  1136. var progress: Float = 0.0
  1137. var totalBytes: Int64 = 0
  1138. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1139. progress = progressType.progress
  1140. totalBytes = progressType.totalBytes
  1141. }
  1142. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1143. cell.progressView.isHidden = false
  1144. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1145. } else {
  1146. cell.progressView.isHidden = true
  1147. cell.progressView.progress = progress
  1148. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1149. }
  1150. // Write status on Label Info
  1151. switch metadata.status {
  1152. case NCGlobal.shared.metadataStatusWaitDownload:
  1153. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1154. break
  1155. case NCGlobal.shared.metadataStatusInDownload:
  1156. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1157. break
  1158. case NCGlobal.shared.metadataStatusDownloading:
  1159. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1160. break
  1161. case NCGlobal.shared.metadataStatusWaitUpload:
  1162. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1163. break
  1164. case NCGlobal.shared.metadataStatusInUpload:
  1165. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1166. break
  1167. case NCGlobal.shared.metadataStatusUploading:
  1168. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1169. break
  1170. case NCGlobal.shared.metadataStatusUploadError:
  1171. if metadata.sessionError != "" {
  1172. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1173. } else {
  1174. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1175. }
  1176. break
  1177. default:
  1178. break
  1179. }
  1180. // Live Photo
  1181. if metadata.livePhoto {
  1182. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1183. }
  1184. // E2EE
  1185. if metadata.e2eEncrypted || isEncryptedFolder {
  1186. cell.hideButtonShare(true)
  1187. } else {
  1188. cell.hideButtonShare(false)
  1189. }
  1190. // Remove last separator
  1191. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1192. cell.separator.isHidden = true
  1193. } else {
  1194. cell.separator.isHidden = false
  1195. }
  1196. // Edit mode
  1197. if isEditMode {
  1198. cell.selectMode(true)
  1199. if selectOcId.contains(metadata.ocId) {
  1200. cell.selected(true)
  1201. } else {
  1202. cell.selected(false)
  1203. }
  1204. } else {
  1205. cell.selectMode(false)
  1206. }
  1207. // Disable Share Button
  1208. if appDelegate.disableSharesView {
  1209. cell.hideButtonShare(true)
  1210. }
  1211. return cell
  1212. }
  1213. //
  1214. // LAYOUT GRID
  1215. //
  1216. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1217. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1218. cell.delegate = self
  1219. cell.objectId = metadata.ocId
  1220. cell.indexPath = indexPath
  1221. cell.labelTitle.text = metadata.fileNameView
  1222. cell.labelTitle.textColor = NCBrandColor.shared.label
  1223. cell.imageSelect.image = nil
  1224. cell.imageStatus.image = nil
  1225. cell.imageLocal.image = nil
  1226. cell.imageFavorite.image = nil
  1227. cell.imageItem.image = nil
  1228. cell.imageItem.backgroundColor = nil
  1229. cell.progressView.progress = 0.0
  1230. if metadata.directory {
  1231. if metadata.e2eEncrypted {
  1232. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1233. } else if isShare {
  1234. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1235. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1236. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1237. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1238. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1239. } else if metadata.mountType == "group" {
  1240. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1241. } else if isMounted {
  1242. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1243. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1244. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1245. } else {
  1246. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1247. }
  1248. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1249. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1250. // Local image: offline
  1251. if tableDirectory != nil && tableDirectory!.offline {
  1252. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1253. }
  1254. } else {
  1255. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1256. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1257. } else {
  1258. if metadata.hasPreview {
  1259. cell.imageItem.backgroundColor = .lightGray
  1260. } else {
  1261. if metadata.iconName.count > 0 {
  1262. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1263. } else {
  1264. cell.imageItem.image = NCBrandColor.cacheImages.file
  1265. }
  1266. }
  1267. }
  1268. // image Local
  1269. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1270. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1271. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1272. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1273. }
  1274. }
  1275. // image Favorite
  1276. if metadata.favorite {
  1277. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1278. }
  1279. // Transfer
  1280. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1281. cell.progressView.isHidden = false
  1282. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1283. } else {
  1284. cell.progressView.isHidden = true
  1285. cell.progressView.progress = 0.0
  1286. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1287. }
  1288. // Live Photo
  1289. if metadata.livePhoto {
  1290. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1291. }
  1292. // Edit mode
  1293. if isEditMode {
  1294. cell.selectMode(true)
  1295. if selectOcId.contains(metadata.ocId) {
  1296. cell.selected(true)
  1297. } else {
  1298. cell.selected(false)
  1299. }
  1300. } else {
  1301. cell.selectMode(false)
  1302. }
  1303. return cell
  1304. }
  1305. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1306. }
  1307. }
  1308. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1309. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1310. headerRichWorkspaceHeight = 0
  1311. if let richWorkspaceText = richWorkspaceText {
  1312. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1313. if trimmed.count > 0 && !isSearching {
  1314. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1315. }
  1316. }
  1317. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1318. }
  1319. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1320. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1321. }
  1322. }