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: NCImageCache.images.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: NCImageCache.images.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. providers: self.providers,
  733. searchResults: self.searchResults)
  734. } update: { _, _, searchResult, metadatas in
  735. guard let metadatas, !metadatas.isEmpty, self.isSearchingMode, let searchResult else { return }
  736. self.appDelegate.unifiedSearchQueue.addOperation(NCOperationUnifiedSearch(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult))
  737. } completion: { _, _ in
  738. self.refreshControl.endRefreshing()
  739. self.isReloadDataSourceNetworkInProgress = false
  740. self.collectionView.reloadData()
  741. }
  742. } else {
  743. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch) { metadatas, error in
  744. DispatchQueue.main.async {
  745. self.refreshControl.endRefreshing()
  746. self.collectionView.reloadData()
  747. }
  748. guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
  749. self.dataSource = NCDataSource(
  750. metadatas: metadatas,
  751. account: self.appDelegate.account,
  752. sort: self.layoutForView?.sort,
  753. ascending: self.layoutForView?.ascending,
  754. directoryOnTop: self.layoutForView?.directoryOnTop,
  755. favoriteOnTop: 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().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().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().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().uploadMetadata(account: metadataFolder.account, serverUrl: serverUrl, userId: metadataFolder.userId)
  815. if error != .success {
  816. NCContentPresenter().showError(error: error)
  817. }
  818. }
  819. } else {
  820. NCContentPresenter().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 = utilityFileSystem.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().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: utilityFileSystem.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().view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  901. return
  902. }
  903. if utilityFileSystem.fileProviderStorageExists(metadata) {
  904. NCViewer().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().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 = utility.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 = NCImageCache.images.file
  954. } else {
  955. (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(named: metadata.iconName)
  956. }
  957. if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!utilityFileSystem.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 = NCImageCache.images.iconContacts
  967. case let str where str.contains("conversation"):
  968. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.iconTalk
  969. case let str where str.contains("calendar"):
  970. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.iconCalendar
  971. case let str where str.contains("deck"):
  972. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.iconDeck
  973. case let str where str.contains("mail"):
  974. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.iconMail
  975. case let str where str.contains("talk"):
  976. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.iconTalk
  977. case let str where str.contains("confirm"):
  978. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.iconConfirm
  979. case let str where str.contains("pages"):
  980. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.iconPages
  981. default:
  982. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.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: "") + " " + utilityFileSystem.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 = NCImageCache.images.folderEncrypted
  1083. } else if isShare {
  1084. cell.filePreviewImageView?.image = NCImageCache.images.folderSharedWithMe
  1085. } else if !metadata.shareType.isEmpty {
  1086. metadata.shareType.contains(3) ?
  1087. (cell.filePreviewImageView?.image = NCImageCache.images.folderPublic) :
  1088. (cell.filePreviewImageView?.image = NCImageCache.images.folderSharedWithMe)
  1089. } else if !metadata.shareType.isEmpty && metadata.shareType.contains(3) {
  1090. cell.filePreviewImageView?.image = NCImageCache.images.folderPublic
  1091. } else if metadata.mountType == "group" {
  1092. cell.filePreviewImageView?.image = NCImageCache.images.folderGroup
  1093. } else if isMounted {
  1094. cell.filePreviewImageView?.image = NCImageCache.images.folderExternal
  1095. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1096. cell.filePreviewImageView?.image = NCImageCache.images.folderAutomaticUpload
  1097. } else {
  1098. cell.filePreviewImageView?.image = NCImageCache.images.folder
  1099. }
  1100. // Local image: offline
  1101. if let tableDirectory, tableDirectory.offline {
  1102. cell.fileLocalImage?.image = NCImageCache.images.offlineFlag
  1103. }
  1104. // color folder
  1105. cell.filePreviewImageView?.image = cell.filePreviewImageView?.image?.colorizeFolder(metadata: metadata, tableDirectory: tableDirectory)
  1106. } else {
  1107. let tableLocalFile = NCManageDatabase.shared.getResultsTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))?.first
  1108. // image local
  1109. if let tableLocalFile, tableLocalFile.offline {
  1110. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1111. cell.fileLocalImage?.image = NCImageCache.images.offlineFlag
  1112. } else if utilityFileSystem.fileProviderStorageExists(metadata) {
  1113. cell.fileLocalImage?.image = NCImageCache.images.local
  1114. }
  1115. }
  1116. // image Favorite
  1117. if metadata.favorite {
  1118. cell.fileFavoriteImage?.image = NCImageCache.images.favorite
  1119. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1120. }
  1121. // Share image
  1122. if isShare {
  1123. cell.fileSharedImage?.image = NCImageCache.images.shared
  1124. } else if !metadata.shareType.isEmpty {
  1125. metadata.shareType.contains(3) ?
  1126. (cell.fileSharedImage?.image = NCImageCache.images.shareByLink) :
  1127. (cell.fileSharedImage?.image = NCImageCache.images.shared)
  1128. } else {
  1129. cell.fileSharedImage?.image = NCImageCache.images.canShare
  1130. }
  1131. if appDelegate.account != metadata.account {
  1132. cell.fileSharedImage?.image = NCImageCache.images.shared
  1133. }
  1134. // Button More
  1135. if metadata.isInTransfer || metadata.isWaitingTransfer {
  1136. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCImageCache.images.buttonStop)
  1137. } else if metadata.lock == true {
  1138. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCImageCache.images.buttonMoreLock)
  1139. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1140. } else {
  1141. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCImageCache.images.buttonMore)
  1142. }
  1143. // Write status on Label Info
  1144. switch metadata.status {
  1145. case NCGlobal.shared.metadataStatusWaitDownload:
  1146. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1147. case NCGlobal.shared.metadataStatusInDownload:
  1148. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1149. case NCGlobal.shared.metadataStatusDownloading:
  1150. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size) + " - ↓ …"
  1151. case NCGlobal.shared.metadataStatusWaitUpload:
  1152. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1153. cell.fileLocalImage?.image = nil
  1154. case NCGlobal.shared.metadataStatusInUpload:
  1155. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1156. cell.fileLocalImage?.image = nil
  1157. case NCGlobal.shared.metadataStatusUploading:
  1158. cell.fileInfoLabel?.text = utilityFileSystem.transformedSize(metadata.size) + " - ↑ …"
  1159. cell.fileLocalImage?.image = nil
  1160. case NCGlobal.shared.metadataStatusUploadError:
  1161. if metadata.sessionError.isEmpty {
  1162. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1163. } else {
  1164. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1165. }
  1166. default:
  1167. break
  1168. }
  1169. // Live Photo
  1170. if metadata.isLivePhoto {
  1171. cell.fileStatusImage?.image = NCImageCache.images.livePhoto
  1172. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1173. }
  1174. // URL
  1175. if metadata.classFile == NKCommon.TypeClassFile.url.rawValue {
  1176. cell.fileLocalImage?.image = nil
  1177. cell.hideButtonShare(true)
  1178. cell.hideButtonMore(true)
  1179. if let ownerId = getAvatarFromIconUrl(metadata: metadata) {
  1180. cell.fileUser = ownerId
  1181. }
  1182. }
  1183. // Separator
  1184. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearchingMode {
  1185. cell.cellSeparatorView?.isHidden = true
  1186. } else {
  1187. cell.cellSeparatorView?.isHidden = false
  1188. }
  1189. // Edit mode
  1190. if isEditMode {
  1191. cell.selectMode(true)
  1192. if selectOcId.contains(metadata.ocId) {
  1193. cell.selected(true)
  1194. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1195. } else {
  1196. cell.selected(false)
  1197. }
  1198. } else {
  1199. cell.selectMode(false)
  1200. }
  1201. // Accessibility
  1202. cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
  1203. // Color string find in search
  1204. if isSearchingMode, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
  1205. let longestWordRange = (title.lowercased() as NSString).range(of: literalSearch)
  1206. let attributedString = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)])
  1207. attributedString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor: UIColor.systemBlue], range: longestWordRange)
  1208. cell.fileTitleLabel?.attributedText = attributedString
  1209. }
  1210. // Add TAGS
  1211. cell.setTags(tags: Array(metadata.tags))
  1212. // Hide buttons
  1213. if metadata.name != NCGlobal.shared.appName {
  1214. cell.titleInfoTrailingFull()
  1215. cell.hideButtonShare(true)
  1216. cell.hideButtonMore(true)
  1217. }
  1218. return cell
  1219. }
  1220. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1221. if kind == UICollectionView.elementKindSectionHeader {
  1222. if indexPath.section == 0 {
  1223. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as? NCSectionHeaderMenu else { return UICollectionReusableView() }
  1224. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1225. self.headerMenu = header
  1226. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1227. header.setImageSwitchList()
  1228. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1229. } else {
  1230. header.setImageSwitchGrid()
  1231. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1232. }
  1233. header.delegate = self
  1234. if !isSearchingMode, headerMenuTransferView, let ocId = NCNetworking.shared.transferInForegorund?.ocId {
  1235. let text = String(format: NSLocalizedString("_upload_foreground_msg_", comment: ""), NCBrandOptions.shared.brand)
  1236. header.setViewTransfer(isHidden: false, ocId: ocId, text: text, progress: NCNetworking.shared.transferInForegorund?.progress)
  1237. } else {
  1238. header.setViewTransfer(isHidden: true)
  1239. }
  1240. if headerMenuButtonsView {
  1241. header.setStatusButtonsView(enable: !dataSource.getMetadataSourceForAllSections().isEmpty)
  1242. header.setButtonsView(height: NCGlobal.shared.heightButtonsView)
  1243. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  1244. } else {
  1245. header.setButtonsView(height: 0)
  1246. }
  1247. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1248. header.setRichWorkspaceText(richWorkspaceText)
  1249. header.setSectionHeight(heightHeaderSection)
  1250. if heightHeaderSection == 0 {
  1251. header.labelSection.text = ""
  1252. } else {
  1253. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1254. }
  1255. header.labelSection.textColor = .label
  1256. return header
  1257. } else {
  1258. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as? NCSectionHeader else { return UICollectionReusableView() }
  1259. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1260. header.labelSection.textColor = .label
  1261. return header
  1262. }
  1263. } else {
  1264. guard let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as? NCSectionFooter else { return UICollectionReusableView() }
  1265. let sections = dataSource.numberOfSections()
  1266. let section = indexPath.section
  1267. let metadataForSection = self.dataSource.getMetadataForSection(indexPath.section)
  1268. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1269. let metadatasCount: Int = metadataForSection?.metadatas.count ?? 0
  1270. let unifiedSearchInProgress = metadataForSection?.unifiedSearchInProgress ?? false
  1271. footer.delegate = self
  1272. footer.metadataForSection = metadataForSection
  1273. footer.setTitleLabel("")
  1274. footer.setButtonText(NSLocalizedString("_show_more_results_", comment: ""))
  1275. footer.separatorIsHidden(true)
  1276. footer.buttonIsHidden(true)
  1277. footer.hideActivityIndicatorSection()
  1278. if isSearchingMode {
  1279. if sections > 1 && section != sections - 1 {
  1280. footer.separatorIsHidden(false)
  1281. }
  1282. // If the number of entries(metadatas) is lower than the cursor, then there are no more entries.
  1283. // 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.
  1284. // This is as good as it gets for determining last page without server-side flag.
  1285. let isLastPage = (metadatasCount < metadataForSection?.lastSearchResult?.cursor ?? 0) || metadataForSection?.lastSearchResult?.entries.isEmpty == true
  1286. if isSearchingMode && isPaginated && metadatasCount > 0 && !isLastPage {
  1287. footer.buttonIsHidden(false)
  1288. }
  1289. if unifiedSearchInProgress {
  1290. footer.showActivityIndicatorSection()
  1291. }
  1292. } else {
  1293. if sections == 1 || section == sections - 1 {
  1294. let info = dataSource.getFooterInformationAllMetadatas()
  1295. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1296. } else {
  1297. footer.separatorIsHidden(false)
  1298. }
  1299. }
  1300. return footer
  1301. }
  1302. }
  1303. }
  1304. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1305. func getHeaderHeight() -> CGFloat {
  1306. var size: CGFloat = 0
  1307. // transfer in progress
  1308. if headerMenuTransferView,
  1309. let metadata = NCManageDatabase.shared.getMetadataFromOcId(NCNetworking.shared.transferInForegorund?.ocId),
  1310. metadata.isTransferInForeground {
  1311. if !isSearchingMode {
  1312. size += NCGlobal.shared.heightHeaderTransfer
  1313. }
  1314. } else {
  1315. NCNetworking.shared.transferInForegorund = nil
  1316. }
  1317. if headerMenuButtonsView {
  1318. size += NCGlobal.shared.heightButtonsView
  1319. }
  1320. return size
  1321. }
  1322. func getHeaderHeight(section: Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1323. var headerRichWorkspace: CGFloat = 0
  1324. if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
  1325. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1326. if !trimmed.isEmpty && !isSearchingMode {
  1327. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1328. }
  1329. }
  1330. if isSearchingMode || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  1331. if section == 0 {
  1332. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1333. } else {
  1334. return (0, 0, NCGlobal.shared.heightSection)
  1335. }
  1336. } else {
  1337. return (getHeaderHeight(), headerRichWorkspace, 0)
  1338. }
  1339. }
  1340. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1341. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1342. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1343. return CGSize(width: collectionView.frame.width, height: heightHeader)
  1344. }
  1345. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1346. let sections = dataSource.numberOfSections()
  1347. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1348. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1349. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1350. var size = CGSize(width: collectionView.frame.width, height: 0)
  1351. if section == sections - 1 {
  1352. size.height += NCGlobal.shared.endHeightFooter
  1353. } else {
  1354. size.height += NCGlobal.shared.heightFooter
  1355. }
  1356. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1357. size.height += NCGlobal.shared.heightFooterButton
  1358. }
  1359. return size
  1360. }
  1361. }
  1362. extension NCCollectionViewCommon: EasyTipViewDelegate {
  1363. func easyTipViewDidTap(_ tipView: EasyTipView) {
  1364. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1365. }
  1366. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  1367. func dismissTip() {
  1368. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1369. self.tipView?.dismiss()
  1370. }
  1371. }
  1372. extension NCCollectionViewCommon {
  1373. func getAvatarFromIconUrl(metadata: tableMetadata) -> String? {
  1374. var ownerId: String?
  1375. if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  1376. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  1377. var found: Bool = false
  1378. for item in splitIconUrl {
  1379. if found {
  1380. ownerId = item
  1381. break
  1382. }
  1383. if item == "avatar" { found = true}
  1384. }
  1385. }
  1386. return ownerId
  1387. }
  1388. }
  1389. // MARK: -
  1390. class NCOperationUnifiedSearch: ConcurrentOperation {
  1391. var collectionViewCommon: NCCollectionViewCommon
  1392. var metadatas: [tableMetadata]
  1393. var searchResult: NKSearchResult
  1394. init(collectionViewCommon: NCCollectionViewCommon, metadatas: [tableMetadata], searchResult: NKSearchResult) {
  1395. self.collectionViewCommon = collectionViewCommon
  1396. self.metadatas = metadatas
  1397. self.searchResult = searchResult
  1398. }
  1399. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  1400. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  1401. CATransaction.begin()
  1402. CATransaction.setCompletionBlock(closure)
  1403. self.collectionViewCommon.collectionView.reloadData()
  1404. CATransaction.commit()
  1405. }
  1406. }
  1407. override func start() {
  1408. guard !isCancelled else { return self.finish() }
  1409. self.collectionViewCommon.dataSource.addSection(metadatas: metadatas, searchResult: searchResult)
  1410. self.collectionViewCommon.searchResults?.append(self.searchResult)
  1411. reloadDataThenPerform {
  1412. self.finish()
  1413. }
  1414. }
  1415. }
  1416. class NCCollectionViewDownloadThumbnail: ConcurrentOperation {
  1417. var metadata: tableMetadata
  1418. var cell: NCCellProtocol?
  1419. var collectionView: UICollectionView?
  1420. var fileNamePath: String
  1421. var fileNamePreviewLocalPath: String
  1422. var fileNameIconLocalPath: String
  1423. let utilityFileSystem = NCUtilityFileSystem()
  1424. init(metadata: tableMetadata, cell: NCCellProtocol?, collectionView: UICollectionView?) {
  1425. self.metadata = tableMetadata.init(value: metadata)
  1426. self.cell = cell
  1427. self.collectionView = collectionView
  1428. self.fileNamePath = utilityFileSystem.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId)
  1429. self.fileNamePreviewLocalPath = utilityFileSystem.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)
  1430. self.fileNameIconLocalPath = utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)
  1431. }
  1432. override func start() {
  1433. guard !isCancelled else { return self.finish() }
  1434. var etagResource: String?
  1435. if FileManager.default.fileExists(atPath: fileNameIconLocalPath) && FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  1436. etagResource = metadata.etagResource
  1437. }
  1438. NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: fileNamePath,
  1439. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  1440. widthPreview: NCGlobal.shared.sizePreview,
  1441. heightPreview: NCGlobal.shared.sizePreview,
  1442. fileNameIconLocalPath: fileNameIconLocalPath,
  1443. sizeIcon: NCGlobal.shared.sizeIcon,
  1444. etag: etagResource,
  1445. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, _, imageIcon, _, etag, error in
  1446. if error == .success, let image = imageIcon {
  1447. NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
  1448. DispatchQueue.main.async {
  1449. if self.metadata.ocId == self.cell?.fileObjectId, let filePreviewImageView = self.cell?.filePreviewImageView {
  1450. UIView.transition(with: filePreviewImageView,
  1451. duration: 0.75,
  1452. options: .transitionCrossDissolve,
  1453. animations: { filePreviewImageView.image = image },
  1454. completion: nil)
  1455. } else {
  1456. self.collectionView?.reloadData()
  1457. }
  1458. }
  1459. }
  1460. self.finish()
  1461. }
  1462. }
  1463. }