NCCollectionViewCommon.swift 82 KB

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