NCMedia.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. //
  2. // NCMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/02/2019.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import Sheeeeeeeeet
  25. class NCMedia: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, NCListCellDelegate, NCSectionHeaderMenuDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  26. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  27. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. private var metadataPush: tableMetadata?
  29. private var isEditMode = false
  30. private var selectFileID = [String]()
  31. private var filterTypeFileImage = false;
  32. private var filterTypeFileVideo = false;
  33. private var sectionDatasource = CCSectionDataSourceMetadata()
  34. private var autoUploadFileName = ""
  35. private var autoUploadDirectory = ""
  36. private var gridLayout: NCGridLayout!
  37. private var actionSheet: ActionSheet?
  38. private let headerMenuHeight: CGFloat = 50
  39. private let sectionHeaderHeight: CGFloat = 20
  40. private let footerHeight: CGFloat = 50
  41. private var addWidth: CGFloat = 10
  42. private var readRetry = 0
  43. private var isDistantPast = false
  44. private let refreshControl = UIRefreshControl()
  45. private var loadingSearch = false
  46. required init?(coder aDecoder: NSCoder) {
  47. super.init(coder: aDecoder)
  48. appDelegate.activeMedia = self
  49. }
  50. override func viewDidLoad() {
  51. super.viewDidLoad()
  52. // Cell
  53. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  54. // Header
  55. collectionView.register(UINib.init(nibName: "NCSectionMediaHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  56. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  57. // Footer
  58. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  59. collectionView.alwaysBounceVertical = true
  60. gridLayout = NCGridLayout()
  61. gridLayout.heightLabelPlusButton = 0
  62. gridLayout.preferenceWidth = 80
  63. gridLayout.sectionInset = UIEdgeInsets(top: 10, left: 1, bottom: 10, right: 1)
  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. }
  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. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  82. // get auto upload folder
  83. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  84. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  85. // clear variable
  86. isDistantPast = false
  87. readRetry = 0
  88. collectionViewReloadDataSource()
  89. loadNetworkDatasource()
  90. }
  91. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  92. super.viewWillTransition(to: size, with: coordinator)
  93. coordinator.animate(alongsideTransition: nil) { _ in
  94. self.collectionView.collectionViewLayout.invalidateLayout()
  95. self.actionSheet?.viewDidLayoutSubviews()
  96. }
  97. }
  98. // MARK: DZNEmpty
  99. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  100. return NCBrandColor.sharedInstance.backgroundView
  101. }
  102. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  103. return CCGraphics.changeThemingColorImage(UIImage.init(named: "mediaNoRecord"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  104. }
  105. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  106. let text = "\n"+NSLocalizedString("_tutorial_photo_view_", comment: "")
  107. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  108. return NSAttributedString.init(string: text, attributes: attributes)
  109. }
  110. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  111. return true
  112. }
  113. // MARK: TAP EVENT
  114. func tapSwitchHeader(sender: Any) {
  115. let itemSizeStart = self.gridLayout.itemSize
  116. UIView.animate(withDuration: 0.0, animations: {
  117. if self.gridLayout.numItems == 1 && self.addWidth > 0 {
  118. self.addWidth = -10
  119. } else if itemSizeStart.width < 50 {
  120. self.addWidth = 10
  121. }
  122. repeat {
  123. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.addWidth
  124. } while (self.gridLayout.itemSize == itemSizeStart)
  125. self.collectionView.collectionViewLayout.invalidateLayout()
  126. })
  127. }
  128. func tapOrderHeader(sender: Any) {
  129. }
  130. func tapMoreHeader(sender: Any) {
  131. var menuView: DropdownMenu?
  132. if isEditMode {
  133. //let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  134. //let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_restore_selected_", comment: ""))
  135. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_delete_selected_", comment: ""))
  136. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item2], selectedRow: -1)
  137. menuView?.token = "tapMoreHeaderMenuSelect"
  138. } else {
  139. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  140. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folderMedia"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_media_folder_", comment: ""))
  141. var item2: DropdownItem
  142. if filterTypeFileImage {
  143. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageno"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_show_", comment: ""))
  144. } else {
  145. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_hide_", comment: ""))
  146. }
  147. var item3: DropdownItem
  148. if filterTypeFileVideo {
  149. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videono"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_show_", comment: ""))
  150. } else {
  151. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videoyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_hide_", comment: ""))
  152. }
  153. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item0,item1,item2,item3], selectedRow: -1)
  154. menuView?.token = "tapMoreHeaderMenu"
  155. }
  156. menuView?.delegate = self
  157. menuView?.rowHeight = 45
  158. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  159. menuView?.tableView.alwaysBounceVertical = false
  160. menuView?.tableViewBackgroundColor = UIColor.white
  161. let header = (sender as? UIButton)?.superview
  162. let headerRect = self.collectionView.convert(header!.bounds, from: self.view)
  163. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  164. menuView?.topOffsetY = CGFloat(menuOffsetY)
  165. menuView?.showMenu()
  166. }
  167. func tapMoreListItem(with fileID: String, sender: Any) {
  168. tapMoreGridItem(with: fileID, sender: sender)
  169. }
  170. func tapMoreGridItem(with fileID: String, sender: Any) {
  171. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  172. return
  173. }
  174. if !isEditMode {
  175. var items = [ActionSheetItem]()
  176. let appearanceDelete = ActionSheetItemAppearance.init()
  177. appearanceDelete.textColor = UIColor.red
  178. // 0 == CCMore, 1 = first NCOffline ....
  179. if (self == self.navigationController?.viewControllers[1]) {
  180. items.append(ActionSheetItem(title: NSLocalizedString("_remove_available_offline_", comment: ""), value: 0, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "offline"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)))
  181. }
  182. items.append(ActionSheetItem(title: NSLocalizedString("_share_", comment: ""), value: 1, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)))
  183. let itemDelete = ActionSheetItem(title: NSLocalizedString("_delete_", comment: ""), value: 2, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: UIColor.red))
  184. itemDelete.customAppearance = appearanceDelete
  185. items.append(itemDelete)
  186. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  187. actionSheet = ActionSheet(items: items) { sheet, item in
  188. if item.value as? Int == 0 {
  189. if metadata.directory {
  190. NCManageDatabase.sharedInstance.setDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!, offline: false, account: self.appDelegate.activeAccount)
  191. } else {
  192. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: false)
  193. }
  194. self.collectionViewReloadDataSource()
  195. }
  196. if item.value as? Int == 1 { self.appDelegate.activeMain.readShare(withAccount: self.appDelegate.activeAccount, openWindow: true, metadata: metadata) }
  197. if item.value as? Int == 2 { self.deleteItem(with: metadata, sender: sender) }
  198. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  199. }
  200. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: metadata.directory, iconName: metadata.iconName, fileID: metadata.fileID, fileNameView: metadata.fileNameView, text: metadata.fileNameView)
  201. actionSheet?.headerView = headerView
  202. actionSheet?.headerView?.frame.size.height = 50
  203. actionSheet?.present(in: self, from: sender as! UIButton)
  204. } else {
  205. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  206. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  207. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  208. }
  209. }
  210. // MARK: DROP-DOWN-MENU
  211. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  212. if dropdownMenu.token == "tapMoreHeaderMenu" {
  213. }
  214. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  215. }
  216. }
  217. // MARK: NC API
  218. func deleteItem(with metadata: tableMetadata, sender: Any) {
  219. var items = [ActionSheetItem]()
  220. guard let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == serverUrl", appDelegate.activeAccount, metadata.serverUrl)) else {
  221. return
  222. }
  223. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  224. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  225. actionSheet = ActionSheet(items: items) { sheet, item in
  226. if item is ActionSheetDangerButton {
  227. NCMainCommon.sharedInstance.deleteFile(metadatas: [metadata], e2ee: tableDirectory.e2eEncrypted, serverUrl: tableDirectory.serverUrl, folderFileID: tableDirectory.fileID) { (errorCode, message) in
  228. self.collectionViewReloadDataSource()
  229. }
  230. }
  231. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  232. }
  233. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: metadata.directory, iconName: metadata.iconName, fileID: metadata.fileID, fileNameView: metadata.fileNameView, text: metadata.fileNameView)
  234. actionSheet?.headerView = headerView
  235. actionSheet?.headerView?.frame.size.height = 50
  236. actionSheet?.present(in: self, from: sender as! UIButton)
  237. }
  238. func search(lteDate: Date, gteDate: Date, addPast: Bool, setDistantPast: Bool) {
  239. if appDelegate.activeAccount.count == 0 {
  240. return
  241. }
  242. if addPast && isDistantPast {
  243. return
  244. }
  245. if !addPast && loadingSearch {
  246. return
  247. }
  248. if setDistantPast {
  249. isDistantPast = true
  250. }
  251. if addPast {
  252. 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)
  253. }
  254. loadingSearch = true
  255. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  256. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  257. self.loadingSearch = false
  258. self.refreshControl.endRefreshing()
  259. self.navigationItem.titleView = nil
  260. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  261. if errorCode == 0 && account == self.appDelegate.activeAccount {
  262. var differenceInsert: Int64 = 0
  263. if metadatas != nil && metadatas!.count > 0 {
  264. differenceInsert = NCManageDatabase.sharedInstance.createTablePhotos(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  265. }
  266. if differenceInsert != 0 {
  267. self.readRetry = 0
  268. self.collectionViewReloadDataSource()
  269. }
  270. if differenceInsert == 0 && addPast {
  271. self.readRetry += 1
  272. switch self.readRetry {
  273. case 1:
  274. var gteDate = Calendar.current.date(byAdding: .day, value: -90, to: gteDate)!
  275. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate)!
  276. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  277. case 2:
  278. var gteDate = Calendar.current.date(byAdding: .day, value: -180, to: gteDate)!
  279. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate)!
  280. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  281. case 3:
  282. var gteDate = Calendar.current.date(byAdding: .day, value: -360, to: gteDate)!
  283. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate)!
  284. self.search(lteDate: lteDate, gteDate: gteDate, addPast: addPast, setDistantPast: false)
  285. default:
  286. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, setDistantPast: true)
  287. }
  288. }
  289. }
  290. })
  291. }
  292. @objc func loadNetworkDatasource() {
  293. if appDelegate.activeAccount.count == 0 {
  294. return
  295. }
  296. if self.sectionDatasource.allRecordsDataSource.count == 0 {
  297. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  298. self.search(lteDate: Date(), gteDate: gteDate!, addPast: true, setDistantPast: false)
  299. } else {
  300. let gteDate = NCManageDatabase.sharedInstance.getTablePhotoDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  301. self.search(lteDate: Date(), gteDate: gteDate, addPast: false, setDistantPast: false)
  302. }
  303. self.collectionView?.reloadData()
  304. }
  305. // MARK: COLLECTIONVIEW METHODS
  306. func collectionViewReloadDataSource() {
  307. DispatchQueue.global().async {
  308. let metadatas = NCManageDatabase.sharedInstance.getTablePhotos(predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount))
  309. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: "date", filterFileID: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, activeAccount: self.appDelegate.activeAccount)
  310. DispatchQueue.main.async {
  311. self.collectionView?.reloadData()
  312. }
  313. }
  314. }
  315. public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  316. //caused by user
  317. selectSearchSections()
  318. }
  319. public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  320. if (!decelerate) {
  321. //cause by user
  322. selectSearchSections()
  323. }
  324. }
  325. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  326. if kind == UICollectionView.elementKindSectionFooter {
  327. let sizeCollection = collectionView.bounds.size.height
  328. let sizeContent = collectionView.contentSize.height
  329. if sizeContent <= sizeCollection {
  330. selectSearchSections()
  331. }
  332. }
  333. if (indexPath.section == 0) {
  334. if kind == UICollectionView.elementKindSectionHeader {
  335. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  336. header.viewLabelSection.backgroundColor = .clear
  337. header.delegate = self
  338. header.setStatusButton(count: sectionDatasource.allFileID.count)
  339. header.buttonOrder.isHidden = true
  340. header.labelSection.isHidden = false
  341. header.buttonMore.isHidden = false
  342. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  343. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  344. header.labelSection.textColor = .white
  345. header.labelSection.layer.cornerRadius = 11
  346. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  347. let widthFrame = header.labelSection.intrinsicContentSize.width + 30
  348. let xFrame = collectionView.bounds.width / 2 - widthFrame / 2
  349. header.labelSection.frame = CGRect(x: xFrame, y: 10, width: widthFrame, height: 22)
  350. return header
  351. } else {
  352. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  353. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  354. return footer
  355. }
  356. } else {
  357. if kind == UICollectionView.elementKindSectionHeader {
  358. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  359. header.backgroundColor = .clear
  360. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  361. return header
  362. } else {
  363. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  364. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  365. return footer
  366. }
  367. }
  368. }
  369. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  370. if section == 0 {
  371. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  372. } else {
  373. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  374. }
  375. }
  376. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  377. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  378. if (section == sections - 1) {
  379. return CGSize(width: collectionView.frame.width, height: footerHeight)
  380. } else {
  381. return CGSize(width: collectionView.frame.width, height: 0)
  382. }
  383. }
  384. func numberOfSections(in collectionView: UICollectionView) -> Int {
  385. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  386. return sections
  387. }
  388. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  389. var numberOfItemsInSection: Int = 0
  390. if section < sectionDatasource.sections.count {
  391. let key = sectionDatasource.sections.object(at: section)
  392. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  393. numberOfItemsInSection = datasource.count
  394. }
  395. return numberOfItemsInSection
  396. }
  397. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  398. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  399. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  400. }
  401. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  402. NCMainCommon.sharedInstance.collectionViewCellForItemAt(indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: nil, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectFileID: selectFileID, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: true, source: self)
  403. return cell
  404. }
  405. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  406. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  407. return
  408. }
  409. metadataPush = metadata
  410. if isEditMode {
  411. if let index = selectFileID.index(of: metadata.fileID) {
  412. selectFileID.remove(at: index)
  413. } else {
  414. selectFileID.append(metadata.fileID)
  415. }
  416. collectionView.reloadItems(at: [indexPath])
  417. return
  418. }
  419. performSegue(withIdentifier: "segueDetail", sender: self)
  420. }
  421. // MARK: Utility
  422. func selectSearchSections() {
  423. let sections = NSMutableSet()
  424. let lastDate = NCManageDatabase.sharedInstance.getTablePhotoDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  425. var gteDate: Date?
  426. for item in collectionView.indexPathsForVisibleItems {
  427. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  428. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  429. sections.add(date)
  430. }
  431. }
  432. }
  433. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  434. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  435. }
  436. if sortedSections.count >= 1 {
  437. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  438. if lastDate == sortedSections.last as! Date {
  439. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  440. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, setDistantPast: false)
  441. } else {
  442. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  443. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, setDistantPast: false)
  444. }
  445. }
  446. }
  447. // MARK: SEGUE
  448. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  449. let photoDataSource: NSMutableArray = []
  450. for fileID: String in sectionDatasource.allFileID as! [String] {
  451. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: fileID) as! tableMetadata
  452. if metadata.typeFile == k_metadataTypeFile_image {
  453. photoDataSource.add(metadata)
  454. }
  455. }
  456. if let segueNavigationController = segue.destination as? UINavigationController {
  457. if let segueViewController = segueNavigationController.topViewController as? CCDetail {
  458. segueViewController.metadataDetail = metadataPush
  459. segueViewController.dateFilterQuery = nil
  460. segueViewController.photoDataSource = photoDataSource
  461. segueViewController.title = metadataPush!.fileNameView
  462. }
  463. }
  464. }
  465. }