NCCollectionViewCommon.swift 84 KB

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