NCCollectionViewCommon.swift 84 KB

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