NCCollectionViewCommon.swift 83 KB

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