NCCollectionViewCommon.swift 87 KB

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