NCCollectionViewCommon.swift 86 KB

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