NCCollectionViewCommon.swift 88 KB

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