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