NCCollectionViewCommon.swift 84 KB

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