NCCollectionViewCommon.swift 77 KB

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