NCCollectionViewCommon.swift 89 KB

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