NCCollectionViewCommon.swift 83 KB

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