NCCollectionViewCommon.swift 83 KB

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