NCCollectionViewCommon.swift 80 KB

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