NCCollectionViewCommon.swift 91 KB

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