NCCollectionViewCommon.swift 88 KB

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