NCCollectionViewCommon.swift 79 KB

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