NCCollectionViewCommon.swift 79 KB

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