NCCollectionViewCommon.swift 81 KB

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