NCCollectionViewCommon.swift 84 KB

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