NCCollectionViewCommon.swift 76 KB

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