NCCollectionViewCommon.swift 92 KB

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