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