NCCollectionViewCommon.swift 87 KB

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