NCCollectionViewCommon.swift 91 KB

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