NCMedia.swift 29 KB

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