NCCollectionViewCommon.swift 94 KB

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