NCCollectionViewCommon.swift 83 KB

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