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