NCCollectionViewCommon.swift 85 KB

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