NCCollectionViewCommon.swift 83 KB

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