NCCollectionViewCommon.swift 78 KB

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