NCCollectionViewCommon.swift 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670
  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, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, UIAdaptivePresentationControllerDelegate {
  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 serverUrl: String = ""
  31. internal var isEncryptedFolder = false
  32. internal var isEditMode = false
  33. internal var selectOcId: [String] = []
  34. internal var metadatasSource: [tableMetadata] = []
  35. internal var metadataFolder: tableMetadata?
  36. internal var metadataTouch: tableMetadata?
  37. internal var dataSource = NCDataSource()
  38. internal var richWorkspaceText: String?
  39. internal var layout = ""
  40. internal var sort: String = ""
  41. internal var ascending: Bool = true
  42. internal var directoryOnTop: Bool = true
  43. internal var groupBy = ""
  44. internal var titleButton = ""
  45. internal var itemForLine = 0
  46. private var autoUploadFileName = ""
  47. private var autoUploadDirectory = ""
  48. internal var listLayout: NCListLayout!
  49. internal var gridLayout: NCGridLayout!
  50. private let headerHeight: CGFloat = 50
  51. private var headerRichWorkspaceHeight: CGFloat = 0
  52. private let footerHeight: CGFloat = 100
  53. private var timerInputSearch: Timer?
  54. internal var literalSearch: String?
  55. internal var isSearching: Bool = false
  56. internal var isReloadDataSourceNetworkInProgress: Bool = false
  57. // DECLARE
  58. internal var layoutKey = ""
  59. internal var titleCurrentFolder = ""
  60. internal var enableSearchBar: Bool = false
  61. internal var DZNimage: UIImage?
  62. internal var DZNtitle: String = ""
  63. internal var DZNdescription: String = ""
  64. required init?(coder aDecoder: NSCoder) {
  65. super.init(coder: aDecoder)
  66. }
  67. override func viewDidLoad() {
  68. super.viewDidLoad()
  69. if enableSearchBar {
  70. searchController = UISearchController(searchResultsController: nil)
  71. searchController?.searchResultsUpdater = self
  72. searchController?.dimsBackgroundDuringPresentation = false
  73. searchController?.delegate = self
  74. searchController?.searchBar.delegate = self
  75. navigationItem.searchController = searchController
  76. navigationItem.hidesSearchBarWhenScrolling = false
  77. }
  78. // Cell
  79. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  80. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  81. collectionView.register(UINib.init(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  82. // Header
  83. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  84. // Footer
  85. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  86. collectionView.alwaysBounceVertical = true
  87. listLayout = NCListLayout()
  88. gridLayout = NCGridLayout()
  89. // Refresh Control
  90. collectionView.addSubview(refreshControl)
  91. refreshControl.tintColor = .gray
  92. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  93. // empty Data Source
  94. self.collectionView.emptyDataSetDelegate = self
  95. self.collectionView.emptyDataSetSource = self
  96. // 3D Touch peek and pop
  97. if traitCollection.forceTouchCapability == .available {
  98. registerForPreviewing(with: self, sourceView: view)
  99. }
  100. // Long Press on CollectionView
  101. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  102. longPressedGesture.minimumPressDuration = 0.5
  103. longPressedGesture.delegate = self
  104. longPressedGesture.delaysTouchesBegan = true
  105. collectionView.addGestureRecognizer(longPressedGesture)
  106. // Notification
  107. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSourceNetworkForced), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_changeStatusFolderE2EE), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: k_notificationCenter_closeRichWorkspaceWebView), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  124. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  125. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  126. changeTheming()
  127. }
  128. override func viewWillAppear(_ animated: Bool) {
  129. super.viewWillAppear(animated)
  130. appDelegate.activeViewController = self
  131. if serverUrl == "" {
  132. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  133. } else {
  134. appDelegate.activeServerUrl = serverUrl
  135. }
  136. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  137. gridLayout.itemForLine = CGFloat(itemForLine)
  138. if layout == k_layout_list {
  139. collectionView?.collectionViewLayout = listLayout
  140. } else {
  141. collectionView?.collectionViewLayout = gridLayout
  142. }
  143. navigationController?.navigationBar.prefersLargeTitles = true
  144. navigationController?.setNavigationBarHidden(false, animated: false)
  145. setNavigationItem()
  146. reloadDataSource()
  147. }
  148. override func viewDidAppear(_ animated: Bool) {
  149. super.viewDidAppear(animated)
  150. reloadDataSourceNetwork()
  151. }
  152. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  153. let viewController = presentationController.presentedViewController
  154. if viewController is NCViewerRichWorkspaceWebView {
  155. closeRichWorkspaceWebView()
  156. } else if viewController is UINavigationController {
  157. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  158. appDelegate.activeFileViewInFolder = nil
  159. }
  160. }
  161. }
  162. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  163. super.viewWillTransition(to: size, with: coordinator)
  164. coordinator.animate(alongsideTransition: nil) { _ in
  165. self.collectionView?.collectionViewLayout.invalidateLayout()
  166. }
  167. }
  168. override var canBecomeFirstResponder: Bool {
  169. return true
  170. }
  171. func setNavigationItem() {
  172. if isEditMode {
  173. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  174. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  175. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  176. } else {
  177. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  178. navigationItem.leftBarButtonItem = nil
  179. navigationItem.title = titleCurrentFolder
  180. }
  181. }
  182. // MARK: - NotificationCenter
  183. @objc func initializeMain() {
  184. if appDelegate.account.count == 0 { return }
  185. if searchController?.isActive ?? false {
  186. searchController?.isActive = false
  187. }
  188. // set active serverUrl
  189. if self.view?.window != nil {
  190. if serverUrl == "" {
  191. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  192. } else {
  193. appDelegate.activeServerUrl = serverUrl
  194. }
  195. }
  196. self.navigationController?.popToRootViewController(animated: false)
  197. appDelegate.listFilesVC.removeAllObjects()
  198. appDelegate.listFavoriteVC.removeAllObjects()
  199. appDelegate.listOfflineVC.removeAllObjects()
  200. reloadDataSource()
  201. }
  202. @objc func changeTheming() {
  203. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  204. collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  205. collectionView.reloadData()
  206. }
  207. @objc func reloadDataSource(_ notification: NSNotification) {
  208. if self.view?.window == nil { return }
  209. reloadDataSource()
  210. }
  211. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  212. if self.view?.window == nil { return }
  213. if let userInfo = notification.userInfo as NSDictionary? {
  214. if let serverUrl = userInfo["serverUrl"] as? String {
  215. if serverUrl == self.serverUrl {
  216. reloadDataSourceNetwork(forced: true)
  217. }
  218. }
  219. }
  220. }
  221. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  222. if self.view?.window == nil { return }
  223. reloadDataSource()
  224. }
  225. @objc func closeRichWorkspaceWebView() {
  226. if self.view?.window == nil { return }
  227. reloadDataSourceNetwork()
  228. }
  229. @objc func deleteFile(_ notification: NSNotification) {
  230. if self.view?.window == nil { return }
  231. if let userInfo = notification.userInfo as NSDictionary? {
  232. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  233. if onlyLocal {
  234. reloadDataSource()
  235. } else if metadata.fileNameView.lowercased() == k_fileNameRichWorkspace.lowercased() {
  236. reloadDataSourceNetwork(forced: true)
  237. } else {
  238. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  239. let indexPath = IndexPath(row: row, section: 0)
  240. collectionView?.performBatchUpdates({
  241. collectionView?.deleteItems(at: [indexPath])
  242. }, completion: { (_) in
  243. self.collectionView?.reloadData()
  244. })
  245. }
  246. }
  247. }
  248. }
  249. }
  250. @objc func moveFile(_ notification: NSNotification) {
  251. if self.view?.window == nil { return }
  252. if let userInfo = notification.userInfo as NSDictionary? {
  253. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata {
  254. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  255. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  256. let indexPath = IndexPath(row: row, section: 0)
  257. collectionView?.performBatchUpdates({
  258. collectionView?.deleteItems(at: [indexPath])
  259. }, completion: { (_) in
  260. self.collectionView?.reloadData()
  261. })
  262. }
  263. } else if metadataNew.serverUrl == serverUrl && metadata.account == appDelegate.account {
  264. if let row = dataSource.addMetadata(metadataNew) {
  265. let indexPath = IndexPath(row: row, section: 0)
  266. collectionView?.performBatchUpdates({
  267. collectionView?.insertItems(at: [indexPath])
  268. }, completion: { (_) in
  269. self.collectionView?.reloadData()
  270. })
  271. }
  272. }
  273. }
  274. }
  275. }
  276. @objc func copyFile(_ notification: NSNotification) {
  277. if self.view?.window == nil { return }
  278. if let userInfo = notification.userInfo as NSDictionary? {
  279. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  280. if serverUrlTo == self.serverUrl {
  281. reloadDataSource()
  282. }
  283. }
  284. }
  285. }
  286. @objc func renameFile(_ notification: NSNotification) {
  287. if self.view?.window == nil { return }
  288. reloadDataSource()
  289. }
  290. @objc func createFolder(_ notification: NSNotification) {
  291. if self.view?.window == nil { return }
  292. if let userInfo = notification.userInfo as NSDictionary? {
  293. if let metadata = userInfo["metadata"] as? tableMetadata {
  294. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  295. if let row = dataSource.addMetadata(metadata) {
  296. let indexPath = IndexPath(row: row, section: 0)
  297. collectionView?.performBatchUpdates({
  298. collectionView?.insertItems(at: [indexPath])
  299. }, completion: { (_) in
  300. self.collectionView?.reloadData()
  301. })
  302. }
  303. }
  304. }
  305. } else {
  306. reloadDataSourceNetwork()
  307. }
  308. }
  309. @objc func favoriteFile(_ notification: NSNotification) {
  310. if self.view?.window == nil { return }
  311. if let userInfo = notification.userInfo as NSDictionary? {
  312. if let metadata = userInfo["metadata"] as? tableMetadata {
  313. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  314. reloadDataSource()
  315. }
  316. }
  317. }
  318. }
  319. @objc func downloadStartFile(_ notification: NSNotification) {
  320. if self.view?.window == nil { return }
  321. if let userInfo = notification.userInfo as NSDictionary? {
  322. if let metadata = userInfo["metadata"] as? tableMetadata {
  323. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  324. let indexPath = IndexPath(row: row, section: 0)
  325. collectionView?.reloadItems(at: [indexPath])
  326. }
  327. }
  328. }
  329. }
  330. @objc func downloadedFile(_ notification: NSNotification) {
  331. if self.view?.window == nil { return }
  332. if let userInfo = notification.userInfo as NSDictionary? {
  333. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  334. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  335. let indexPath = IndexPath(row: row, section: 0)
  336. collectionView?.reloadItems(at: [indexPath])
  337. }
  338. }
  339. }
  340. }
  341. @objc func downloadCancelFile(_ notification: NSNotification) {
  342. if self.view?.window == nil { return }
  343. if let userInfo = notification.userInfo as NSDictionary? {
  344. if let metadata = userInfo["metadata"] as? tableMetadata {
  345. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  346. let indexPath = IndexPath(row: row, section: 0)
  347. collectionView?.reloadItems(at: [indexPath])
  348. }
  349. }
  350. }
  351. }
  352. @objc func uploadStartFile(_ notification: NSNotification) {
  353. if self.view?.window == nil { return }
  354. if let userInfo = notification.userInfo as NSDictionary? {
  355. if let metadata = userInfo["metadata"] as? tableMetadata {
  356. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  357. if let row = dataSource.addMetadata(metadata) {
  358. let indexPath = IndexPath(row: row, section: 0)
  359. collectionView?.performBatchUpdates({
  360. collectionView?.insertItems(at: [indexPath])
  361. }, completion: { (_) in
  362. self.collectionView?.reloadData()
  363. })
  364. }
  365. }
  366. }
  367. }
  368. }
  369. @objc func uploadedFile(_ notification: NSNotification) {
  370. if self.view?.window == nil { return }
  371. if let userInfo = notification.userInfo as NSDictionary? {
  372. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  373. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  374. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  375. collectionView?.reloadData()
  376. }
  377. }
  378. }
  379. }
  380. @objc func uploadCancelFile(_ notification: NSNotification) {
  381. if self.view?.window == nil { return }
  382. if let userInfo = notification.userInfo as NSDictionary? {
  383. if let metadata = userInfo["metadata"] as? tableMetadata {
  384. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  385. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  386. let indexPath = IndexPath(row: row, section: 0)
  387. collectionView?.performBatchUpdates({
  388. collectionView?.deleteItems(at: [indexPath])
  389. }, completion: { (_) in
  390. self.collectionView?.reloadData()
  391. })
  392. } else {
  393. self.reloadDataSource()
  394. }
  395. }
  396. }
  397. }
  398. }
  399. @objc func triggerProgressTask(_ notification: NSNotification) {
  400. if self.view?.window == nil { return }
  401. if let userInfo = notification.userInfo as NSDictionary? {
  402. if let ocId = userInfo["ocId"] as? String {
  403. let _ = userInfo["account"] as? String ?? ""
  404. let _ = userInfo["serverUrl"] as? String ?? ""
  405. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  406. let progress = progressNumber.floatValue
  407. let status = userInfo["status"] as? Int ?? Int(k_metadataStatusNormal)
  408. let totalBytes = userInfo["totalBytes"] as? Double ?? 0
  409. let totalBytesExpected = userInfo["totalBytesExpected"] as? Double ?? 0
  410. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  411. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  412. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  413. if cell is NCListCell {
  414. let cell = cell as! NCListCell
  415. if progress > 0 {
  416. cell.progressView?.isHidden = false
  417. cell.progressView?.progress = progress
  418. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  419. if status == k_metadataStatusInDownload {
  420. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  421. } else if status == k_metadataStatusInUpload {
  422. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  423. }
  424. }
  425. } else if cell is NCTransferCell {
  426. let cell = cell as! NCTransferCell
  427. if progress > 0 {
  428. cell.progressView?.isHidden = false
  429. cell.progressView?.progress = progress
  430. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  431. if status == k_metadataStatusInDownload {
  432. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  433. } else if status == k_metadataStatusInUpload {
  434. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  435. }
  436. }
  437. } else if cell is NCGridCell {
  438. let cell = cell as! NCGridCell
  439. if progress > 0 {
  440. cell.progressView.isHidden = false
  441. cell.progressView.progress = progress
  442. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  443. }
  444. }
  445. }
  446. }
  447. }
  448. }
  449. }
  450. // MARK: - DZNEmpty
  451. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  452. return NCBrandColor.sharedInstance.backgroundView
  453. }
  454. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  455. if searchController?.isActive ?? false {
  456. return CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: .gray)
  457. }
  458. if isReloadDataSourceNetworkInProgress {
  459. return CCGraphics.changeThemingColorImage(UIImage.init(named: "networkInProgress"), width: 300, height: 300, color: .gray)
  460. }
  461. return DZNimage
  462. }
  463. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  464. var text = "\n"+NSLocalizedString(DZNtitle, comment: "")
  465. if isReloadDataSourceNetworkInProgress {
  466. text = "\n"+NSLocalizedString("_request_in_progress_", comment: "")
  467. }
  468. if searchController?.isActive ?? false {
  469. if isReloadDataSourceNetworkInProgress {
  470. text = "\n"+NSLocalizedString("_search_in_progress_", comment: "")
  471. } else {
  472. text = "\n"+NSLocalizedString("_search_no_record_found_", comment: "")
  473. }
  474. }
  475. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.gray]
  476. return NSAttributedString.init(string: text, attributes: attributes)
  477. }
  478. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  479. var text = "\n"+NSLocalizedString(DZNdescription, comment: "")
  480. if isReloadDataSourceNetworkInProgress {
  481. text = ""
  482. }
  483. if searchController?.isActive ?? false {
  484. text = "\n"+NSLocalizedString("_search_instruction_", comment: "")
  485. }
  486. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  487. return NSAttributedString.init(string: text, attributes: attributes)
  488. }
  489. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  490. return true
  491. }
  492. // MARK: - SEARCH
  493. func updateSearchResults(for searchController: UISearchController) {
  494. timerInputSearch?.invalidate()
  495. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  496. literalSearch = searchController.searchBar.text
  497. collectionView?.reloadData()
  498. }
  499. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  500. isSearching = true
  501. metadatasSource.removeAll()
  502. reloadDataSource()
  503. }
  504. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  505. isSearching = false
  506. literalSearch = ""
  507. reloadDataSource()
  508. }
  509. // MARK: - TAP EVENT
  510. @objc func tapSelect(sender: Any) {
  511. isEditMode = !isEditMode
  512. selectOcId.removeAll()
  513. setNavigationItem()
  514. self.collectionView.reloadData()
  515. }
  516. func tapSwitchHeader(sender: Any) {
  517. if collectionView.collectionViewLayout == gridLayout {
  518. // list layout
  519. UIView.animate(withDuration: 0.0, animations: {
  520. self.collectionView.collectionViewLayout.invalidateLayout()
  521. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  522. self.collectionView.reloadData()
  523. })
  524. })
  525. layout = k_layout_list
  526. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  527. } else {
  528. // grid layout
  529. UIView.animate(withDuration: 0.0, animations: {
  530. self.collectionView.collectionViewLayout.invalidateLayout()
  531. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  532. self.collectionView.reloadData()
  533. })
  534. })
  535. layout = k_layout_grid
  536. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  537. }
  538. }
  539. func tapOrderHeader(sender: Any) {
  540. let sortMenu = NCSortMenu()
  541. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  542. }
  543. @objc func tapSelectMenu(sender: Any) {
  544. guard let tabBarController = self.tabBarController else { return }
  545. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  546. }
  547. func tapMoreHeader(sender: Any) { }
  548. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  549. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  550. }
  551. func tapShareListItem(with objectId: String, sender: Any) {
  552. if isEditMode { return }
  553. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  554. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  555. }
  556. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  557. if isEditMode { return }
  558. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  559. if namedButtonMore == k_buttonMoreMore {
  560. toggleMoreMenu(viewController: self, metadata: metadata)
  561. } else if namedButtonMore == k_buttonMoreStop {
  562. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  563. }
  564. }
  565. func tapRichWorkspace(sender: Any) {
  566. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  567. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  568. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  569. viewerRichWorkspace.serverUrl = serverUrl
  570. navigationController.modalPresentationStyle = .fullScreen
  571. self.present(navigationController, animated: true, completion: nil)
  572. }
  573. }
  574. }
  575. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  576. openMenuItems(with: objectId, gestureRecognizer: gestureRecognizer)
  577. }
  578. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  579. openMenuItems(with: objectId, gestureRecognizer: gestureRecognizer)
  580. }
  581. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  582. }
  583. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  584. }
  585. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  586. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  587. }
  588. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  589. if gestureRecognizer.state != .began { return }
  590. if serverUrl == "" { return }
  591. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  592. metadataTouch = metadata
  593. } else {
  594. metadataTouch = nil
  595. }
  596. var listMenuItems: [UIMenuItem] = []
  597. let touchPoint = gestureRecognizer.location(in: collectionView)
  598. becomeFirstResponder()
  599. if metadataTouch != nil {
  600. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  601. }
  602. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  603. if metadataTouch != nil {
  604. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  605. if !NCBrandOptions.sharedInstance.disable_openin_file {
  606. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  607. }
  608. }
  609. if listMenuItems.count > 0 {
  610. UIMenuController.shared.menuItems = listMenuItems
  611. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  612. UIMenuController.shared.setMenuVisible(true, animated: true)
  613. }
  614. }
  615. // MARK: - Menu Item
  616. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  617. if (#selector(pasteFilesMenu(_:)) == action) {
  618. if UIPasteboard.general.items.count > 0 {
  619. return true
  620. }
  621. }
  622. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  623. guard let metadata = metadataTouch else { return false }
  624. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  625. return true
  626. }
  627. }
  628. return false
  629. }
  630. @objc func copyFileMenu(_ notification: Any) {
  631. var metadatas: [tableMetadata] = []
  632. var items = [[String : Any]]()
  633. if isEditMode {
  634. for ocId in selectOcId {
  635. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  636. metadatas.append(metadata)
  637. }
  638. }
  639. } else {
  640. guard let metadata = metadataTouch else { return }
  641. metadatas.append(metadata)
  642. }
  643. for metadata in metadatas {
  644. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  645. do {
  646. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  647. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  648. } catch {
  649. print("error")
  650. }
  651. } else {
  652. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  653. }
  654. }
  655. UIPasteboard.general.setItems(items, options: [:])
  656. if isEditMode {
  657. tapSelect(sender: self)
  658. }
  659. }
  660. @objc func pasteFilesMenu(_ notification: Any) {
  661. var listData: [String] = []
  662. for item in UIPasteboard.general.items {
  663. for object in item {
  664. let contentType = object.key
  665. let data = object.value
  666. if contentType == k_metadataKeyedUnarchiver {
  667. do {
  668. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  669. uploadPasteOcId(ocId)
  670. }
  671. } catch {
  672. print("error")
  673. }
  674. continue
  675. }
  676. if data is String {
  677. if listData.contains(data as! String) {
  678. continue
  679. } else {
  680. listData.append(data as! String)
  681. }
  682. }
  683. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  684. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  685. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  686. }
  687. }
  688. }
  689. }
  690. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  691. do {
  692. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  693. let ocId = UUID().uuidString
  694. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  695. if data is UIImage {
  696. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  697. } else if data is Data {
  698. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  699. } else if data is String {
  700. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  701. } else {
  702. return
  703. }
  704. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  705. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  706. metadataForUpload.sessionSelector = selectorUploadFile
  707. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  708. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  709. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  710. } catch { }
  711. }
  712. private func uploadPasteOcId(_ ocId: String) {
  713. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  714. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  715. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  716. let ocId = NSUUID().uuidString
  717. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  718. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  719. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  720. metadataForUpload.sessionSelector = selectorUploadFile
  721. metadataForUpload.size = metadata.size
  722. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  723. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  724. }
  725. }
  726. }
  727. @objc func openQuickLookMenu(_ notification: Any) {
  728. guard let metadata = metadataTouch else { return }
  729. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  730. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  731. } else {
  732. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  733. }
  734. }
  735. @objc func openInMenu(_ notification: Any) {
  736. guard let metadata = metadataTouch else { return }
  737. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  738. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  739. } else {
  740. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  741. }
  742. }
  743. // MARK: - SEGUE
  744. @objc func segue(metadata: tableMetadata) {
  745. self.metadataTouch = metadata
  746. performSegue(withIdentifier: "segueDetail", sender: self)
  747. }
  748. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  749. let photoDataSource: NSMutableArray = []
  750. for metadata in (dataSource.metadatas) {
  751. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  752. photoDataSource.add(metadata)
  753. }
  754. }
  755. if let segueNavigationController = segue.destination as? UINavigationController {
  756. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  757. segueViewController.metadata = metadataTouch
  758. segueViewController.layoutKey = layoutKey
  759. }
  760. } else if let segueViewController = segue.destination as? NCDetailViewController {
  761. segueViewController.metadata = metadataTouch
  762. segueViewController.layoutKey = layoutKey
  763. }
  764. }
  765. // MARK: - DataSource + NC Endpoint
  766. @objc func reloadDataSource() {
  767. if appDelegate.account.count == 0 { return }
  768. // Get richWorkspace Text
  769. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  770. richWorkspaceText = directory?.richWorkspace
  771. // E2EE
  772. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  773. // get auto upload folder
  774. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  775. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  776. // get layout for view
  777. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  778. }
  779. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  780. @objc func reloadDataSourceNetworkRefreshControl() {
  781. reloadDataSourceNetwork(forced: true)
  782. }
  783. @objc func networkSearch() {
  784. if appDelegate.account.count == 0 { return }
  785. if literalSearch?.count ?? 0 > 1 {
  786. isReloadDataSourceNetworkInProgress = true
  787. collectionView?.reloadData()
  788. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  789. if self.searchController?.isActive ?? false && errorCode == 0 {
  790. self.metadatasSource = metadatas!
  791. }
  792. self.refreshControl.endRefreshing()
  793. self.isReloadDataSourceNetworkInProgress = false
  794. self.reloadDataSource()
  795. }
  796. } else {
  797. self.refreshControl.endRefreshing()
  798. }
  799. }
  800. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  801. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  802. if errorCode == 0 {
  803. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  804. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  805. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  806. if errorCode == 0 {
  807. self.metadataFolder = metadataFolder
  808. // E2EE
  809. if let metadataFolder = metadataFolder {
  810. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  811. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  812. if errorCode == 0 && e2eMetadata != nil {
  813. if !NCEndToEndMetadata.sharedInstance.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  814. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  815. } else {
  816. self.reloadDataSource()
  817. }
  818. } else if errorCode != k_CCErrorResourceNotFound {
  819. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  820. }
  821. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  822. }
  823. } else {
  824. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  825. }
  826. } else {
  827. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  828. }
  829. } else {
  830. completion(nil, nil, errorCode, errorDescription)
  831. }
  832. }
  833. } else {
  834. completion(nil, nil, 0, "")
  835. }
  836. } else {
  837. completion(nil, nil, errorCode, errorDescription)
  838. }
  839. }
  840. }
  841. }
  842. // MARK: - 3D Touch peek and pop
  843. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  844. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  845. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  846. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  847. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  848. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  849. viewController.metadata = metadata
  850. if layout == k_layout_grid {
  851. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  852. previewingContext.sourceRect = cell.frame
  853. viewController.imageFile = cell.imageItem.image
  854. } else {
  855. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  856. previewingContext.sourceRect = cell.frame
  857. viewController.imageFile = cell.imageItem.image
  858. }
  859. viewController.showOpenIn = true
  860. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  861. viewController.showShare = false
  862. return viewController
  863. }
  864. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  865. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  866. collectionView(collectionView, didSelectItemAt: indexPath)
  867. }
  868. }
  869. // MARK: - Collection View
  870. extension NCCollectionViewCommon: UICollectionViewDelegate {
  871. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  872. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  873. metadataTouch = metadata
  874. if isEditMode {
  875. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  876. selectOcId.remove(at: index)
  877. } else {
  878. selectOcId.append(metadata.ocId)
  879. }
  880. collectionView.reloadItems(at: [indexPath])
  881. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  882. return
  883. }
  884. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  885. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  886. return
  887. }
  888. if metadata.directory {
  889. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  890. // FILES
  891. if layoutKey == k_layout_view_files {
  892. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  893. guard let vcFiles = (viewController as? NCFiles) else { return }
  894. if vcFiles.isViewLoaded {
  895. self.navigationController?.pushViewController(vcFiles, animated: true)
  896. }
  897. } else {
  898. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  899. vcFiles.isRoot = false
  900. vcFiles.serverUrl = serverUrlPush
  901. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  902. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  903. self.navigationController?.pushViewController(vcFiles, animated: true)
  904. }
  905. }
  906. // FAVORITE
  907. if layoutKey == k_layout_view_favorite {
  908. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  909. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  910. if vcFavorite.isViewLoaded {
  911. self.navigationController?.pushViewController(vcFavorite, animated: true)
  912. }
  913. } else {
  914. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  915. vcFavorite.serverUrl = serverUrlPush
  916. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  917. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  918. self.navigationController?.pushViewController(vcFavorite, animated: true)
  919. }
  920. }
  921. // OFFLINE
  922. if layoutKey == k_layout_view_offline {
  923. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  924. guard let vcOffline = (viewController as? NCOffline) else { return }
  925. if vcOffline.isViewLoaded {
  926. self.navigationController?.pushViewController(vcOffline, animated: true)
  927. }
  928. } else {
  929. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  930. vcOffline.serverUrl = serverUrlPush
  931. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  932. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  933. self.navigationController?.pushViewController(vcOffline, animated: true)
  934. }
  935. }
  936. // RECENT ( for push use Files ... he he he )
  937. if layoutKey == k_layout_view_recent {
  938. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  939. guard let vcFiles = (viewController as? NCFiles) else { return }
  940. if vcFiles.isViewLoaded {
  941. self.navigationController?.pushViewController(vcFiles, animated: true)
  942. }
  943. } else {
  944. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  945. vcFiles.isRoot = false
  946. vcFiles.serverUrl = serverUrlPush
  947. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  948. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  949. self.navigationController?.pushViewController(vcFiles, animated: true)
  950. }
  951. }
  952. if layoutKey == k_layout_view_viewInFolder {
  953. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  954. vcFileViewInFolder.serverUrl = serverUrlPush
  955. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  956. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  957. }
  958. } else {
  959. guard let metadataTouch = metadataTouch else { return }
  960. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  961. if NCCommunication.shared.isNetworkReachable() {
  962. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  963. } else {
  964. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  965. }
  966. return
  967. }
  968. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  969. if NCCommunication.shared.isNetworkReachable() {
  970. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  971. } else {
  972. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  973. }
  974. return
  975. }
  976. if metadata.typeFile == k_metadataTypeFile_video {
  977. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  978. return
  979. }
  980. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  981. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  982. } else {
  983. NCNetworking.shared.download(metadata: metadataTouch, selector: selectorLoadFileView) { (_) in }
  984. }
  985. }
  986. }
  987. func collectionViewSelectAll() {
  988. selectOcId.removeAll()
  989. for metadata in metadatasSource {
  990. selectOcId.append(metadata.ocId)
  991. }
  992. collectionView.reloadData()
  993. }
  994. }
  995. extension NCCollectionViewCommon: UICollectionViewDataSource {
  996. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  997. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  998. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  999. }
  1000. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1001. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1002. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  1003. }
  1004. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1005. if kind == UICollectionView.elementKindSectionHeader {
  1006. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1007. if collectionView.collectionViewLayout == gridLayout {
  1008. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  1009. } else {
  1010. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  1011. }
  1012. header.delegate = self
  1013. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  1014. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  1015. header.setStatusButton(count: dataSource.metadatas.count)
  1016. header.setTitleSorted(datasourceTitleButton: titleButton)
  1017. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  1018. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  1019. return header
  1020. } else {
  1021. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1022. let info = dataSource.getFilesInformation()
  1023. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  1024. return footer
  1025. }
  1026. }
  1027. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1028. return 1
  1029. }
  1030. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1031. return dataSource.numberOfItems()
  1032. }
  1033. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1034. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1035. return UICollectionViewCell()
  1036. }
  1037. var tableShare: tableShare?
  1038. var isShare = false
  1039. var isMounted = false
  1040. if metadataFolder != nil {
  1041. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  1042. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  1043. }
  1044. if dataSource.metadataShare[metadata.ocId] != nil {
  1045. tableShare = dataSource.metadataShare[metadata.ocId]
  1046. }
  1047. //
  1048. // LAYOUT LIST
  1049. //
  1050. if layout == k_layout_list {
  1051. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1052. cell.delegate = self
  1053. cell.objectId = metadata.ocId
  1054. cell.indexPath = indexPath
  1055. cell.labelTitle.text = metadata.fileNameView
  1056. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1057. cell.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  1058. cell.imageSelect.image = nil
  1059. cell.imageStatus.image = nil
  1060. cell.imageLocal.image = nil
  1061. cell.imageFavorite.image = nil
  1062. cell.imageShared.image = nil
  1063. cell.imageMore.image = nil
  1064. cell.imageItem.image = nil
  1065. cell.imageItem.backgroundColor = nil
  1066. cell.progressView.progress = 0.0
  1067. if metadata.directory {
  1068. if metadata.e2eEncrypted {
  1069. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1070. } else if isShare {
  1071. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1072. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1073. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1074. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1075. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1076. } else if metadata.mountType == "group" {
  1077. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1078. } else if isMounted {
  1079. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1080. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1081. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1082. } else {
  1083. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1084. }
  1085. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  1086. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1087. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1088. // Local image: offline
  1089. if tableDirectory != nil && tableDirectory!.offline {
  1090. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1091. }
  1092. } else {
  1093. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1094. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1095. } else {
  1096. if metadata.hasPreview {
  1097. cell.imageItem.backgroundColor = .lightGray
  1098. } else {
  1099. if metadata.iconName.count > 0 {
  1100. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1101. } else {
  1102. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1103. }
  1104. }
  1105. }
  1106. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1107. // image local
  1108. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1109. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1110. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1111. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1112. }
  1113. }
  1114. // image Favorite
  1115. if metadata.favorite {
  1116. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1117. }
  1118. // Share image
  1119. if (isShare) {
  1120. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1121. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1122. cell.imageShared.image = NCCollectionCommon.images.cellShareByLinkImage
  1123. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1124. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1125. } else {
  1126. cell.imageShared.image = NCCollectionCommon.images.cellCanShareImage
  1127. }
  1128. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userID {
  1129. // Load avatar
  1130. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  1131. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  1132. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  1133. cell.imageShared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  1134. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  1135. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1136. } else {
  1137. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  1138. if errorCode == 0 && account == self.appDelegate.account {
  1139. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1140. }
  1141. }
  1142. }
  1143. }
  1144. // Transfer
  1145. var progress: Float = 0.0
  1146. var totalBytes: Double = 0.0
  1147. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  1148. if progressArray != nil && progressArray?.count == 3 {
  1149. progress = progressArray?.object(at: 0) as? Float ?? 0
  1150. totalBytes = progressArray?.object(at: 1) as? Double ?? 0
  1151. }
  1152. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1153. cell.progressView.isHidden = false
  1154. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1155. } else {
  1156. cell.progressView.isHidden = true
  1157. cell.progressView.progress = progress
  1158. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1159. }
  1160. // Write status on Label Info
  1161. switch metadata.status {
  1162. case Int(k_metadataStatusWaitDownload):
  1163. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1164. break
  1165. case Int(k_metadataStatusInDownload):
  1166. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1167. break
  1168. case Int(k_metadataStatusDownloading):
  1169. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1170. break
  1171. case Int(k_metadataStatusWaitUpload):
  1172. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1173. break
  1174. case Int(k_metadataStatusInUpload):
  1175. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1176. break
  1177. case Int(k_metadataStatusUploading):
  1178. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1179. break
  1180. default:
  1181. break
  1182. }
  1183. // Live Photo
  1184. if metadata.livePhoto {
  1185. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1186. }
  1187. // E2EE
  1188. if metadata.e2eEncrypted || isEncryptedFolder {
  1189. cell.hideButtonShare(true)
  1190. } else {
  1191. cell.hideButtonShare(false)
  1192. }
  1193. // Remove last separator
  1194. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1195. cell.separator.isHidden = true
  1196. } else {
  1197. cell.separator.isHidden = false
  1198. }
  1199. // Edit mode
  1200. if isEditMode {
  1201. cell.selectMode(true)
  1202. if selectOcId.contains(metadata.ocId) {
  1203. cell.selected(true)
  1204. } else {
  1205. cell.selected(false)
  1206. }
  1207. } else {
  1208. cell.selectMode(false)
  1209. }
  1210. return cell
  1211. }
  1212. //
  1213. // LAYOUT GRID
  1214. //
  1215. if layout == k_layout_grid {
  1216. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1217. cell.delegate = self
  1218. cell.objectId = metadata.ocId
  1219. cell.indexPath = indexPath
  1220. cell.labelTitle.text = metadata.fileNameView
  1221. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1222. cell.imageSelect.image = nil
  1223. cell.imageStatus.image = nil
  1224. cell.imageLocal.image = nil
  1225. cell.imageFavorite.image = nil
  1226. cell.imageItem.image = nil
  1227. cell.imageItem.backgroundColor = nil
  1228. cell.progressView.progress = 0.0
  1229. if metadata.directory {
  1230. if metadata.e2eEncrypted {
  1231. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1232. } else if isShare {
  1233. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1234. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1235. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1236. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1237. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1238. } else if metadata.mountType == "group" {
  1239. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1240. } else if isMounted {
  1241. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1242. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1243. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1244. } else {
  1245. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1246. }
  1247. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1248. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1249. // Local image: offline
  1250. if tableDirectory != nil && tableDirectory!.offline {
  1251. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1252. }
  1253. } else {
  1254. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1255. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1256. } else {
  1257. if metadata.hasPreview {
  1258. cell.imageItem.backgroundColor = .lightGray
  1259. } else {
  1260. if metadata.iconName.count > 0 {
  1261. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1262. } else {
  1263. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1264. }
  1265. }
  1266. }
  1267. // image Local
  1268. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1269. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1270. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1271. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1272. }
  1273. }
  1274. // image Favorite
  1275. if metadata.favorite {
  1276. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1277. }
  1278. // Transfer
  1279. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1280. cell.progressView.isHidden = false
  1281. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1282. } else {
  1283. cell.progressView.isHidden = true
  1284. cell.progressView.progress = 0.0
  1285. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1286. }
  1287. // Live Photo
  1288. if metadata.livePhoto {
  1289. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1290. }
  1291. // Edit mode
  1292. if isEditMode {
  1293. cell.selectMode(true)
  1294. if selectOcId.contains(metadata.ocId) {
  1295. cell.selected(true)
  1296. } else {
  1297. cell.selected(false)
  1298. }
  1299. } else {
  1300. cell.selectMode(false)
  1301. }
  1302. return cell
  1303. }
  1304. return UICollectionViewCell()
  1305. }
  1306. }
  1307. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1308. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1309. headerRichWorkspaceHeight = 0
  1310. if let richWorkspaceText = richWorkspaceText {
  1311. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1312. if trimmed.count > 0 && !isSearching {
  1313. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1314. }
  1315. }
  1316. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1317. }
  1318. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1319. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1320. }
  1321. }