NCCollectionViewCommon.swift 84 KB

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