NCCollectionViewCommon.swift 83 KB

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