NCCollectionViewCommon.swift 82 KB

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