NCMedia.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. //
  2. // NCMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/02/2019.
  6. // Copyright © 2018 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 Sheeeeeeeeet
  25. class NCMedia: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, NCSelectDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. @IBOutlet weak var menuButtonMore: UIButton!
  28. @IBOutlet weak var menuButtonSwitch: UIButton!
  29. @IBOutlet weak var menuView: UIView!
  30. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. private var metadataPush: tableMetadata?
  32. private var isEditMode = false
  33. private var selectFileID = [String]()
  34. private var filterTypeFileImage = false;
  35. private var filterTypeFileVideo = false;
  36. private var sectionDatasource = CCSectionDataSourceMetadata()
  37. private var autoUploadFileName = ""
  38. private var autoUploadDirectory = ""
  39. private var gridLayout: NCGridMediaLayout!
  40. private var actionSheet: ActionSheet?
  41. private let sectionHeaderHeight: CGFloat = 50
  42. private let footerHeight: CGFloat = 50
  43. private var stepImageWidth: CGFloat = 10
  44. private var readRetry = 0
  45. private var isDistantPast = false
  46. private let refreshControl = UIRefreshControl()
  47. private var loadingSearch = false
  48. required init?(coder aDecoder: NSCoder) {
  49. super.init(coder: aDecoder)
  50. appDelegate.activeMedia = self
  51. }
  52. override func viewDidLoad() {
  53. super.viewDidLoad()
  54. // Cell
  55. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  56. // Header
  57. collectionView.register(UINib.init(nibName: "NCSectionMediaHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  58. // Footer
  59. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  60. collectionView.alwaysBounceVertical = true
  61. gridLayout = NCGridMediaLayout()
  62. gridLayout.preferenceWidth = CGFloat(CCUtility.getMediaWidthImage())
  63. gridLayout.sectionHeadersPinToVisibleBounds = true
  64. collectionView.collectionViewLayout = gridLayout
  65. // Add Refresh Control
  66. collectionView.refreshControl = refreshControl
  67. // Configure Refresh Control
  68. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  69. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  70. refreshControl.addTarget(self, action: #selector(loadNetworkDatasource), for: .valueChanged)
  71. // empty Data Source
  72. collectionView.emptyDataSetDelegate = self;
  73. collectionView.emptyDataSetSource = self;
  74. }
  75. override func viewWillAppear(_ animated: Bool) {
  76. super.viewWillAppear(animated)
  77. // Color
  78. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  79. appDelegate.aspectTabBar(self.tabBarController?.tabBar, hidden: false)
  80. menuView.backgroundColor = NCBrandColor.sharedInstance.brand
  81. menuButtonSwitch.setImage(UIImage(named: "switchGridChange")?.withRenderingMode(.alwaysTemplate), for: .normal)
  82. menuButtonSwitch.tintColor = NCBrandColor.sharedInstance.brandText
  83. menuButtonMore.setImage(UIImage(named: "moreBig")?.withRenderingMode(.alwaysTemplate), for: .normal)
  84. menuButtonMore.tintColor = NCBrandColor.sharedInstance.brandText
  85. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  86. // get auto upload folder
  87. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  88. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  89. selectSearchSections()
  90. }
  91. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  92. super.viewWillTransition(to: size, with: coordinator)
  93. coordinator.animate(alongsideTransition: nil) { _ in
  94. self.collectionView.collectionViewLayout.invalidateLayout()
  95. self.collectionView.reloadData()
  96. self.actionSheet?.viewDidLayoutSubviews()
  97. }
  98. }
  99. // MARK: DZNEmpty
  100. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  101. return NCBrandColor.sharedInstance.backgroundView
  102. }
  103. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  104. return CCGraphics.changeThemingColorImage(UIImage.init(named: "mediaNoRecord"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  105. }
  106. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  107. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  108. if loadingSearch {
  109. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  110. }
  111. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  112. return NSAttributedString.init(string: text, attributes: attributes)
  113. }
  114. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  115. return true
  116. }
  117. // MARK: IBAction
  118. @IBAction func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  119. let itemSizeStart = self.gridLayout.itemSize
  120. UIView.animate(withDuration: 0.0, animations: {
  121. if self.gridLayout.numItems == 1 && self.stepImageWidth > 0 {
  122. self.stepImageWidth = -10
  123. } else if itemSizeStart.width < 50 {
  124. self.stepImageWidth = 10
  125. }
  126. repeat {
  127. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.stepImageWidth
  128. } while (self.gridLayout.itemSize == itemSizeStart)
  129. CCUtility.setMediaWidthImage(Int(self.gridLayout?.preferenceWidth ?? 80))
  130. self.collectionView.collectionViewLayout.invalidateLayout()
  131. })
  132. }
  133. @IBAction func touchUpInsideMenuButtonMore(_ sender: Any) {
  134. var menu: DropdownMenu?
  135. if !isEditMode {
  136. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  137. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folderMedia"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_media_folder_", comment: ""))
  138. var item2: DropdownItem
  139. if filterTypeFileImage {
  140. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageno"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_show_", comment: ""))
  141. } else {
  142. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_hide_", comment: ""))
  143. }
  144. var item3: DropdownItem
  145. if filterTypeFileVideo {
  146. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videono"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_show_", comment: ""))
  147. } else {
  148. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videoyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_hide_", comment: ""))
  149. }
  150. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0,item1,item2,item3], selectedRow: -1)
  151. menu?.token = "menuButtonMore"
  152. } else {
  153. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  154. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_delete_", comment: ""))
  155. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0, item1], selectedRow: -1)
  156. menu?.token = "menuButtonMoreSelect"
  157. }
  158. menu?.delegate = self
  159. menu?.rowHeight = 45
  160. menu?.highlightColor = NCBrandColor.sharedInstance.brand
  161. menu?.tableView.alwaysBounceVertical = false
  162. menu?.tableViewBackgroundColor = UIColor.white
  163. menu?.topOffsetY = menuView.bounds.height
  164. menu?.showMenu()
  165. }
  166. // MARK: DROP-DOWN-MENU
  167. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  168. if dropdownMenu.token == "menuButtonMore" {
  169. switch indexPath.row {
  170. case 0:
  171. isEditMode = true
  172. case 1:
  173. selectStartDirectoryPhotosTab()
  174. case 2:
  175. filterTypeFileImage = !filterTypeFileImage
  176. collectionViewReloadDataSource(loadNetworkDatasource: false)
  177. case 3:
  178. filterTypeFileVideo = !filterTypeFileVideo
  179. collectionViewReloadDataSource(loadNetworkDatasource: false)
  180. default: ()
  181. }
  182. }
  183. if dropdownMenu.token == "menuButtonMoreSelect" {
  184. switch indexPath.row {
  185. case 0:
  186. isEditMode = false
  187. selectFileID.removeAll()
  188. collectionView.reloadData()
  189. case 1:
  190. deleteItems()
  191. default: ()
  192. }
  193. }
  194. }
  195. // MARK: Select Directory
  196. func selectStartDirectoryPhotosTab() {
  197. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  198. let viewController = navigationController.topViewController as! NCSelect
  199. viewController.delegate = self
  200. viewController.hideButtonCreateFolder = true
  201. viewController.includeDirectoryE2EEncryption = false
  202. viewController.includeImages = false
  203. viewController.layoutViewSelect = k_layout_view_move
  204. viewController.selectFile = false
  205. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  206. viewController.type = "mediaFolder"
  207. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  208. self.present(navigationController, animated: true, completion: nil)
  209. }
  210. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  211. let oldStartDirectoryMediaTabView = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  212. if serverUrl != nil && serverUrl != oldStartDirectoryMediaTabView {
  213. // Save Start Directory
  214. NCManageDatabase.sharedInstance.setAccountStartDirectoryMediaTabView(serverUrl!)
  215. //
  216. NCManageDatabase.sharedInstance.clearTable(tableMedia.self, account: appDelegate.activeAccount)
  217. self.sectionDatasource = CCSectionDataSourceMetadata()
  218. //
  219. loadNetworkDatasource()
  220. }
  221. }
  222. // MARK: NC API
  223. func deleteItems() {
  224. var metadatas = [tableMetadata]()
  225. for fileID in selectFileID {
  226. if let metadata = NCManageDatabase.sharedInstance.getTableMedia(predicate: NSPredicate(format: "fileID == %@", fileID)) {
  227. metadatas.append(metadata)
  228. }
  229. }
  230. if metadatas.count > 0 {
  231. NCMainCommon.sharedInstance.deleteFile(metadatas: metadatas as NSArray, e2ee: false, serverUrl: "", folderFileID: "") { (errorCode, message) in
  232. self.isEditMode = false
  233. self.selectFileID.removeAll()
  234. self.selectSearchSections()
  235. }
  236. }
  237. }
  238. func search(lteDate: Date, gteDate: Date, addPast: Bool, setDistantPast: Bool) {
  239. if appDelegate.activeAccount.count == 0 {
  240. return
  241. }
  242. if addPast && isDistantPast {
  243. return
  244. }
  245. if !addPast && loadingSearch {
  246. return
  247. }
  248. if setDistantPast {
  249. isDistantPast = true
  250. }
  251. if addPast {
  252. CCGraphics.addImage(toTitle: NSLocalizedString("_media_", comment: ""), colorTitle: NCBrandColor.sharedInstance.brandText, imageTitle: CCGraphics.changeThemingColorImage(UIImage.init(named: "load"), multiplier: 2, color: NCBrandColor.sharedInstance.brandText), imageRight: false, navigationItem: self.navigationItem)
  253. }
  254. loadingSearch = true
  255. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  256. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  257. self.loadingSearch = false
  258. self.refreshControl.endRefreshing()
  259. self.navigationItem.titleView = nil
  260. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  261. if errorCode == 0 && account == self.appDelegate.activeAccount {
  262. var differenceInsert: Int64 = 0
  263. if metadatas != nil && metadatas!.count > 0 {
  264. differenceInsert = NCManageDatabase.sharedInstance.createTableMedia(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  265. }
  266. print("[LOG] Different Insert \(differenceInsert)]")
  267. if differenceInsert != 0 {
  268. self.readRetry = 0
  269. self.collectionViewReloadDataSource(loadNetworkDatasource: false)
  270. }
  271. if differenceInsert == 0 && addPast {
  272. self.readRetry += 1
  273. switch self.readRetry {
  274. case 1:
  275. if var gteDate = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  276. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate) ?? Date()
  277. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  278. print("[LOG] Media search 90 gg]")
  279. }
  280. case 2:
  281. if var gteDate = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  282. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate) ?? Date()
  283. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  284. print("[LOG] Media search 180 gg]")
  285. }
  286. case 3:
  287. if var gteDate = Calendar.current.date(byAdding: .day, value: -360, to: gteDate) {
  288. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate) ?? Date()
  289. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  290. print("[LOG] Media search 360 gg]")
  291. }
  292. default:
  293. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, setDistantPast: true)
  294. print("[LOG] Media search distant pass]")
  295. }
  296. }
  297. self.collectionView?.reloadData()
  298. } else {
  299. self.collectionViewReloadDataSource(loadNetworkDatasource: false)
  300. }
  301. })
  302. }
  303. @objc private func loadNetworkDatasource() {
  304. isDistantPast = false
  305. readRetry = 0
  306. if appDelegate.activeAccount.count == 0 {
  307. return
  308. }
  309. if self.sectionDatasource.allRecordsDataSource.count == 0 {
  310. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  311. self.search(lteDate: Date(), gteDate: gteDate!, addPast: true, setDistantPast: false)
  312. } else {
  313. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  314. self.search(lteDate: Date(), gteDate: gteDate, addPast: false, setDistantPast: false)
  315. }
  316. self.collectionView?.reloadData()
  317. }
  318. private func selectSearchSections() {
  319. let sections = NSMutableSet()
  320. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  321. var gteDate: Date?
  322. for item in collectionView.indexPathsForVisibleItems {
  323. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  324. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  325. sections.add(date)
  326. }
  327. }
  328. }
  329. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  330. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  331. }
  332. if sortedSections.count >= 1 {
  333. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  334. if lastDate == sortedSections.last as! Date {
  335. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  336. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, setDistantPast: false)
  337. } else {
  338. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  339. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, setDistantPast: false)
  340. }
  341. }
  342. }
  343. // MARK: COLLECTIONVIEW METHODS
  344. public func collectionViewReloadDataSource(loadNetworkDatasource: Bool) {
  345. DispatchQueue.global().async {
  346. let metadatas = NCManageDatabase.sharedInstance.getTableMedias(predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount))
  347. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: "date", filterFileID: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, activeAccount: self.appDelegate.activeAccount)
  348. DispatchQueue.main.async {
  349. if loadNetworkDatasource {
  350. self.loadNetworkDatasource()
  351. }
  352. self.collectionView?.reloadData()
  353. }
  354. }
  355. }
  356. public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  357. selectSearchSections()
  358. }
  359. public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  360. if (!decelerate) {
  361. selectSearchSections()
  362. }
  363. }
  364. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  365. if kind == UICollectionView.elementKindSectionFooter {
  366. let sizeCollection = collectionView.bounds.size.height
  367. let sizeContent = collectionView.contentSize.height
  368. if sizeContent <= sizeCollection {
  369. selectSearchSections()
  370. }
  371. }
  372. if kind == UICollectionView.elementKindSectionHeader {
  373. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  374. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  375. header.labelSection.textColor = .white
  376. header.labelSection.layer.cornerRadius = 11
  377. header.labelSection.layer.masksToBounds = true
  378. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  379. let width = header.labelSection.intrinsicContentSize.width + 30
  380. let leading = collectionView.bounds.width / 2 - width / 2
  381. header.labelWidthConstraint.constant = width
  382. header.labelLeadingConstraint.constant = leading
  383. return header
  384. } else {
  385. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  386. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  387. return footer
  388. }
  389. }
  390. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  391. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  392. }
  393. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  394. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  395. if (section == sections - 1) {
  396. return CGSize(width: collectionView.frame.width, height: footerHeight)
  397. } else {
  398. return CGSize(width: collectionView.frame.width, height: 0)
  399. }
  400. }
  401. func numberOfSections(in collectionView: UICollectionView) -> Int {
  402. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  403. return sections
  404. }
  405. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  406. var numberOfItemsInSection: Int = 0
  407. if section < sectionDatasource.sections.count {
  408. let key = sectionDatasource.sections.object(at: section)
  409. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  410. numberOfItemsInSection = datasource.count
  411. }
  412. return numberOfItemsInSection
  413. }
  414. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  415. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  416. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  417. }
  418. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  419. NCMainCommon.sharedInstance.collectionViewCellForItemAt(indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: nil, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectFileID: selectFileID, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: true, source: self)
  420. return cell
  421. }
  422. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  423. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  424. return
  425. }
  426. metadataPush = metadata
  427. if isEditMode {
  428. if let index = selectFileID.index(of: metadata.fileID) {
  429. selectFileID.remove(at: index)
  430. } else {
  431. selectFileID.append(metadata.fileID)
  432. }
  433. collectionView.reloadItems(at: [indexPath])
  434. return
  435. }
  436. performSegue(withIdentifier: "segueDetail", sender: self)
  437. }
  438. // MARK: SEGUE
  439. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  440. let photoDataSource: NSMutableArray = []
  441. for fileID: String in sectionDatasource.allFileID as! [String] {
  442. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: fileID) as! tableMetadata
  443. if metadata.typeFile == k_metadataTypeFile_image {
  444. photoDataSource.add(metadata)
  445. }
  446. }
  447. if let segueNavigationController = segue.destination as? UINavigationController {
  448. if let segueViewController = segueNavigationController.topViewController as? CCDetail {
  449. segueViewController.metadataDetail = metadataPush
  450. segueViewController.dateFilterQuery = nil
  451. segueViewController.photoDataSource = photoDataSource
  452. segueViewController.title = metadataPush!.fileNameView
  453. }
  454. }
  455. }
  456. }