NCCollectionViewCommon.swift 77 KB

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