NCCollectionViewCommon.swift 87 KB

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