NCCollectionViewCommon.swift 85 KB

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