NCCollectionViewCommon.swift 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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 UIKit
  24. import Realm
  25. import NextcloudKit
  26. import EasyTipView
  27. import JGProgressHUD
  28. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, NCSectionFooterDelegate, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate, UIContextMenuInteractionDelegate, NCAccountRequestDelegate, NCSelectableNavigationView {
  29. @IBOutlet weak var collectionView: UICollectionView!
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. internal let refreshControl = UIRefreshControl()
  32. internal var searchController: UISearchController?
  33. internal var emptyDataSet: NCEmptyDataSet?
  34. internal var backgroundImageView = UIImageView()
  35. internal var serverUrl: String = ""
  36. internal var isDirectoryE2EE = false
  37. internal var isEditMode = false
  38. internal var selectOcId: [String] = []
  39. internal var selectIndexPath: [IndexPath] = []
  40. internal var metadataFolder: tableMetadata?
  41. internal var dataSource = NCDataSource()
  42. internal var richWorkspaceText: String?
  43. internal var headerMenu: NCSectionHeaderMenu?
  44. internal var isSearchingMode: Bool = false
  45. internal var layoutForView: NCDBLayoutForView?
  46. internal var selectableDataSource: [RealmSwiftObject] { dataSource.getMetadataSourceForAllSections() }
  47. private var autoUploadFileName = ""
  48. private var autoUploadDirectory = ""
  49. internal var groupByField = "name"
  50. internal var providers: [NKSearchProvider]?
  51. internal var searchResults: [NKSearchResult]?
  52. internal var listLayout: NCListLayout!
  53. internal var gridLayout: NCGridLayout!
  54. internal var literalSearch: String?
  55. internal var isReloadDataSourceNetworkInProgress: Bool = false
  56. private var pushed: Bool = false
  57. private var tipView: EasyTipView?
  58. private var isTransitioning: Bool = false
  59. // DECLARE
  60. internal var layoutKey = ""
  61. internal var titleCurrentFolder = ""
  62. internal var titlePreviusFolder: String?
  63. internal var enableSearchBar: Bool = false
  64. internal var headerMenuTransferView = false
  65. internal var headerMenuButtonsView: Bool = true
  66. internal var headerRichWorkspaceDisable:Bool = false
  67. internal var emptyImage: UIImage?
  68. internal var emptyTitle: String = ""
  69. internal var emptyDescription: String = ""
  70. // MARK: - View Life Cycle
  71. required init?(coder aDecoder: NSCoder) {
  72. super.init(coder: aDecoder)
  73. }
  74. override func viewDidLoad() {
  75. super.viewDidLoad()
  76. self.navigationController?.presentationController?.delegate = self
  77. // CollectionView & layout
  78. collectionView.alwaysBounceVertical = true
  79. listLayout = NCListLayout()
  80. gridLayout = NCGridLayout()
  81. // Color
  82. view.backgroundColor = .systemBackground
  83. collectionView.backgroundColor = .systemBackground
  84. refreshControl.tintColor = .gray
  85. if enableSearchBar {
  86. searchController = UISearchController(searchResultsController: nil)
  87. searchController?.searchResultsUpdater = self
  88. searchController?.obscuresBackgroundDuringPresentation = false
  89. searchController?.delegate = self
  90. searchController?.searchBar.delegate = self
  91. searchController?.searchBar.autocapitalizationType = .none
  92. navigationItem.searchController = searchController
  93. navigationItem.hidesSearchBarWhenScrolling = true
  94. }
  95. // Cell
  96. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  97. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  98. collectionView.register(UINib(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  99. // Header
  100. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  101. collectionView.register(UINib(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  102. // Footer
  103. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  104. // Refresh Control
  105. collectionView.refreshControl = refreshControl
  106. refreshControl.action(for: .valueChanged) { _ in
  107. self.dataSource.clearDirectory()
  108. self.reloadDataSourceNetwork(isForced: true)
  109. }
  110. // Empty
  111. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: getHeaderHeight(), delegate: self)
  112. // Long Press on CollectionView
  113. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  114. longPressedGesture.minimumPressDuration = 0.5
  115. longPressedGesture.delegate = self
  116. longPressedGesture.delaysTouchesBegan = true
  117. collectionView.addGestureRecognizer(longPressedGesture)
  118. // TIP
  119. var preferences = EasyTipView.Preferences()
  120. preferences.drawing.foregroundColor = .white
  121. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  122. preferences.drawing.textAlignment = .left
  123. preferences.drawing.arrowPosition = .top
  124. preferences.drawing.cornerRadius = 10
  125. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  126. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  127. preferences.animating.showInitialAlpha = 0
  128. preferences.animating.showDuration = 1.5
  129. preferences.animating.dismissDuration = 1.5
  130. tipView = EasyTipView(text: NSLocalizedString("_tip_accountrequest_", comment: ""), preferences: preferences, delegate: self)
  131. // Notification
  132. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  133. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  134. }
  135. override func viewWillAppear(_ animated: Bool) {
  136. super.viewWillAppear(animated)
  137. appDelegate.activeViewController = self
  138. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  139. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  140. if layoutForView?.layout == NCGlobal.shared.layoutList {
  141. collectionView?.collectionViewLayout = listLayout
  142. } else {
  143. collectionView?.collectionViewLayout = gridLayout
  144. }
  145. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  146. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  147. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  148. NotificationCenter.default.addObserver(self, selector: #selector(setNavigationItem), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  149. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  150. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetwork), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  151. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  152. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  153. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  154. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  155. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  156. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  157. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  158. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  159. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  160. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  161. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  162. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  163. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  164. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  165. if serverUrl == "" {
  166. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  167. } else {
  168. appDelegate.activeServerUrl = serverUrl
  169. }
  170. navigationController?.navigationBar.prefersLargeTitles = true
  171. navigationController?.setNavigationBarHidden(false, animated: true)
  172. setNavigationItem()
  173. reloadDataSource(isForced: false)
  174. if !isSearchingMode {
  175. reloadDataSourceNetwork()
  176. }
  177. //FIXME: iPAD PDF landscape mode iOS 16
  178. DispatchQueue.main.async {
  179. self.collectionView?.collectionViewLayout.invalidateLayout()
  180. }
  181. }
  182. override func viewDidAppear(_ animated: Bool) {
  183. super.viewDidAppear(animated)
  184. showTip()
  185. }
  186. override func viewWillDisappear(_ animated: Bool) {
  187. super.viewWillDisappear(animated)
  188. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  189. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  190. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  191. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  192. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  193. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  194. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  195. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  196. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  197. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  198. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  199. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  200. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  201. pushed = false
  202. // REQUEST
  203. NCNetworking.shared.cancelUnifiedSearchFiles()
  204. // TIP
  205. self.tipView?.dismiss()
  206. }
  207. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  208. let viewController = presentationController.presentedViewController
  209. if viewController is NCViewerRichWorkspaceWebView {
  210. closeRichWorkspaceWebView()
  211. }
  212. }
  213. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  214. super.viewWillTransition(to: size, with: coordinator)
  215. self.collectionView?.collectionViewLayout.invalidateLayout()
  216. self.collectionView?.reloadData()
  217. self.tipView?.dismiss()
  218. coordinator.animate(alongsideTransition: nil) { _ in
  219. self.showTip()
  220. }
  221. }
  222. override var canBecomeFirstResponder: Bool {
  223. return true
  224. }
  225. // MARK: - NotificationCenter
  226. @objc func initialize() {
  227. guard !appDelegate.account.isEmpty else { return }
  228. // Search
  229. if searchController?.isActive ?? false || isSearchingMode {
  230. searchController?.isActive = false
  231. isSearchingMode = false
  232. }
  233. // Select
  234. if isEditMode {
  235. isEditMode = !isEditMode
  236. selectOcId.removeAll()
  237. selectIndexPath.removeAll()
  238. }
  239. if self.view?.window != nil {
  240. if serverUrl == "" {
  241. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  242. } else {
  243. appDelegate.activeServerUrl = serverUrl
  244. }
  245. appDelegate.listFilesVC.removeAll()
  246. appDelegate.listFavoriteVC.removeAll()
  247. appDelegate.listOfflineVC.removeAll()
  248. }
  249. if serverUrl != "" {
  250. self.navigationController?.popToRootViewController(animated: false)
  251. }
  252. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  253. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  254. if layoutForView?.layout == NCGlobal.shared.layoutList {
  255. collectionView?.collectionViewLayout = listLayout
  256. } else {
  257. collectionView?.collectionViewLayout = gridLayout
  258. }
  259. setNavigationItem()
  260. }
  261. @objc func applicationWillResignActive(_ notification: NSNotification) {
  262. self.refreshControl.endRefreshing()
  263. }
  264. @objc func changeTheming() {
  265. collectionView.reloadData()
  266. }
  267. @objc func reloadDataSource(_ notification: NSNotification) {
  268. reloadDataSource()
  269. }
  270. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  271. if !isSearchingMode {
  272. reloadDataSourceNetwork(isForced: true)
  273. }
  274. }
  275. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  276. reloadDataSource()
  277. }
  278. @objc func closeRichWorkspaceWebView() {
  279. reloadDataSourceNetwork()
  280. }
  281. @objc func deleteFile(_ notification: NSNotification) {
  282. guard let userInfo = notification.userInfo as NSDictionary?,
  283. let error = userInfo["error"] as? NKError else { return }
  284. let onlyLocalCache: Bool = userInfo["onlyLocalCache"] as? Bool ?? false
  285. self.queryDB(isForced: true)
  286. if error == .success, let indexPath = userInfo["indexPath"] as? [IndexPath], !indexPath.isEmpty, !onlyLocalCache {
  287. collectionView?.performBatchUpdates({
  288. collectionView?.deleteItems(at: indexPath)
  289. }, completion: { _ in
  290. self.collectionView?.reloadData()
  291. })
  292. } else {
  293. if error != .success {
  294. NCContentPresenter.shared.showError(error: error)
  295. }
  296. self.collectionView?.reloadData()
  297. }
  298. if let hud = userInfo["hud"] as? JGProgressHUD {
  299. hud.dismiss()
  300. }
  301. }
  302. @objc func moveFile(_ notification: NSNotification) {
  303. deleteFile(notification)
  304. }
  305. @objc func copyFile(_ notification: NSNotification) {
  306. guard let userInfo = notification.userInfo as NSDictionary? else { return }
  307. if let hud = userInfo["hud"] as? JGProgressHUD {
  308. hud.dismiss()
  309. }
  310. }
  311. @objc func renameFile(_ notification: NSNotification) {
  312. guard let userInfo = notification.userInfo as NSDictionary?,
  313. let account = userInfo["account"] as? String,
  314. account == appDelegate.account
  315. else { return }
  316. if isSearchingMode {
  317. reloadDataSourceNetwork()
  318. } else {
  319. reloadDataSource()
  320. }
  321. }
  322. @objc func createFolder(_ notification: NSNotification) {
  323. guard let userInfo = notification.userInfo as NSDictionary?,
  324. let ocId = userInfo["ocId"] as? String,
  325. let serverUrl = userInfo["serverUrl"] as? String,
  326. serverUrl == self.serverUrl,
  327. let account = userInfo["account"] as? String,
  328. account == appDelegate.account,
  329. let e2ee = userInfo["e2ee"] as? Bool,
  330. let withPush = userInfo["withPush"] as? Bool
  331. else { return }
  332. if e2ee {
  333. reloadDataSourceNetwork(isForced: true)
  334. } else if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  335. reloadDataSource()
  336. if withPush {
  337. pushMetadata(metadata)
  338. }
  339. }
  340. }
  341. @objc func favoriteFile(_ notification: NSNotification) {
  342. guard let userInfo = notification.userInfo as NSDictionary?,
  343. let ocId = userInfo["ocId"] as? String,
  344. let serverUrl = userInfo["serverUrl"] as? String,
  345. serverUrl == self.serverUrl
  346. else {
  347. if self is NCFavorite {
  348. reloadDataSource()
  349. }
  350. return
  351. }
  352. dataSource.reloadMetadata(ocId: ocId)
  353. collectionView?.reloadData()
  354. }
  355. @objc func downloadStartFile(_ notification: NSNotification) {
  356. guard let userInfo = notification.userInfo as NSDictionary?,
  357. let serverUrl = userInfo["serverUrl"] as? String,
  358. serverUrl == self.serverUrl,
  359. let account = userInfo["account"] as? String,
  360. account == appDelegate.account
  361. else { return }
  362. reloadDataSource()
  363. }
  364. @objc func downloadedFile(_ notification: NSNotification) {
  365. guard let userInfo = notification.userInfo as NSDictionary?,
  366. let serverUrl = userInfo["serverUrl"] as? String,
  367. serverUrl == self.serverUrl,
  368. let account = userInfo["account"] as? String,
  369. account == appDelegate.account
  370. else { return }
  371. reloadDataSource()
  372. }
  373. @objc func downloadCancelFile(_ notification: NSNotification) {
  374. guard let userInfo = notification.userInfo as NSDictionary?,
  375. let ocId = userInfo["ocId"] as? String,
  376. let serverUrl = userInfo["serverUrl"] as? String,
  377. serverUrl == self.serverUrl,
  378. let account = userInfo["account"] as? String,
  379. account == appDelegate.account
  380. else { return }
  381. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  382. if let indexPath = indexPath {
  383. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  384. collectionView?.reloadItems(at: [indexPath])
  385. } else {
  386. self.collectionView?.reloadData()
  387. }
  388. } else {
  389. reloadDataSource()
  390. }
  391. }
  392. @objc func uploadStartFile(_ notification: NSNotification) {
  393. guard let userInfo = notification.userInfo as NSDictionary?,
  394. let ocId = userInfo["ocId"] as? String,
  395. let serverUrl = userInfo["serverUrl"] as? String,
  396. let account = userInfo["account"] as? String
  397. else { return }
  398. guard !isSearchingMode, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  399. // Header view trasfer
  400. if metadata.isTransferInForeground {
  401. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: 0)
  402. self.collectionView?.reloadData()
  403. }
  404. if serverUrl == self.serverUrl, account == appDelegate.account {
  405. reloadDataSource()
  406. }
  407. }
  408. @objc func uploadedFile(_ notification: NSNotification) {
  409. guard let userInfo = notification.userInfo as NSDictionary?,
  410. let ocId = userInfo["ocId"] as? String,
  411. let ocIdTemp = userInfo["ocIdTemp"] as? String,
  412. let serverUrl = userInfo["serverUrl"] as? String,
  413. let account = userInfo["account"] as? String
  414. else { return }
  415. if ocIdTemp == NCNetworking.shared.transferInForegorund?.ocId {
  416. NCNetworking.shared.transferInForegorund = nil
  417. self.collectionView?.reloadData()
  418. }
  419. if account == appDelegate.account, serverUrl == self.serverUrl, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  420. if metadata.e2eEncrypted {
  421. reloadDataSourceNetwork(isForced: true)
  422. } else {
  423. reloadDataSource()
  424. }
  425. }
  426. }
  427. @objc func uploadCancelFile(_ notification: NSNotification) {
  428. guard let userInfo = notification.userInfo as NSDictionary?,
  429. let ocId = userInfo["ocId"] as? String,
  430. let serverUrl = userInfo["serverUrl"] as? String,
  431. let account = userInfo["account"] as? String
  432. else { return }
  433. if ocId == NCNetworking.shared.transferInForegorund?.ocId {
  434. NCNetworking.shared.transferInForegorund = nil
  435. self.collectionView?.reloadData()
  436. }
  437. if account == appDelegate.account, serverUrl == self.serverUrl {
  438. reloadDataSource()
  439. }
  440. }
  441. @objc func triggerProgressTask(_ notification: NSNotification) {
  442. guard let userInfo = notification.userInfo as NSDictionary?,
  443. let progressNumber = userInfo["progress"] as? NSNumber,
  444. let totalBytes = userInfo["totalBytes"] as? Int64,
  445. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64,
  446. let ocId = userInfo["ocId"] as? String
  447. else { return }
  448. let chunk: Int = userInfo["chunk"] as? Int ?? 0
  449. let e2eEncrypted: Bool = userInfo["e2eEncrypted"] as? Bool ?? false
  450. // Header Transfer
  451. if headerMenuTransferView && (chunk > 0 || e2eEncrypted) {
  452. if NCNetworking.shared.transferInForegorund?.ocId == ocId {
  453. NCNetworking.shared.transferInForegorund?.progress = progressNumber.floatValue
  454. } else {
  455. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: progressNumber.floatValue)
  456. collectionView.reloadData()
  457. }
  458. self.headerMenu?.progressTransfer.progress = progressNumber.floatValue
  459. }
  460. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  461. if let (indexPath, _) = self.dataSource.getIndexPathMetadata(ocId: ocId) as? (IndexPath, NCMetadataForSection?),
  462. let cell = collectionView?.cellForItem(at: indexPath) {
  463. if let cell = cell as? NCCellProtocol {
  464. if progressNumber.floatValue == 1 && !(cell is NCTransferCell) {
  465. cell.fileProgressView?.isHidden = true
  466. cell.fileProgressView?.progress = .zero
  467. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  468. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  469. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  470. } else {
  471. cell.fileInfoLabel?.text = ""
  472. }
  473. } else {
  474. cell.fileProgressView?.isHidden = false
  475. cell.fileProgressView?.progress = progressNumber.floatValue
  476. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  477. if status == NCGlobal.shared.metadataStatusInDownload {
  478. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  479. } else if status == NCGlobal.shared.metadataStatusInUpload {
  480. if totalBytes > 0 {
  481. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  482. } else {
  483. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ …"
  484. }
  485. }
  486. }
  487. }
  488. }
  489. }
  490. // MARK: - Tip
  491. func showTip() {
  492. if self is NCFiles, self.view.window != nil, !NCBrandOptions.shared.disable_multiaccount, !NCBrandOptions.shared.disable_manage_account, self.serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId), let view = self.navigationItem.leftBarButtonItem?.customView {
  493. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest), NCManageDatabase.shared.getAllAccountOrderAlias().count > 0 {
  494. self.tipView?.show(forView: view)
  495. }
  496. }
  497. }
  498. // MARK: - Layout
  499. @objc func setNavigationItem() {
  500. self.setNavigationRightItems()
  501. navigationItem.title = titleCurrentFolder
  502. guard layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  503. // PROFILE BUTTON
  504. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  505. let image = NCUtility.shared.loadUserImage(
  506. for: appDelegate.user,
  507. displayName: activeAccount?.displayName,
  508. userBaseUrl: appDelegate)
  509. let button = UIButton(type: .custom)
  510. button.setImage(image, for: .normal)
  511. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) {
  512. var titleButton = " "
  513. if getNavigationTitle() == activeAccount?.alias {
  514. titleButton = ""
  515. } else {
  516. titleButton += activeAccount?.displayName ?? ""
  517. }
  518. button.setTitle(titleButton, for: .normal)
  519. button.setTitleColor(.systemBlue, for: .normal)
  520. }
  521. button.semanticContentAttribute = .forceLeftToRight
  522. button.sizeToFit()
  523. button.action(for: .touchUpInside) { _ in
  524. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  525. if accounts.count > 0 && !NCBrandOptions.shared.disable_multiaccount && !NCBrandOptions.shared.disable_manage_account {
  526. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  527. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  528. vcAccountRequest.accounts = accounts
  529. vcAccountRequest.enableTimerProgress = false
  530. vcAccountRequest.enableAddAccount = true
  531. vcAccountRequest.delegate = self
  532. vcAccountRequest.dismissDidEnterBackground = true
  533. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  534. let numberCell = accounts.count + 1
  535. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  536. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  537. self.present(popup, animated: true)
  538. }
  539. // TIP
  540. self.dismissTip()
  541. }
  542. }
  543. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  544. navigationItem.leftItemsSupplementBackButton = true
  545. if titlePreviusFolder == nil {
  546. navigationController?.navigationBar.topItem?.title = getNavigationTitle()
  547. } else {
  548. navigationController?.navigationBar.topItem?.title = titlePreviusFolder
  549. }
  550. navigationItem.title = titleCurrentFolder
  551. }
  552. func getNavigationTitle() -> String {
  553. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  554. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  555. return NCBrandOptions.shared.brand
  556. }
  557. return userAlias
  558. }
  559. // MARK: - Empty
  560. func emptyDataSetView(_ view: NCEmptyView) {
  561. self.emptyDataSet?.setOffset(getHeaderHeight())
  562. if isSearchingMode {
  563. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  564. if isReloadDataSourceNetworkInProgress {
  565. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  566. } else {
  567. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  568. }
  569. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  570. } else if isReloadDataSourceNetworkInProgress {
  571. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  572. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  573. view.emptyDescription.text = ""
  574. } else {
  575. if serverUrl == "" {
  576. view.emptyImage.image = emptyImage
  577. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  578. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  579. } else {
  580. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  581. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  582. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  583. }
  584. }
  585. }
  586. // MARK: - SEARCH
  587. func updateSearchResults(for searchController: UISearchController) {
  588. self.literalSearch = searchController.searchBar.text
  589. }
  590. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  591. isSearchingMode = true
  592. self.providers?.removeAll()
  593. self.dataSource.clearDataSource()
  594. self.collectionView.reloadData()
  595. // TIP
  596. self.tipView?.dismiss()
  597. }
  598. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  599. if isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
  600. reloadDataSourceNetwork()
  601. }
  602. }
  603. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  604. DispatchQueue.global().async {
  605. NCNetworking.shared.cancelUnifiedSearchFiles()
  606. self.isSearchingMode = false
  607. self.literalSearch = ""
  608. self.providers?.removeAll()
  609. self.dataSource.clearDataSource()
  610. self.reloadDataSource()
  611. }
  612. }
  613. // MARK: - TAP EVENT
  614. func accountRequestChangeAccount(account: String) {
  615. NCManageDatabase.shared.setAccountActive(account)
  616. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  617. NCOperationQueue.shared.cancelAllQueue()
  618. NCNetworking.shared.cancelAllTask()
  619. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  620. }
  621. }
  622. func accountRequestAddAccount() {
  623. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  624. }
  625. func tapButtonSwitch(_ sender: Any) {
  626. guard isTransitioning == false else { return }
  627. isTransitioning = true
  628. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  629. // list layout
  630. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  631. layoutForView?.layout = NCGlobal.shared.layoutList
  632. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  633. self.groupByField = "name"
  634. if self.dataSource.groupByField != self.groupByField {
  635. self.dataSource.changeGroupByField(self.groupByField)
  636. }
  637. self.collectionView.reloadData()
  638. self.collectionView.collectionViewLayout.invalidateLayout()
  639. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true) {_ in self.isTransitioning = false }
  640. } else {
  641. // grid layout
  642. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  643. layoutForView?.layout = NCGlobal.shared.layoutGrid
  644. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  645. if isSearchingMode {
  646. self.groupByField = "name"
  647. } else {
  648. self.groupByField = "classFile"
  649. }
  650. if self.dataSource.groupByField != self.groupByField {
  651. self.dataSource.changeGroupByField(self.groupByField)
  652. }
  653. self.collectionView.reloadData()
  654. self.collectionView.collectionViewLayout.invalidateLayout()
  655. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true) {_ in self.isTransitioning = false }
  656. }
  657. }
  658. func tapButtonOrder(_ sender: Any) {
  659. let sortMenu = NCSortMenu()
  660. sortMenu.toggleMenu(viewController: self, account: appDelegate.account, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  661. }
  662. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  663. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, indexPath: indexPath, sender: sender)
  664. }
  665. func tapShareListItem(with objectId: String, indexPath: IndexPath, sender: Any) {
  666. if isEditMode { return }
  667. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  668. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  669. }
  670. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  671. if isEditMode { return }
  672. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  673. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  674. toggleMenu(metadata: metadata, indexPath: indexPath, imageIcon: image)
  675. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  676. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  677. }
  678. }
  679. func tapRichWorkspace(_ sender: Any) {
  680. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  681. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  682. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  683. viewerRichWorkspace.serverUrl = serverUrl
  684. viewerRichWorkspace.delegate = self
  685. navigationController.modalPresentationStyle = .fullScreen
  686. self.present(navigationController, animated: true, completion: nil)
  687. }
  688. }
  689. }
  690. func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {
  691. unifiedSearchMore(metadataForSection: metadataForSection)
  692. }
  693. func tapButtonTransfer(_ sender: Any) {
  694. if let ocId = NCNetworking.shared.transferInForegorund?.ocId,
  695. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  696. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  697. }
  698. }
  699. func longPressListItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  700. }
  701. func longPressGridItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  702. }
  703. func longPressMoreListItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  704. }
  705. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  706. }
  707. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  708. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  709. }
  710. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  711. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  712. return nil
  713. }, actionProvider: { _ in
  714. return nil
  715. })
  716. }
  717. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  718. if gestureRecognizer.state != .began { return }
  719. var listMenuItems: [UIMenuItem] = []
  720. let touchPoint = gestureRecognizer.location(in: collectionView)
  721. becomeFirstResponder()
  722. if serverUrl != "" {
  723. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  724. }
  725. if listMenuItems.count > 0 {
  726. UIMenuController.shared.menuItems = listMenuItems
  727. UIMenuController.shared.showMenu(from: collectionView, rect: CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0))
  728. }
  729. }
  730. // MARK: - Menu Item
  731. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  732. if #selector(pasteFilesMenu) == action {
  733. if !UIPasteboard.general.items.isEmpty, !(metadataFolder?.e2eEncrypted ?? false) {
  734. return true
  735. }
  736. }
  737. return false
  738. }
  739. @objc func pasteFilesMenu() {
  740. NCActionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  741. }
  742. // MARK: - DataSource + NC Endpoint
  743. func queryDB(isForced: Bool) { }
  744. @objc func reloadDataSource(isForced: Bool = true) {
  745. guard !appDelegate.account.isEmpty else { return }
  746. // E2EE
  747. isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(serverUrl: serverUrl, userBase: appDelegate)
  748. // get auto upload folder
  749. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  750. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)
  751. // get layout for view
  752. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  753. // set GroupField for Grid
  754. if !isSearchingMode && layoutForView?.layout == NCGlobal.shared.layoutGrid {
  755. groupByField = "classFile"
  756. } else {
  757. groupByField = "name"
  758. }
  759. }
  760. @objc func reloadDataSourceNetwork(isForced: Bool = false) { }
  761. @objc func networkSearch() {
  762. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  763. else {
  764. self.refreshControl.endRefreshing()
  765. return
  766. }
  767. isReloadDataSourceNetworkInProgress = true
  768. self.dataSource.clearDataSource()
  769. self.refreshControl.beginRefreshing()
  770. self.collectionView.reloadData()
  771. if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  772. NCNetworking.shared.unifiedSearchFiles(userBaseUrl: appDelegate, literal: literalSearch) { account, searchProviders in
  773. self.providers = searchProviders
  774. self.searchResults = []
  775. self.dataSource = NCDataSource(
  776. metadatas: [] ,
  777. account: self.appDelegate.account,
  778. sort: self.layoutForView?.sort,
  779. ascending: self.layoutForView?.ascending,
  780. directoryOnTop: self.layoutForView?.directoryOnTop,
  781. favoriteOnTop: true,
  782. filterLivePhoto: true,
  783. providers: self.providers,
  784. searchResults: self.searchResults)
  785. } update: { account, id, searchResult, metadatas in
  786. guard let metadatas = metadatas, metadatas.count > 0, self.isSearchingMode , let searchResult = searchResult else { return }
  787. NCOperationQueue.shared.unifiedSearchAddSection(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult)
  788. } completion: { account, error in
  789. self.refreshControl.endRefreshing()
  790. self.isReloadDataSourceNetworkInProgress = false
  791. self.collectionView.reloadData()
  792. }
  793. } else {
  794. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch) { metadatas, error in
  795. DispatchQueue.main.async {
  796. self.refreshControl.endRefreshing()
  797. self.collectionView.reloadData()
  798. }
  799. guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
  800. self.dataSource = NCDataSource(
  801. metadatas: metadatas,
  802. account: self.appDelegate.account,
  803. sort: self.layoutForView?.sort,
  804. ascending: self.layoutForView?.ascending,
  805. directoryOnTop: self.layoutForView?.directoryOnTop,
  806. favoriteOnTop: true,
  807. filterLivePhoto: true,
  808. groupByField: self.groupByField,
  809. providers: self.providers,
  810. searchResults: self.searchResults)
  811. self.isReloadDataSourceNetworkInProgress = false
  812. }
  813. }
  814. }
  815. func unifiedSearchMore(metadataForSection: NCMetadataForSection?) {
  816. guard let metadataForSection = metadataForSection, let lastSearchResult = metadataForSection.lastSearchResult, let cursor = lastSearchResult.cursor, let term = literalSearch else { return }
  817. metadataForSection.unifiedSearchInProgress = true
  818. self.collectionView?.reloadData()
  819. NCNetworking.shared.unifiedSearchFilesProvider(userBaseUrl: appDelegate, id: lastSearchResult.id, term: term, limit: 5, cursor: cursor) { account, searchResult, metadatas, error in
  820. if error != .success {
  821. NCContentPresenter.shared.showError(error: error)
  822. }
  823. metadataForSection.unifiedSearchInProgress = false
  824. guard let searchResult = searchResult, let metadatas = metadatas else { return }
  825. self.dataSource.appendMetadatasToSection(metadatas, metadataForSection: metadataForSection, lastSearchResult: searchResult)
  826. DispatchQueue.main.async {
  827. self.collectionView?.reloadData()
  828. }
  829. }
  830. }
  831. @objc func networkReadFolder(isForced: Bool, completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ error: NKError) -> Void) {
  832. var tableDirectory: tableDirectory?
  833. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { (account, metadataFolder, error) in
  834. guard error == .success else {
  835. completion(nil, nil, nil, nil, error)
  836. return
  837. }
  838. if let metadataFolder = metadataFolder {
  839. tableDirectory = NCManageDatabase.shared.setDirectory(serverUrl: self.serverUrl, richWorkspace: metadataFolder.richWorkspace, account: account)
  840. }
  841. if isForced || tableDirectory?.etag != metadataFolder?.etag || metadataFolder?.e2eEncrypted ?? false {
  842. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { account, metadataFolder, metadatas, metadatasUpdate, _, metadatasDelete, error in
  843. guard error == .success else {
  844. completion(tableDirectory, nil, nil, nil, error)
  845. return
  846. }
  847. self.metadataFolder = metadataFolder
  848. // E2EE
  849. if let metadataFolder = metadataFolder, metadataFolder.e2eEncrypted, CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  850. NextcloudKit.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { account, e2eMetadata, _, data, error in
  851. if error == .success, let e2eMetadata = e2eMetadata {
  852. let error = NCEndToEndMetadata().decoderMetadata(e2eMetadata, serverUrl: self.serverUrl, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId, ownerId: metadataFolder.ownerId)
  853. if error == .success {
  854. self.reloadDataSource()
  855. } else {
  856. NCContentPresenter.shared.showError(error: error)
  857. }
  858. } else if error.errorCode != NCGlobal.shared.errorResourceNotFound {
  859. NCContentPresenter.shared.showError(error: NKError(errorCode: NCGlobal.shared.errorDecodeMetadata, errorDescription: "_e2e_error_decode_metadata_"))
  860. }
  861. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, error)
  862. }
  863. } else {
  864. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, error)
  865. }
  866. }
  867. } else {
  868. completion(tableDirectory, nil, nil, nil, NKError())
  869. }
  870. }
  871. }
  872. // MARK: - Push metadata
  873. func pushMetadata(_ metadata: tableMetadata) {
  874. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  875. appDelegate.activeMetadata = metadata
  876. // FILES
  877. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  878. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  879. if viewController.isViewLoaded {
  880. pushViewController(viewController: viewController)
  881. }
  882. } else {
  883. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  884. viewController.isRoot = false
  885. viewController.serverUrl = serverUrlPush
  886. viewController.titlePreviusFolder = navigationItem.title
  887. viewController.titleCurrentFolder = metadata.fileNameView
  888. appDelegate.listFilesVC[serverUrlPush] = viewController
  889. pushViewController(viewController: viewController)
  890. }
  891. }
  892. }
  893. // FAVORITE
  894. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  895. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  896. if viewController.isViewLoaded {
  897. pushViewController(viewController: viewController)
  898. }
  899. } else {
  900. if let viewController: NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  901. viewController.serverUrl = serverUrlPush
  902. viewController.titlePreviusFolder = navigationItem.title
  903. viewController.titleCurrentFolder = metadata.fileNameView
  904. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  905. pushViewController(viewController: viewController)
  906. }
  907. }
  908. }
  909. // OFFLINE
  910. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  911. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  912. if viewController.isViewLoaded {
  913. pushViewController(viewController: viewController)
  914. }
  915. } else {
  916. if let viewController: NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  917. viewController.serverUrl = serverUrlPush
  918. viewController.titlePreviusFolder = navigationItem.title
  919. viewController.titleCurrentFolder = metadata.fileNameView
  920. appDelegate.listOfflineVC[serverUrlPush] = viewController
  921. pushViewController(viewController: viewController)
  922. }
  923. }
  924. }
  925. // RECENT ( for push use Files ... he he he )
  926. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  927. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  928. if viewController.isViewLoaded {
  929. pushViewController(viewController: viewController)
  930. }
  931. } else {
  932. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  933. viewController.isRoot = false
  934. viewController.serverUrl = serverUrlPush
  935. viewController.titlePreviusFolder = navigationItem.title
  936. viewController.titleCurrentFolder = metadata.fileNameView
  937. appDelegate.listFilesVC[serverUrlPush] = viewController
  938. pushViewController(viewController: viewController)
  939. }
  940. }
  941. }
  942. // SHARES ( for push use Files ... he he he )
  943. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  944. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  945. if viewController.isViewLoaded {
  946. pushViewController(viewController: viewController)
  947. }
  948. } else {
  949. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  950. viewController.isRoot = false
  951. viewController.serverUrl = serverUrlPush
  952. viewController.titlePreviusFolder = navigationItem.title
  953. viewController.titleCurrentFolder = metadata.fileNameView
  954. appDelegate.listFilesVC[serverUrlPush] = viewController
  955. pushViewController(viewController: viewController)
  956. }
  957. }
  958. }
  959. // GROUPFOLDERS
  960. if layoutKey == NCGlobal.shared.layoutViewGroupfolders && !pushed {
  961. if let viewController = appDelegate.listGroupfoldersVC[serverUrlPush] {
  962. if viewController.isViewLoaded {
  963. pushViewController(viewController: viewController)
  964. }
  965. } else {
  966. if let viewController: NCGroupfolders = UIStoryboard(name: "NCGroupfolders", bundle: nil).instantiateInitialViewController() as? NCGroupfolders {
  967. viewController.serverUrl = serverUrlPush
  968. viewController.titlePreviusFolder = navigationItem.title
  969. viewController.titleCurrentFolder = metadata.fileNameView
  970. appDelegate.listGroupfoldersVC[serverUrlPush] = viewController
  971. pushViewController(viewController: viewController)
  972. }
  973. }
  974. }
  975. }
  976. }
  977. // MARK: - E2EE
  978. extension NCCollectionViewCommon: NCEndToEndInitializeDelegate {
  979. func endToEndInitializeSuccess() {
  980. if let metadata = appDelegate.activeMetadata {
  981. pushMetadata(metadata)
  982. }
  983. }
  984. }
  985. // MARK: - Collection View
  986. extension NCCollectionViewCommon: UICollectionViewDelegate {
  987. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  988. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  989. appDelegate.activeMetadata = metadata
  990. let metadataSourceForAllSections = dataSource.getMetadataSourceForAllSections()
  991. if isEditMode {
  992. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  993. selectOcId.remove(at: index)
  994. selectIndexPath.removeAll(where: { $0 == indexPath })
  995. } else {
  996. selectOcId.append(metadata.ocId)
  997. selectIndexPath.append(indexPath)
  998. }
  999. collectionView.reloadItems(at: [indexPath])
  1000. return
  1001. }
  1002. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  1003. let e2ee = NCEndToEndInitialize()
  1004. e2ee.delegate = self
  1005. e2ee.initEndToEndEncryption()
  1006. return
  1007. }
  1008. if metadata.directory {
  1009. pushMetadata(metadata)
  1010. } else {
  1011. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1012. if !metadata.isDirectoryE2EE && (metadata.isImage || metadata.isAudioOrVideo) {
  1013. var metadatas: [tableMetadata] = []
  1014. for metadata in metadataSourceForAllSections {
  1015. if metadata.isImage || metadata.isAudioOrVideo {
  1016. metadatas.append(metadata)
  1017. }
  1018. }
  1019. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  1020. return
  1021. }
  1022. if CCUtility.fileProviderStorageExists(metadata) {
  1023. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  1024. } else if NextcloudKit.shared.isNetworkReachable() {
  1025. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _, _ in }
  1026. } else {
  1027. let error = NKError(errorCode: NCGlobal.shared.errorOffline, errorDescription: "_go_online_")
  1028. NCContentPresenter.shared.showInfo(error: error)
  1029. }
  1030. }
  1031. }
  1032. func pushViewController(viewController: UIViewController) {
  1033. if pushed { return }
  1034. pushed = true
  1035. navigationController?.pushViewController(viewController, animated: true)
  1036. }
  1037. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1038. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  1039. if isEditMode || metadata.classFile == NKCommon.TypeClassFile.url.rawValue { return nil }
  1040. let identifier = indexPath as NSCopying
  1041. var image: UIImage?
  1042. let cell = collectionView.cellForItem(at: indexPath)
  1043. if cell is NCListCell {
  1044. image = (cell as! NCListCell).imageItem.image
  1045. } else if cell is NCGridCell {
  1046. image = (cell as! NCGridCell).imageItem.image
  1047. }
  1048. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  1049. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  1050. }, actionProvider: { _ in
  1051. return NCContextMenu().viewMenu(ocId: metadata.ocId, indexPath: indexPath, viewController: self, image: image)
  1052. })
  1053. }
  1054. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  1055. animator.addCompletion {
  1056. if let indexPath = configuration.identifier as? IndexPath {
  1057. self.collectionView(collectionView, didSelectItemAt: indexPath)
  1058. }
  1059. }
  1060. }
  1061. }
  1062. extension NCCollectionViewCommon: UICollectionViewDataSource {
  1063. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1064. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1065. // Thumbnail
  1066. if !metadata.directory {
  1067. if metadata.name == NCGlobal.shared.appName {
  1068. if let image = NCUtility.shared.createFilePreviewImage(ocId: metadata.ocId, etag: metadata.etag, fileNameView: metadata.fileNameView, classFile: metadata.classFile, status: metadata.status, createPreviewMedia: !metadata.hasPreview) {
  1069. (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1070. } else {
  1071. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1072. }
  1073. } else {
  1074. // Unified search
  1075. switch metadata.iconName {
  1076. case let str where str.contains("contacts"):
  1077. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1078. case let str where str.contains("conversation"):
  1079. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1080. case let str where str.contains("calendar"):
  1081. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1082. case let str where str.contains("deck"):
  1083. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1084. case let str where str.contains("mail"):
  1085. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconMail
  1086. case let str where str.contains("talk"):
  1087. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1088. case let str where str.contains("confirm"):
  1089. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconConfirm
  1090. case let str where str.contains("pages"):
  1091. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconPages
  1092. default:
  1093. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1094. }
  1095. if !metadata.iconUrl.isEmpty {
  1096. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol {
  1097. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1098. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1099. }
  1100. }
  1101. }
  1102. }
  1103. // Avatar
  1104. if metadata.ownerId.count > 0,
  1105. metadata.ownerId != appDelegate.userId,
  1106. appDelegate.account == metadata.account,
  1107. let cell = cell as? NCCellProtocol {
  1108. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1109. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1110. }
  1111. }
  1112. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { }
  1113. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1114. return dataSource.numberOfSections()
  1115. }
  1116. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1117. let numberItems = dataSource.numberOfItemsInSection(section)
  1118. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1119. return numberItems
  1120. }
  1121. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1122. var cell: NCCellProtocol & UICollectionViewCell
  1123. // LAYOUT LIST
  1124. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1125. guard let listCell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell else { return UICollectionViewCell() }
  1126. listCell.delegate = self
  1127. cell = listCell
  1128. } else {
  1129. // LAYOUT GRID
  1130. guard let gridCell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridCell else { return UICollectionViewCell() }
  1131. gridCell.delegate = self
  1132. cell = gridCell
  1133. }
  1134. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return cell }
  1135. var isShare = false
  1136. var isMounted = false
  1137. var a11yValues: [String] = []
  1138. if metadataFolder != nil {
  1139. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1140. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1141. }
  1142. cell.fileSelectImage?.image = nil
  1143. cell.fileStatusImage?.image = nil
  1144. cell.fileLocalImage?.image = nil
  1145. cell.fileFavoriteImage?.image = nil
  1146. cell.fileSharedImage?.image = nil
  1147. cell.fileMoreImage?.image = nil
  1148. cell.filePreviewImageView?.image = nil
  1149. cell.filePreviewImageView?.backgroundColor = nil
  1150. cell.fileObjectId = metadata.ocId
  1151. cell.indexPath = indexPath
  1152. cell.fileUser = metadata.ownerId
  1153. cell.fileProgressView?.isHidden = true
  1154. cell.fileProgressView?.progress = 0.0
  1155. cell.hideButtonShare(false)
  1156. cell.hideButtonMore(false)
  1157. cell.titleInfoTrailingDefault()
  1158. if isSearchingMode {
  1159. cell.fileTitleLabel?.text = metadata.fileName
  1160. cell.fileTitleLabel?.lineBreakMode = .byTruncatingTail
  1161. if metadata.name == NCGlobal.shared.appName {
  1162. cell.fileInfoLabel?.text = NSLocalizedString("_in_", comment: "") + " " + NCUtilityFileSystem.shared.getPath(path: metadata.path, user: metadata.user)
  1163. } else {
  1164. cell.fileInfoLabel?.text = metadata.subline
  1165. }
  1166. } else {
  1167. cell.fileTitleLabel?.text = metadata.fileNameView
  1168. cell.fileTitleLabel?.lineBreakMode = .byTruncatingMiddle
  1169. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  1170. }
  1171. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1172. cell.fileProgressView?.isHidden = false
  1173. }
  1174. // Accessibility [shared]
  1175. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1176. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1177. }
  1178. if metadata.directory {
  1179. let tableDirectory = NCManageDatabase.shared.getTableDirectory(ocId: metadata.ocId)
  1180. if metadata.e2eEncrypted {
  1181. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderEncrypted
  1182. } else if isShare {
  1183. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1184. } else if !metadata.shareType.isEmpty {
  1185. metadata.shareType.contains(3) ?
  1186. (cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderPublic) :
  1187. (cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe)
  1188. } else if !metadata.shareType.isEmpty && metadata.shareType.contains(3) {
  1189. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderPublic
  1190. } else if metadata.mountType == "group" {
  1191. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderGroup
  1192. } else if isMounted {
  1193. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderExternal
  1194. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1195. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1196. } else {
  1197. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folder
  1198. }
  1199. // Local image: offline
  1200. if let tableDirectory, tableDirectory.offline {
  1201. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1202. }
  1203. // color folder
  1204. cell.filePreviewImageView?.image = cell.filePreviewImageView?.image?.colorizeFolder(metadata: metadata, tableDirectory: tableDirectory)
  1205. } else {
  1206. // image local
  1207. if NCManageDatabase.shared.getTableLocalFile(ocId: metadata.ocId) != nil {
  1208. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1209. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1210. } else if CCUtility.fileProviderStorageExists(metadata) {
  1211. cell.fileLocalImage?.image = NCBrandColor.cacheImages.local
  1212. }
  1213. }
  1214. // image Favorite
  1215. if metadata.favorite {
  1216. cell.fileFavoriteImage?.image = NCBrandColor.cacheImages.favorite
  1217. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1218. }
  1219. // Share image
  1220. if isShare {
  1221. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1222. } else if !metadata.shareType.isEmpty {
  1223. metadata.shareType.contains(3) ?
  1224. (cell.fileSharedImage?.image = NCBrandColor.cacheImages.shareByLink) :
  1225. (cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared)
  1226. } else {
  1227. cell.fileSharedImage?.image = NCBrandColor.cacheImages.canShare
  1228. }
  1229. if appDelegate.account != metadata.account {
  1230. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1231. }
  1232. // Button More
  1233. if metadata.isInTransfer || metadata.isWaitingTransfer {
  1234. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1235. } else if metadata.lock == true {
  1236. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1237. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1238. } else {
  1239. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1240. }
  1241. // Write status on Label Info
  1242. switch metadata.status {
  1243. case NCGlobal.shared.metadataStatusWaitDownload:
  1244. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1245. break
  1246. case NCGlobal.shared.metadataStatusInDownload:
  1247. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1248. break
  1249. case NCGlobal.shared.metadataStatusDownloading:
  1250. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↓ …"
  1251. break
  1252. case NCGlobal.shared.metadataStatusWaitUpload:
  1253. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1254. cell.fileLocalImage?.image = nil
  1255. break
  1256. case NCGlobal.shared.metadataStatusInUpload:
  1257. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1258. cell.fileLocalImage?.image = nil
  1259. break
  1260. case NCGlobal.shared.metadataStatusUploading:
  1261. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↑ …"
  1262. cell.fileLocalImage?.image = nil
  1263. break
  1264. case NCGlobal.shared.metadataStatusUploadError:
  1265. if metadata.sessionError != "" {
  1266. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1267. } else {
  1268. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1269. }
  1270. break
  1271. default:
  1272. break
  1273. }
  1274. // Live Photo
  1275. if metadata.livePhoto {
  1276. cell.fileStatusImage?.image = NCBrandColor.cacheImages.livePhoto
  1277. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1278. }
  1279. // URL
  1280. if metadata.classFile == NKCommon.TypeClassFile.url.rawValue {
  1281. cell.fileLocalImage?.image = nil
  1282. cell.hideButtonShare(true)
  1283. cell.hideButtonMore(true)
  1284. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1285. cell.fileUser = ownerId
  1286. }
  1287. }
  1288. // Disable Share Button
  1289. if appDelegate.disableSharesView {
  1290. cell.hideButtonShare(true)
  1291. }
  1292. // Separator
  1293. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearchingMode {
  1294. cell.cellSeparatorView?.isHidden = true
  1295. } else {
  1296. cell.cellSeparatorView?.isHidden = false
  1297. }
  1298. // Edit mode
  1299. if isEditMode {
  1300. cell.selectMode(true)
  1301. if selectOcId.contains(metadata.ocId) {
  1302. cell.selected(true)
  1303. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1304. } else {
  1305. cell.selected(false)
  1306. }
  1307. } else {
  1308. cell.selectMode(false)
  1309. }
  1310. // Accessibility
  1311. cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
  1312. // Color string find in search
  1313. if isSearchingMode, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
  1314. let longestWordRange = (title.lowercased() as NSString).range(of: literalSearch)
  1315. let attributedString = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
  1316. attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor : UIColor.systemBlue], range: longestWordRange)
  1317. cell.fileTitleLabel?.attributedText = attributedString
  1318. }
  1319. // Add TAGS
  1320. cell.setTags(tags: Array(metadata.tags))
  1321. // Hide buttons
  1322. if metadata.name != NCGlobal.shared.appName {
  1323. cell.titleInfoTrailingFull()
  1324. cell.hideButtonShare(true)
  1325. cell.hideButtonMore(true)
  1326. }
  1327. // ** IMPORT MUST BE AT THE END **
  1328. //
  1329. if !metadata.isSharable() {
  1330. cell.hideButtonShare(true)
  1331. }
  1332. return cell
  1333. }
  1334. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1335. if kind == UICollectionView.elementKindSectionHeader {
  1336. if indexPath.section == 0 {
  1337. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1338. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1339. self.headerMenu = header
  1340. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1341. header.setImageSwitchList()
  1342. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1343. } else {
  1344. header.setImageSwitchGrid()
  1345. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1346. }
  1347. header.delegate = self
  1348. if !isSearchingMode, headerMenuTransferView, let ocId = NCNetworking.shared.transferInForegorund?.ocId {
  1349. let text = String(format: NSLocalizedString("_upload_foreground_msg_", comment: ""), NCBrandOptions.shared.brand)
  1350. header.setViewTransfer(isHidden: false, ocId: ocId, text: text, progress: NCNetworking.shared.transferInForegorund?.progress)
  1351. } else {
  1352. header.setViewTransfer(isHidden: true)
  1353. }
  1354. if headerMenuButtonsView {
  1355. header.setStatusButtonsView(enable: !dataSource.getMetadataSourceForAllSections().isEmpty)
  1356. header.setButtonsView(height: NCGlobal.shared.heightButtonsView)
  1357. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  1358. } else {
  1359. header.setButtonsView(height: 0)
  1360. }
  1361. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1362. header.setRichWorkspaceText(richWorkspaceText)
  1363. header.setSectionHeight(heightHeaderSection)
  1364. if heightHeaderSection == 0 {
  1365. header.labelSection.text = ""
  1366. } else {
  1367. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1368. }
  1369. header.labelSection.textColor = .label
  1370. return header
  1371. } else {
  1372. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  1373. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1374. header.labelSection.textColor = .label
  1375. return header
  1376. }
  1377. } else {
  1378. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1379. let sections = dataSource.numberOfSections()
  1380. let section = indexPath.section
  1381. let metadataForSection = self.dataSource.getMetadataForSection(indexPath.section)
  1382. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1383. let metadatasCount: Int = metadataForSection?.metadatas.count ?? 0
  1384. let unifiedSearchInProgress = metadataForSection?.unifiedSearchInProgress ?? false
  1385. footer.delegate = self
  1386. footer.metadataForSection = metadataForSection
  1387. footer.setTitleLabel("")
  1388. footer.setButtonText(NSLocalizedString("_show_more_results_", comment: ""))
  1389. footer.separatorIsHidden(true)
  1390. footer.buttonIsHidden(true)
  1391. footer.hideActivityIndicatorSection()
  1392. if isSearchingMode {
  1393. if sections > 1 && section != sections - 1 {
  1394. footer.separatorIsHidden(false)
  1395. }
  1396. // If the number of entries(metadatas) is lower than the cursor, then there are no more entries.
  1397. // The blind spot in this is when the number of entries is the same as the cursor. If so, we don't have a way of knowing if there are no more entries.
  1398. // This is as good as it gets for determining last page without server-side flag.
  1399. let isLastPage = (metadatasCount < metadataForSection?.lastSearchResult?.cursor ?? 0) || metadataForSection?.lastSearchResult?.entries.isEmpty == true
  1400. if isSearchingMode && isPaginated && metadatasCount > 0 && !isLastPage {
  1401. footer.buttonIsHidden(false)
  1402. }
  1403. if unifiedSearchInProgress {
  1404. footer.showActivityIndicatorSection()
  1405. }
  1406. } else {
  1407. if sections == 1 || section == sections - 1 {
  1408. let info = dataSource.getFooterInformationAllMetadatas()
  1409. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1410. } else {
  1411. footer.separatorIsHidden(false)
  1412. }
  1413. }
  1414. return footer
  1415. }
  1416. }
  1417. }
  1418. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1419. func getHeaderHeight() -> CGFloat {
  1420. var size: CGFloat = 0
  1421. // transfer in progress
  1422. if headerMenuTransferView,
  1423. let metadata = NCManageDatabase.shared.getMetadataFromOcId(NCNetworking.shared.transferInForegorund?.ocId),
  1424. metadata.isTransferInForeground {
  1425. if !isSearchingMode {
  1426. size += NCGlobal.shared.heightHeaderTransfer
  1427. }
  1428. } else {
  1429. NCNetworking.shared.transferInForegorund = nil
  1430. }
  1431. if headerMenuButtonsView {
  1432. size += NCGlobal.shared.heightButtonsView
  1433. }
  1434. return size
  1435. }
  1436. func getHeaderHeight(section:Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1437. var headerRichWorkspace: CGFloat = 0
  1438. if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
  1439. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1440. if trimmed.count > 0 && !isSearchingMode {
  1441. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1442. }
  1443. }
  1444. if isSearchingMode || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  1445. if section == 0 {
  1446. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1447. } else {
  1448. return (0, 0, NCGlobal.shared.heightSection)
  1449. }
  1450. } else {
  1451. return (getHeaderHeight(), headerRichWorkspace, 0)
  1452. }
  1453. }
  1454. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1455. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1456. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1457. return CGSize(width: collectionView.frame.width, height: heightHeader)
  1458. }
  1459. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1460. let sections = dataSource.numberOfSections()
  1461. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1462. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1463. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1464. var size = CGSize(width: collectionView.frame.width, height: 0)
  1465. if section == sections - 1 {
  1466. size.height += NCGlobal.shared.endHeightFooter
  1467. } else {
  1468. size.height += NCGlobal.shared.heightFooter
  1469. }
  1470. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1471. size.height += NCGlobal.shared.heightFooterButton
  1472. }
  1473. return size
  1474. }
  1475. }
  1476. extension NCCollectionViewCommon: EasyTipViewDelegate {
  1477. func easyTipViewDidTap(_ tipView: EasyTipView) {
  1478. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1479. }
  1480. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  1481. func dismissTip() {
  1482. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1483. self.tipView?.dismiss()
  1484. }
  1485. }