NCCollectionViewCommon.swift 93 KB

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