NCCollectionViewCommon.swift 80 KB

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