NCCollectionViewCommon.swift 81 KB

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