NCCollectionViewCommon.swift 80 KB

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