NCCollectionViewCommon.swift 83 KB

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