NCCollectionViewCommon.swift 81 KB

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