NCCollectionViewCommon.swift 82 KB

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