NCMedia.swift 27 KB

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