NCCollectionViewCommon.swift 98 KB

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