NCMedia.swift 31 KB

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