NCCollectionViewCommon.swift 85 KB

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