NCMedia.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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, FastScrollCollectionViewDelegate {
  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 viewDidAppear(_ animated: Bool) {
  94. super.viewDidAppear(animated)
  95. collectionView?.reloadDataThenPerform {
  96. self.downloadThumbnail()
  97. }
  98. }
  99. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  100. super.viewWillTransition(to: size, with: coordinator)
  101. coordinator.animate(alongsideTransition: nil) { _ in
  102. self.collectionView?.reloadDataThenPerform {
  103. self.downloadThumbnail()
  104. }
  105. self.actionSheet?.viewDidLayoutSubviews()
  106. }
  107. }
  108. // MARK: DZNEmpty
  109. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  110. return NCBrandColor.sharedInstance.backgroundView
  111. }
  112. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  113. return CCGraphics.changeThemingColorImage(UIImage.init(named: "mediaNoRecord"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  114. }
  115. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  116. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  117. if loadingSearch {
  118. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  119. }
  120. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  121. return NSAttributedString.init(string: text, attributes: attributes)
  122. }
  123. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  124. return true
  125. }
  126. // MARK: IBAction
  127. @IBAction func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  128. let itemSizeStart = self.gridLayout.itemSize
  129. UIView.animate(withDuration: 0.0, animations: {
  130. if self.gridLayout.numItems == 1 && self.stepImageWidth > 0 {
  131. self.stepImageWidth = -10
  132. } else if itemSizeStart.width < 50 {
  133. self.stepImageWidth = 10
  134. }
  135. repeat {
  136. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.stepImageWidth
  137. } while (self.gridLayout.itemSize == itemSizeStart)
  138. CCUtility.setMediaWidthImage(Int(self.gridLayout?.preferenceWidth ?? 80))
  139. self.collectionView.collectionViewLayout.invalidateLayout()
  140. if self.stepImageWidth < 0 {
  141. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  142. self.selectSearchSections()
  143. }
  144. }
  145. })
  146. }
  147. @IBAction func touchUpInsideMenuButtonMore(_ sender: Any) {
  148. var menu: DropdownMenu?
  149. if !isEditMode {
  150. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  151. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folderMedia"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_media_folder_", comment: ""))
  152. var item2: DropdownItem
  153. if filterTypeFileImage {
  154. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageno"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_show_", comment: ""))
  155. } else {
  156. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_hide_", comment: ""))
  157. }
  158. var item3: DropdownItem
  159. if filterTypeFileVideo {
  160. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videono"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_show_", comment: ""))
  161. } else {
  162. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videoyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_hide_", comment: ""))
  163. }
  164. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0,item1,item2,item3], selectedRow: -1)
  165. menu?.token = "menuButtonMore"
  166. } else {
  167. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  168. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_delete_", comment: ""))
  169. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0, item1], selectedRow: -1)
  170. menu?.token = "menuButtonMoreSelect"
  171. }
  172. menu?.delegate = self
  173. menu?.rowHeight = 45
  174. menu?.highlightColor = NCBrandColor.sharedInstance.brand
  175. menu?.tableView.alwaysBounceVertical = false
  176. menu?.tableViewBackgroundColor = UIColor.white
  177. menu?.topOffsetY = menuView.bounds.height
  178. menu?.showMenu()
  179. }
  180. // MARK: DROP-DOWN-MENU
  181. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  182. if dropdownMenu.token == "menuButtonMore" {
  183. switch indexPath.row {
  184. case 0:
  185. isEditMode = true
  186. case 1:
  187. selectStartDirectoryPhotosTab()
  188. case 2:
  189. filterTypeFileImage = !filterTypeFileImage
  190. collectionViewReloadDataSource(loadNetworkDatasource: false)
  191. case 3:
  192. filterTypeFileVideo = !filterTypeFileVideo
  193. collectionViewReloadDataSource(loadNetworkDatasource: false)
  194. default: ()
  195. }
  196. }
  197. if dropdownMenu.token == "menuButtonMoreSelect" {
  198. switch indexPath.row {
  199. case 0:
  200. isEditMode = false
  201. selectFileID.removeAll()
  202. collectionView?.reloadDataThenPerform {
  203. self.downloadThumbnail()
  204. }
  205. case 1:
  206. deleteItems()
  207. default: ()
  208. }
  209. }
  210. }
  211. // MARK: Select Directory
  212. func selectStartDirectoryPhotosTab() {
  213. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  214. let viewController = navigationController.topViewController as! NCSelect
  215. viewController.delegate = self
  216. viewController.hideButtonCreateFolder = true
  217. viewController.includeDirectoryE2EEncryption = false
  218. viewController.includeImages = false
  219. viewController.layoutViewSelect = k_layout_view_move
  220. viewController.selectFile = false
  221. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  222. viewController.type = "mediaFolder"
  223. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  224. self.present(navigationController, animated: true, completion: nil)
  225. }
  226. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  227. let oldStartDirectoryMediaTabView = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  228. if serverUrl != nil && serverUrl != oldStartDirectoryMediaTabView {
  229. // Save Start Directory
  230. NCManageDatabase.sharedInstance.setAccountStartDirectoryMediaTabView(serverUrl!)
  231. //
  232. NCManageDatabase.sharedInstance.clearTable(tableMedia.self, account: appDelegate.activeAccount)
  233. self.sectionDatasource = CCSectionDataSourceMetadata()
  234. //
  235. loadNetworkDatasource()
  236. }
  237. }
  238. // MARK: NC API
  239. func deleteItems() {
  240. var metadatas = [tableMetadata]()
  241. for fileID in selectFileID {
  242. if let metadata = NCManageDatabase.sharedInstance.getTableMedia(predicate: NSPredicate(format: "fileID == %@", fileID)) {
  243. metadatas.append(metadata)
  244. }
  245. }
  246. if metadatas.count > 0 {
  247. NCMainCommon.sharedInstance.deleteFile(metadatas: metadatas as NSArray, e2ee: false, serverUrl: "", folderFileID: "") { (errorCode, message) in
  248. self.isEditMode = false
  249. self.selectFileID.removeAll()
  250. self.selectSearchSections()
  251. }
  252. }
  253. }
  254. func search(lteDate: Date, gteDate: Date, addPast: Bool, setDistantPast: Bool) {
  255. if appDelegate.activeAccount.count == 0 {
  256. return
  257. }
  258. if addPast && isDistantPast {
  259. return
  260. }
  261. if !addPast && loadingSearch {
  262. return
  263. }
  264. if setDistantPast {
  265. isDistantPast = true
  266. }
  267. if addPast {
  268. //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)
  269. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  270. }
  271. loadingSearch = true
  272. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  273. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  274. self.loadingSearch = false
  275. self.refreshControl.endRefreshing()
  276. NCUtility.sharedInstance.stopActivityIndicator()
  277. //self.navigationItem.titleView = nil
  278. //self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  279. if errorCode == 0 && account == self.appDelegate.activeAccount {
  280. var differenceInsert: Int64 = 0
  281. if metadatas != nil && metadatas!.count > 0 {
  282. differenceInsert = NCManageDatabase.sharedInstance.createTableMedia(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  283. }
  284. print("[LOG] Different Insert \(differenceInsert)]")
  285. if differenceInsert != 0 {
  286. self.readRetry = 0
  287. self.collectionViewReloadDataSource(loadNetworkDatasource: false)
  288. }
  289. if differenceInsert == 0 && addPast {
  290. self.readRetry += 1
  291. switch self.readRetry {
  292. case 1:
  293. if var gteDate = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  294. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate) ?? Date()
  295. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  296. print("[LOG] Media search 90 gg]")
  297. }
  298. case 2:
  299. if var gteDate = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  300. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate) ?? Date()
  301. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  302. print("[LOG] Media search 180 gg]")
  303. }
  304. case 3:
  305. if var gteDate = Calendar.current.date(byAdding: .day, value: -360, to: gteDate) {
  306. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate) ?? Date()
  307. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  308. print("[LOG] Media search 360 gg]")
  309. }
  310. default:
  311. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, setDistantPast: true)
  312. print("[LOG] Media search distant pass]")
  313. }
  314. }
  315. self.collectionView?.reloadDataThenPerform {
  316. self.downloadThumbnail()
  317. }
  318. } else {
  319. self.collectionViewReloadDataSource(loadNetworkDatasource: false)
  320. }
  321. })
  322. }
  323. @objc private func loadNetworkDatasource() {
  324. isDistantPast = false
  325. readRetry = 0
  326. if appDelegate.activeAccount.count == 0 {
  327. return
  328. }
  329. if sectionDatasource.allRecordsDataSource.count == 0 {
  330. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  331. search(lteDate: Date(), gteDate: gteDate!, addPast: true, setDistantPast: false)
  332. } else {
  333. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  334. search(lteDate: Date(), gteDate: gteDate, addPast: false, setDistantPast: false)
  335. }
  336. collectionView?.reloadDataThenPerform {
  337. self.downloadThumbnail()
  338. }
  339. }
  340. private func selectSearchSections() {
  341. let sections = NSMutableSet()
  342. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  343. var gteDate: Date?
  344. for item in collectionView.indexPathsForVisibleItems {
  345. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  346. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  347. sections.add(date)
  348. }
  349. }
  350. }
  351. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  352. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  353. }
  354. if sortedSections.count >= 1 {
  355. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  356. if lastDate == sortedSections.last as! Date {
  357. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  358. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, setDistantPast: false)
  359. } else {
  360. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  361. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, setDistantPast: false)
  362. }
  363. }
  364. }
  365. private func downloadThumbnail() {
  366. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  367. for item in self.collectionView.indexPathsForVisibleItems {
  368. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  369. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: self.collectionView, indexPath: item)
  370. }
  371. }
  372. }
  373. }
  374. // MARK: COLLECTIONVIEW METHODS
  375. public func collectionViewReloadDataSource(loadNetworkDatasource: Bool) {
  376. if appDelegate.activeAccount.count == 0 {
  377. return
  378. }
  379. DispatchQueue.global().async {
  380. let metadatas = NCManageDatabase.sharedInstance.getTableMedias(predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount))
  381. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: "date", filterFileID: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, sorted: "date", ascending: true, activeAccount: self.appDelegate.activeAccount)
  382. DispatchQueue.main.async {
  383. if loadNetworkDatasource {
  384. self.loadNetworkDatasource()
  385. }
  386. self.collectionView?.reloadDataThenPerform {
  387. self.downloadThumbnail()
  388. }
  389. }
  390. }
  391. }
  392. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  393. if kind == UICollectionView.elementKindSectionFooter {
  394. let sizeCollection = collectionView.bounds.size.height
  395. let sizeContent = collectionView.contentSize.height
  396. if sizeContent <= sizeCollection {
  397. selectSearchSections()
  398. }
  399. }
  400. if kind == UICollectionView.elementKindSectionHeader {
  401. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  402. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  403. header.labelSection.textColor = .white
  404. header.labelHeightConstraint.constant = 20
  405. header.labelSection.layer.cornerRadius = 10
  406. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  407. let width = header.labelSection.intrinsicContentSize.width + 30
  408. let leading = collectionView.bounds.width / 2 - width / 2
  409. header.labelWidthConstraint.constant = width
  410. header.labelLeadingConstraint.constant = leading
  411. return header
  412. } else {
  413. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  414. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  415. return footer
  416. }
  417. }
  418. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  419. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  420. }
  421. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  422. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  423. if (section == sections - 1) {
  424. return CGSize(width: collectionView.frame.width, height: footerHeight)
  425. } else {
  426. return CGSize(width: collectionView.frame.width, height: 0)
  427. }
  428. }
  429. func numberOfSections(in collectionView: UICollectionView) -> Int {
  430. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  431. return sections
  432. }
  433. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  434. var numberOfItemsInSection: Int = 0
  435. if section < sectionDatasource.sections.count {
  436. let key = sectionDatasource.sections.object(at: section)
  437. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  438. numberOfItemsInSection = datasource.count
  439. }
  440. return numberOfItemsInSection
  441. }
  442. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  443. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  444. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  445. }
  446. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  447. 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, downloadThumbnail: false, source: self)
  448. return cell
  449. }
  450. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  451. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  452. return
  453. }
  454. metadataPush = metadata
  455. if isEditMode {
  456. if let index = selectFileID.index(of: metadata.fileID) {
  457. selectFileID.remove(at: index)
  458. } else {
  459. selectFileID.append(metadata.fileID)
  460. }
  461. collectionView.reloadItems(at: [indexPath])
  462. return
  463. }
  464. performSegue(withIdentifier: "segueDetail", sender: self)
  465. }
  466. // MARK: SEGUE
  467. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  468. let photoDataSource: NSMutableArray = []
  469. for fileID: String in sectionDatasource.allFileID as! [String] {
  470. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: fileID) as! tableMetadata
  471. if metadata.typeFile == k_metadataTypeFile_image {
  472. photoDataSource.add(metadata)
  473. }
  474. }
  475. if let segueNavigationController = segue.destination as? UINavigationController {
  476. if let segueViewController = segueNavigationController.topViewController as? CCDetail {
  477. segueViewController.metadataDetail = metadataPush
  478. segueViewController.dateFilterQuery = nil
  479. segueViewController.photoDataSource = photoDataSource
  480. segueViewController.title = metadataPush!.fileNameView
  481. }
  482. }
  483. }
  484. }
  485. extension FastScrollCollectionView
  486. {
  487. /// Calls reloadsData() on self, and ensures that the given closure is
  488. /// called after reloadData() has been completed.
  489. ///
  490. /// Discussion: reloadData() appears to be asynchronous. i.e. the
  491. /// reloading actually happens during the next layout pass. So, doing
  492. /// things like scrolling the collectionView immediately after a
  493. /// call to reloadData() can cause trouble.
  494. ///
  495. /// This method uses CATransaction to schedule the closure.
  496. func reloadDataThenPerform(_ closure: @escaping (() -> Void))
  497. {
  498. CATransaction.begin()
  499. CATransaction.setCompletionBlock(closure)
  500. self.reloadData()
  501. CATransaction.commit()
  502. }
  503. }
  504. // MARK: - UIScrollViewDelegate
  505. extension NCMedia: UIScrollViewDelegate {
  506. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  507. collectionView.scrollViewDidScroll(scrollView)
  508. }
  509. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  510. collectionView.scrollViewWillBeginDragging(scrollView)
  511. }
  512. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  513. collectionView.scrollViewDidEndDecelerating(scrollView)
  514. }
  515. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  516. collectionView.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
  517. }
  518. }
  519. // MARK: FastScroll
  520. extension NCMedia {
  521. fileprivate func configFastScroll() {
  522. collectionView.fastScrollDelegate = self
  523. //bubble
  524. collectionView.deactivateBubble = true
  525. collectionView.bubbleFocus = .dynamic
  526. collectionView.bubbleTextSize = 14.0
  527. collectionView.bubbleMarginRight = 50.0
  528. collectionView.bubbleColor = UIColor(red: 38.0 / 255.0, green: 48.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
  529. //handle
  530. /*
  531. collectionView.handleHeight = 40.0
  532. collectionView.handleWidth = 40.0
  533. collectionView.handleRadius = 20.0
  534. collectionView.handleMarginRight = -20
  535. */
  536. collectionView.handleColor = NCBrandColor.sharedInstance.brand //UIColor(red: 38.0 / 255.0, green: 48.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
  537. //scrollbar
  538. collectionView.scrollbarWidth = 0.0
  539. collectionView.scrollbarMarginTop = 45.0
  540. collectionView.scrollbarMarginBottom = 5.0
  541. collectionView.scrollbarMarginRight = 10.0
  542. //callback action to display bubble name
  543. /*
  544. collectionView.bubbleNameForIndexPath = { indexPath in
  545. let visibleSection: Section = self.data[indexPath.section]
  546. return visibleSection.sectionTitle
  547. }
  548. */
  549. }
  550. func hideHandle() {
  551. selectSearchSections()
  552. }
  553. }