NCCollectionViewCommon.swift 88 KB

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