NCCollectionViewCommon.swift 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  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.metadatasSource }
  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 headerMenu: 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 = 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: headerHeight, 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. // MARK: - BackgroundImageColor Delegate
  555. func colorPickerCancel() {
  556. changeTheming()
  557. }
  558. func colorPickerWillChange(color: UIColor) {
  559. collectionView.backgroundColor = color
  560. }
  561. func colorPickerDidChange(lightColor: String, darkColor: String) {
  562. NCManageDatabase.shared.setAccountColorFiles(lightColorBackground: lightColor, darkColorBackground: darkColor)
  563. changeTheming()
  564. }
  565. // MARK: - Empty
  566. func emptyDataSetView(_ view: NCEmptyView) {
  567. if isSearching {
  568. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  569. if isReloadDataSourceNetworkInProgress {
  570. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  571. } else {
  572. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  573. }
  574. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  575. } else if isReloadDataSourceNetworkInProgress {
  576. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  577. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  578. view.emptyDescription.text = ""
  579. } else {
  580. if serverUrl == "" {
  581. view.emptyImage.image = emptyImage
  582. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  583. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  584. } else {
  585. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  586. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  587. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  588. }
  589. }
  590. }
  591. // MARK: - SEARCH
  592. func updateSearchResults(for searchController: UISearchController) {
  593. timerInputSearch?.invalidate()
  594. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  595. literalSearch = searchController.searchBar.text
  596. collectionView?.reloadData()
  597. }
  598. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  599. isSearching = true
  600. metadatasSource.removeAll()
  601. reloadDataSource()
  602. }
  603. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  604. isSearching = false
  605. literalSearch = ""
  606. reloadDataSource()
  607. }
  608. // MARK: - TAP EVENT
  609. func accountRequestChangeAccount(account: String) {
  610. NCManageDatabase.shared.setAccountActive(account)
  611. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  612. NCOperationQueue.shared.cancelAllQueue()
  613. NCNetworking.shared.cancelAllTask()
  614. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  615. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  616. }
  617. }
  618. func accountRequestAddAccount() {
  619. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  620. }
  621. func tapSwitchHeader(sender: Any) {
  622. if collectionView.collectionViewLayout == gridLayout {
  623. // list layout
  624. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  625. UIView.animate(withDuration: 0.0, animations: {
  626. self.collectionView.collectionViewLayout.invalidateLayout()
  627. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { _ in
  628. self.collectionView.reloadData()
  629. })
  630. })
  631. layoutForView?.layout = NCGlobal.shared.layoutList
  632. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  633. } else {
  634. // grid layout
  635. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  636. UIView.animate(withDuration: 0.0, animations: {
  637. self.collectionView.collectionViewLayout.invalidateLayout()
  638. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { _ in
  639. self.collectionView.reloadData()
  640. })
  641. })
  642. layoutForView?.layout = NCGlobal.shared.layoutGrid
  643. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  644. }
  645. }
  646. func tapOrderHeader(sender: Any) {
  647. let sortMenu = NCSortMenu()
  648. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  649. }
  650. func tapMoreHeader(sender: Any) { }
  651. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  652. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  653. }
  654. func tapShareListItem(with objectId: String, sender: Any) {
  655. if isEditMode { return }
  656. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  657. NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .sharing)
  658. }
  659. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  660. if isEditMode { return }
  661. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  662. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  663. toggleMenu(metadata: metadata, imageIcon: image)
  664. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  665. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  666. }
  667. }
  668. func tapRichWorkspace(sender: Any) {
  669. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  670. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  671. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  672. viewerRichWorkspace.serverUrl = serverUrl
  673. navigationController.modalPresentationStyle = .fullScreen
  674. self.present(navigationController, animated: true, completion: nil)
  675. }
  676. }
  677. }
  678. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  679. }
  680. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  681. }
  682. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  683. }
  684. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  685. }
  686. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  687. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  688. /*
  689. if #available(iOS 13.0, *) {
  690. let interaction = UIContextMenuInteraction(delegate: self)
  691. self.view.addInteraction(interaction)
  692. }
  693. */
  694. }
  695. @available(iOS 13.0, *)
  696. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  697. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  698. return nil
  699. }, actionProvider: { _ in
  700. // let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  701. // }
  702. // return UIMenu(title: "Main Menu", children: [share])
  703. return nil
  704. })
  705. }
  706. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  707. if gestureRecognizer.state != .began { return }
  708. var listMenuItems: [UIMenuItem] = []
  709. let touchPoint = gestureRecognizer.location(in: collectionView)
  710. becomeFirstResponder()
  711. if serverUrl != "" {
  712. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  713. }
  714. if #available(iOS 13.0, *) {
  715. if !NCBrandOptions.shared.disable_background_color {
  716. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_background_", comment: ""), action: #selector(backgroundFilesMenu)))
  717. }
  718. }
  719. if listMenuItems.count > 0 {
  720. UIMenuController.shared.menuItems = listMenuItems
  721. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  722. UIMenuController.shared.setMenuVisible(true, animated: true)
  723. }
  724. }
  725. // MARK: - Menu Item
  726. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  727. if #selector(pasteFilesMenu) == action {
  728. if UIPasteboard.general.items.count > 0 {
  729. return true
  730. }
  731. }
  732. if #selector(backgroundFilesMenu) == action {
  733. return true
  734. }
  735. return false
  736. }
  737. @objc func pasteFilesMenu() {
  738. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  739. }
  740. @objc func backgroundFilesMenu() {
  741. if let vcBackgroundImageColor = UIStoryboard(name: "NCBackgroundImageColor", bundle: nil).instantiateInitialViewController() as? NCBackgroundImageColor {
  742. vcBackgroundImageColor.delegate = self
  743. vcBackgroundImageColor.setupColor = collectionView.backgroundColor
  744. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  745. vcBackgroundImageColor.lightColor = activeAccount.lightColorBackground
  746. vcBackgroundImageColor.darkColor = activeAccount.darkColorBackground
  747. }
  748. let popup = NCPopupViewController(contentController: vcBackgroundImageColor, popupWidth: vcBackgroundImageColor.width, popupHeight: vcBackgroundImageColor.height)
  749. popup.backgroundAlpha = 0
  750. self.present(popup, animated: true)
  751. }
  752. }
  753. // MARK: - DataSource + NC Endpoint
  754. @objc func reloadDataSource() {
  755. if appDelegate.account == "" { return }
  756. // Get richWorkspace Text
  757. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  758. richWorkspaceText = directory?.richWorkspace
  759. // E2EE
  760. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  761. // get auto upload folder
  762. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  763. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  764. // get layout for view
  765. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  766. }
  767. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  768. @objc func networkSearch() {
  769. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  770. else {
  771. DispatchQueue.main.async { self.refreshControl.endRefreshing() }
  772. return
  773. }
  774. let completionHandler: ([tableMetadata]?, Int, String) -> Void = { metadatas, errorCode, errorDescription in
  775. DispatchQueue.main.async {
  776. if self.searchController?.isActive == true, errorCode == 0, let metadatas = metadatas {
  777. self.metadatasSource = metadatas
  778. }
  779. self.refreshControl.endRefreshing()
  780. self.isReloadDataSourceNetworkInProgress = false
  781. self.reloadDataSource()
  782. }
  783. }
  784. isReloadDataSourceNetworkInProgress = true
  785. collectionView?.reloadData()
  786. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  787. if serverVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  788. NCNetworking.shared.unifiedSearchFiles(urlBase: appDelegate, literal: literalSearch, update: { metadatas in
  789. guard let metadatas = metadatas, metadatas.count > 0 else { return }
  790. DispatchQueue.main.async {
  791. // update
  792. /*
  793. var indexPaths: [IndexPath] = []
  794. guard let metadatas = metadatas else { return }
  795. for metadata in metadatas {
  796. if let indexPath = self.dataSource.addMetadata(metadata, withCreateMetadatas: false) {
  797. indexPaths.append(indexPath)
  798. }
  799. }
  800. self.metadatasSource = self.dataSource.createMetadatas()
  801. self.collectionView?.performBatchUpdates({
  802. self.collectionView?.insertItems(at: indexPaths)
  803. }, completion: { _ in
  804. self.collectionView?.reloadData()
  805. })
  806. */
  807. }
  808. }, completion: completionHandler)
  809. } else {
  810. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch, completion: completionHandler)
  811. }
  812. }
  813. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  814. var tableDirectory: tableDirectory?
  815. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { (account, metadataFolder, errorCode, errorDescription) in
  816. if errorCode == 0 {
  817. if let metadataFolder = metadataFolder {
  818. tableDirectory = NCManageDatabase.shared.setDirectory(richWorkspace: metadataFolder.richWorkspace, serverUrl: self.serverUrl, account: account)
  819. }
  820. if forced || tableDirectory?.etag != metadataFolder?.etag || metadataFolder?.e2eEncrypted ?? false {
  821. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { account, metadataFolder, metadatas, metadatasUpdate, _, metadatasDelete, errorCode, errorDescription in
  822. if errorCode == 0 {
  823. self.metadataFolder = metadataFolder
  824. // E2EE
  825. if let metadataFolder = metadataFolder {
  826. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  827. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { account, e2eMetadata, errorCode, errorDescription in
  828. if errorCode == 0 && e2eMetadata != nil {
  829. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  830. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  831. } else {
  832. self.reloadDataSource()
  833. }
  834. } else if errorCode != NCGlobal.shared.errorResourceNotFound {
  835. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  836. }
  837. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  838. }
  839. } else {
  840. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  841. }
  842. } else {
  843. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  844. }
  845. } else {
  846. completion(tableDirectory, nil, nil, nil, errorCode, errorDescription)
  847. }
  848. }
  849. } else {
  850. completion(tableDirectory, nil, nil, nil, 0, "")
  851. }
  852. } else {
  853. completion(nil, nil, nil, nil, errorCode, errorDescription)
  854. }
  855. }
  856. }
  857. // MARK: - Push metadata
  858. func pushMetadata(_ metadata: tableMetadata) {
  859. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  860. appDelegate.activeMetadata = metadata
  861. // FILES
  862. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  863. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  864. if viewController.isViewLoaded {
  865. pushViewController(viewController: viewController)
  866. }
  867. } else {
  868. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  869. viewController.isRoot = false
  870. viewController.serverUrl = serverUrlPush
  871. viewController.titleCurrentFolder = metadata.fileNameView
  872. appDelegate.listFilesVC[serverUrlPush] = viewController
  873. pushViewController(viewController: viewController)
  874. }
  875. }
  876. }
  877. // FAVORITE
  878. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  879. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  880. if viewController.isViewLoaded {
  881. pushViewController(viewController: viewController)
  882. }
  883. } else {
  884. if let viewController: NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  885. viewController.serverUrl = serverUrlPush
  886. viewController.titleCurrentFolder = metadata.fileNameView
  887. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  888. pushViewController(viewController: viewController)
  889. }
  890. }
  891. }
  892. // OFFLINE
  893. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  894. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  895. if viewController.isViewLoaded {
  896. pushViewController(viewController: viewController)
  897. }
  898. } else {
  899. if let viewController: NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  900. viewController.serverUrl = serverUrlPush
  901. viewController.titleCurrentFolder = metadata.fileNameView
  902. appDelegate.listOfflineVC[serverUrlPush] = viewController
  903. pushViewController(viewController: viewController)
  904. }
  905. }
  906. }
  907. // RECENT ( for push use Files ... he he he )
  908. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  909. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  910. if viewController.isViewLoaded {
  911. pushViewController(viewController: viewController)
  912. }
  913. } else {
  914. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  915. viewController.isRoot = false
  916. viewController.serverUrl = serverUrlPush
  917. viewController.titleCurrentFolder = metadata.fileNameView
  918. appDelegate.listFilesVC[serverUrlPush] = viewController
  919. pushViewController(viewController: viewController)
  920. }
  921. }
  922. }
  923. // VIEW IN FOLDER
  924. if layoutKey == NCGlobal.shared.layoutViewViewInFolder && !pushed {
  925. if let viewController: NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder {
  926. viewController.serverUrl = serverUrlPush
  927. viewController.titleCurrentFolder = metadata.fileNameView
  928. pushViewController(viewController: viewController)
  929. }
  930. }
  931. // SHARES ( for push use Files ... he he he )
  932. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  933. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  934. if viewController.isViewLoaded {
  935. pushViewController(viewController: viewController)
  936. }
  937. } else {
  938. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  939. viewController.isRoot = false
  940. viewController.serverUrl = serverUrlPush
  941. viewController.titleCurrentFolder = metadata.fileNameView
  942. appDelegate.listFilesVC[serverUrlPush] = viewController
  943. pushViewController(viewController: viewController)
  944. }
  945. }
  946. }
  947. }
  948. }
  949. // MARK: - Collection View
  950. extension NCCollectionViewCommon: UICollectionViewDelegate {
  951. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  952. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  953. appDelegate.activeMetadata = metadata
  954. if isEditMode {
  955. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  956. selectOcId.remove(at: index)
  957. } else {
  958. selectOcId.append(metadata.ocId)
  959. }
  960. collectionView.reloadItems(at: [indexPath])
  961. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatasSource.count)"
  962. return
  963. }
  964. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  965. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorE2EENotEnabled)
  966. return
  967. }
  968. if metadata.directory {
  969. pushMetadata(metadata)
  970. } else if !(self is NCFileViewInFolder) {
  971. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  972. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  973. var metadatas: [tableMetadata] = []
  974. for metadata in dataSource.metadatasSource {
  975. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  976. metadatas.append(metadata)
  977. }
  978. }
  979. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  980. return
  981. }
  982. if CCUtility.fileProviderStorageExists(metadata) {
  983. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  984. } else if NCCommunication.shared.isNetworkReachable() {
  985. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _ in }
  986. } else {
  987. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorOffline)
  988. }
  989. }
  990. }
  991. func pushViewController(viewController: UIViewController) {
  992. if pushed { return }
  993. pushed = true
  994. navigationController?.pushViewController(viewController, animated: true)
  995. }
  996. @available(iOS 13.0, *)
  997. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  998. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  999. if isEditMode || metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue { return nil }
  1000. let identifier = indexPath as NSCopying
  1001. var image: UIImage?
  1002. let cell = collectionView.cellForItem(at: indexPath)
  1003. if cell is NCListCell {
  1004. image = (cell as! NCListCell).imageItem.image
  1005. } else if cell is NCGridCell {
  1006. image = (cell as! NCGridCell).imageItem.image
  1007. }
  1008. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  1009. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  1010. }, actionProvider: { _ in
  1011. return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: true, enableViewInFolder: false, image: image)
  1012. })
  1013. }
  1014. @available(iOS 13.0, *)
  1015. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  1016. animator.addCompletion {
  1017. if let indexPath = configuration.identifier as? IndexPath {
  1018. self.collectionView(collectionView, didSelectItemAt: indexPath)
  1019. }
  1020. }
  1021. }
  1022. }
  1023. extension NCCollectionViewCommon: UICollectionViewDataSource {
  1024. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1025. if kind == UICollectionView.elementKindSectionHeader {
  1026. if dataSource.numberOfSections() == 1 {
  1027. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1028. self.headerMenu = header
  1029. if collectionView.collectionViewLayout == gridLayout {
  1030. header.buttonSwitch.setImage(UIImage(named: "switchList")!.image(color: NCBrandColor.shared.gray, size: 50), for: .normal)
  1031. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1032. } else {
  1033. header.buttonSwitch.setImage(UIImage(named: "switchGrid")!.image(color: NCBrandColor.shared.gray, size: 50), for: .normal)
  1034. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1035. }
  1036. header.delegate = self
  1037. header.setStatusButton(count: dataSource.metadatasSource.count)
  1038. header.setTitleSorted(datasourceTitleButton: layoutForView?.titleButtonHeader ?? "")
  1039. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  1040. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  1041. return header
  1042. } else {
  1043. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  1044. header.labelSection.text = self.dataSource.getSectionValue(indexPath: indexPath).firstUppercased
  1045. header.labelSection.textColor = NCBrandColor.shared.brandElement
  1046. return header
  1047. }
  1048. } else {
  1049. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1050. if dataSource.numberOfSections() == 1 {
  1051. let info = dataSource.getFooterInformation()
  1052. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  1053. } else {
  1054. footer.setTitleLabel(text: "")
  1055. }
  1056. return footer
  1057. }
  1058. }
  1059. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1060. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1061. // Thumbnail
  1062. if !metadata.directory {
  1063. if metadata.name == "files" {
  1064. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1065. (cell as! NCCellProtocol).filePreviewImageView?.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1066. } else {
  1067. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1068. }
  1069. } else {
  1070. // Unified search
  1071. switch metadata.iconName {
  1072. case let str where str.contains("contacts"):
  1073. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1074. case let str where str.contains("conversation"):
  1075. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1076. case let str where str.contains("calendar"):
  1077. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1078. case let str where str.contains("deck"):
  1079. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1080. case let str where str.contains("mail"):
  1081. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconMail
  1082. case let str where str.contains("talk"):
  1083. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1084. default:
  1085. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1086. }
  1087. //var urlString: String = ""
  1088. if !metadata.iconUrl.isEmpty {
  1089. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol {
  1090. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1091. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1092. }
  1093. /*
  1094. if metadata.iconUrl.starts(with: "/apps") {
  1095. //urlString = metadata.urlBase + metadata.iconUrl
  1096. } else if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  1097. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  1098. var found:Bool = false
  1099. var ownerId: String = ""
  1100. for item in splitIconUrl {
  1101. if found {
  1102. ownerId = item
  1103. break
  1104. }
  1105. if item == "avatar" { found = true}
  1106. }
  1107. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1108. if let cell = cell as? NCCellProtocol {
  1109. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1110. }
  1111. }
  1112. // NCCommunication.shared.downloadContent(serverUrl: urlString) { _, data, errorCode, _ in
  1113. // if errorCode == 0, let data = data, let image = UIImage(data: data) {
  1114. // (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1115. // }
  1116. // }
  1117. */
  1118. }
  1119. }
  1120. }
  1121. // Avatar
  1122. if metadata.ownerId.count > 0,
  1123. metadata.ownerId != appDelegate.userId,
  1124. appDelegate.account == metadata.account,
  1125. let cell = cell as? NCCellProtocol {
  1126. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1127. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1128. }
  1129. }
  1130. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1131. }
  1132. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1133. return dataSource.numberOfSections()
  1134. }
  1135. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1136. let numberItems = dataSource.numberOfItemsInSection(section)
  1137. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1138. return numberItems
  1139. }
  1140. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1141. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1142. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1143. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1144. } else {
  1145. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1146. }
  1147. }
  1148. var isShare = false
  1149. var isMounted = false
  1150. if metadataFolder != nil {
  1151. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1152. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1153. }
  1154. let tableShare = dataSource.metadatasForSection[indexPath.section].metadataShare[metadata.ocId]
  1155. //
  1156. // LAYOUT LIST
  1157. //
  1158. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1159. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1160. cell.delegate = self
  1161. cell.fileObjectId = metadata.ocId
  1162. cell.fileUser = metadata.ownerId
  1163. if isSearching {
  1164. if metadata.name == "files" {
  1165. cell.labelTitle.text = NCUtilityFileSystem.shared.getPath(metadata: metadata)
  1166. cell.labelTitle.lineBreakMode = .byTruncatingHead
  1167. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1168. } else {
  1169. cell.labelTitle.text = metadata.fileName
  1170. cell.labelTitle.lineBreakMode = .byTruncatingTail
  1171. cell.labelInfo.text = metadata.subline
  1172. }
  1173. } else {
  1174. cell.labelTitle.text = metadata.fileNameView
  1175. cell.labelTitle.lineBreakMode = .byTruncatingMiddle
  1176. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1177. }
  1178. cell.labelTitle.textColor = NCBrandColor.shared.label
  1179. cell.labelInfo.textColor = NCBrandColor.shared.systemGray
  1180. cell.imageSelect.image = nil
  1181. cell.imageStatus.image = nil
  1182. cell.imageLocal.image = nil
  1183. cell.imageFavorite.image = nil
  1184. cell.imageShared.image = nil
  1185. cell.imageMore.image = nil
  1186. cell.imageItem.image = nil
  1187. cell.imageItem.backgroundColor = nil
  1188. cell.hideButtonShare(false)
  1189. cell.hideButtonMore(false)
  1190. // Progress
  1191. var progress: Float = 0.0
  1192. var totalBytes: Int64 = 0
  1193. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1194. progress = progressType.progress
  1195. totalBytes = progressType.totalBytes
  1196. }
  1197. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1198. cell.progressView.isHidden = false
  1199. cell.progressView.progress = progress
  1200. } else {
  1201. cell.progressView.isHidden = true
  1202. cell.progressView.progress = 0.0
  1203. }
  1204. var a11yValues: [String] = []
  1205. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1206. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1207. }
  1208. if metadata.directory {
  1209. if metadata.e2eEncrypted {
  1210. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1211. } else if isShare {
  1212. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1213. } else if tableShare != nil && tableShare?.shareType != 3 {
  1214. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1215. } else if tableShare != nil && tableShare?.shareType == 3 {
  1216. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1217. } else if metadata.mountType == "group" {
  1218. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1219. } else if isMounted {
  1220. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1221. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1222. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1223. } else {
  1224. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1225. }
  1226. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1227. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1228. // Local image: offline
  1229. if tableDirectory != nil && tableDirectory!.offline {
  1230. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1231. }
  1232. } else {
  1233. // image local
  1234. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  1235. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1236. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1237. } else if CCUtility.fileProviderStorageExists(metadata) {
  1238. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1239. }
  1240. }
  1241. // image Favorite
  1242. if metadata.favorite {
  1243. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1244. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1245. }
  1246. // Share image
  1247. if isShare {
  1248. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1249. } else if tableShare != nil && tableShare?.shareType == 3 {
  1250. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  1251. } else if tableShare != nil && tableShare?.shareType != 3 {
  1252. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1253. } else {
  1254. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  1255. }
  1256. if appDelegate.account != metadata.account {
  1257. cell.imageShared.image = NCBrandColor.cacheImages.shared
  1258. }
  1259. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1260. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1261. } else if metadata.lock == true {
  1262. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1263. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1264. } else {
  1265. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1266. }
  1267. // Write status on Label Info
  1268. switch metadata.status {
  1269. case NCGlobal.shared.metadataStatusWaitDownload:
  1270. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1271. break
  1272. case NCGlobal.shared.metadataStatusInDownload:
  1273. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1274. break
  1275. case NCGlobal.shared.metadataStatusDownloading:
  1276. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1277. break
  1278. case NCGlobal.shared.metadataStatusWaitUpload:
  1279. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1280. break
  1281. case NCGlobal.shared.metadataStatusInUpload:
  1282. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1283. break
  1284. case NCGlobal.shared.metadataStatusUploading:
  1285. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1286. break
  1287. case NCGlobal.shared.metadataStatusUploadError:
  1288. if metadata.sessionError != "" {
  1289. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1290. } else {
  1291. cell.labelInfo.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1292. }
  1293. break
  1294. default:
  1295. break
  1296. }
  1297. cell.accessibilityLabel = metadata.fileNameView + ", " + (cell.labelInfo.text ?? "")
  1298. // Live Photo
  1299. if metadata.livePhoto {
  1300. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1301. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1302. }
  1303. // E2EE
  1304. if metadata.e2eEncrypted || isEncryptedFolder {
  1305. cell.hideButtonShare(true)
  1306. }
  1307. // URL
  1308. if metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue {
  1309. cell.imageLocal.image = nil
  1310. cell.hideButtonShare(true)
  1311. cell.hideButtonMore(true)
  1312. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1313. cell.fileUser = ownerId
  1314. }
  1315. }
  1316. // Disable Share Button
  1317. if appDelegate.disableSharesView {
  1318. cell.hideButtonShare(true)
  1319. }
  1320. // Separator
  1321. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearching {
  1322. cell.separator.isHidden = true
  1323. } else {
  1324. cell.separator.isHidden = false
  1325. }
  1326. // Edit mode
  1327. if isEditMode {
  1328. cell.selectMode(true)
  1329. if selectOcId.contains(metadata.ocId) {
  1330. cell.selected(true)
  1331. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1332. } else {
  1333. cell.selected(false)
  1334. }
  1335. } else {
  1336. cell.selectMode(false)
  1337. }
  1338. cell.accessibilityValue = a11yValues.joined(separator: ", ")
  1339. return cell
  1340. }
  1341. //
  1342. // LAYOUT GRID
  1343. //
  1344. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1345. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1346. cell.delegate = self
  1347. cell.fileObjectId = metadata.ocId
  1348. cell.fileUser = metadata.ownerId
  1349. cell.labelTitle.text = metadata.fileNameView
  1350. cell.labelTitle.textColor = NCBrandColor.shared.label
  1351. cell.imageSelect.image = nil
  1352. cell.imageStatus.image = nil
  1353. cell.imageLocal.image = nil
  1354. cell.imageFavorite.image = nil
  1355. cell.imageItem.image = nil
  1356. cell.imageItem.backgroundColor = nil
  1357. cell.hideButtonMore(false)
  1358. // Progress
  1359. var progress: Float = 0.0
  1360. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1361. progress = progressType.progress
  1362. }
  1363. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1364. cell.progressView.isHidden = false
  1365. cell.progressView.progress = progress
  1366. cell.accessibilityLabel = metadata.fileNameView + ", \(Int(progress * 100))%"
  1367. } else {
  1368. cell.progressView.isHidden = true
  1369. cell.progressView.progress = 0.0
  1370. cell.accessibilityLabel = metadata.fileNameView
  1371. }
  1372. var a11yValues: [String] = []
  1373. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1374. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1375. }
  1376. if metadata.directory {
  1377. if metadata.e2eEncrypted {
  1378. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  1379. } else if isShare {
  1380. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1381. } else if tableShare != nil && tableShare!.shareType != 3 {
  1382. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  1383. } else if tableShare != nil && tableShare!.shareType == 3 {
  1384. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  1385. } else if metadata.mountType == "group" {
  1386. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  1387. } else if isMounted {
  1388. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  1389. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1390. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1391. } else {
  1392. cell.imageItem.image = NCBrandColor.cacheImages.folder
  1393. }
  1394. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1395. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1396. // Local image: offline
  1397. if tableDirectory != nil && tableDirectory!.offline {
  1398. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1399. }
  1400. } else {
  1401. // image Local
  1402. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  1403. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  1404. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1405. } else if CCUtility.fileProviderStorageExists(metadata) {
  1406. cell.imageLocal.image = NCBrandColor.cacheImages.local
  1407. }
  1408. }
  1409. // image Favorite
  1410. if metadata.favorite {
  1411. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  1412. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1413. }
  1414. // Transfer
  1415. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1416. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1417. } else if metadata.lock == true {
  1418. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1419. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1420. } else {
  1421. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1422. }
  1423. // Live Photo
  1424. if metadata.livePhoto {
  1425. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  1426. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1427. }
  1428. // URL
  1429. if metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue {
  1430. cell.imageLocal.image = nil
  1431. cell.hideButtonMore(true)
  1432. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1433. cell.fileUser = ownerId
  1434. }
  1435. }
  1436. // Edit mode
  1437. if isEditMode {
  1438. cell.selectMode(true)
  1439. if selectOcId.contains(metadata.ocId) {
  1440. cell.selected(true)
  1441. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1442. } else {
  1443. cell.selected(false)
  1444. }
  1445. } else {
  1446. cell.selectMode(false)
  1447. }
  1448. cell.accessibilityValue = a11yValues.joined(separator: ", ")
  1449. return cell
  1450. }
  1451. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1452. }
  1453. }
  1454. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1455. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1456. headerRichWorkspaceHeight = 0
  1457. if let richWorkspaceText = richWorkspaceText {
  1458. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1459. if trimmed.count > 0 && !isSearching {
  1460. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1461. }
  1462. }
  1463. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1464. }
  1465. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1466. if dataSource.numberOfSections() == 1 {
  1467. return CGSize(width: collectionView.frame.width, height: footerEndHeight)
  1468. } else {
  1469. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1470. }
  1471. }
  1472. }