NCMedia.swift 31 KB

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