NCCollectionViewCommon.swift 87 KB

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