NCCollectionViewCommon.swift 82 KB

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