NCMedia.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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, UICollectionViewDataSourcePrefetching, 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 = 1
  43. private let stepDays = -30
  44. private var isDistantPast = false
  45. private let refreshControl = UIRefreshControl()
  46. private var loadingSearch = false
  47. required init?(coder aDecoder: NSCoder) {
  48. super.init(coder: aDecoder)
  49. appDelegate.activeMedia = self
  50. }
  51. override func viewDidLoad() {
  52. super.viewDidLoad()
  53. // Cell
  54. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  55. // Header
  56. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  57. collectionView.register(UINib.init(nibName: "NCSectionHeader", 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 = NCGridLayout()
  62. gridLayout.heightLabelPlusButton = 0
  63. gridLayout.preferenceWidth = 80
  64. gridLayout.sectionInset = UIEdgeInsets(top: 10, left: 1, bottom: 10, right: 1)
  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(loadDatasource), for: .valueChanged)
  72. // empty Data Source
  73. self.collectionView.emptyDataSetDelegate = self;
  74. self.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 = 1
  88. loadDatasource()
  89. }
  90. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  91. super.viewWillTransition(to: size, with: coordinator)
  92. coordinator.animate(alongsideTransition: nil) { _ in
  93. self.collectionView.collectionViewLayout.invalidateLayout()
  94. self.actionSheet?.viewDidLayoutSubviews()
  95. }
  96. }
  97. // MARK: DZNEmpty
  98. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  99. return NCBrandColor.sharedInstance.backgroundView
  100. }
  101. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  102. return CCGraphics.changeThemingColorImage(UIImage.init(named: "filesNoFiles"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  103. }
  104. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  105. let text = "\n"+NSLocalizedString("_files_no_files_", comment: "")
  106. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  107. return NSAttributedString.init(string: text, attributes: attributes)
  108. }
  109. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  110. return true
  111. }
  112. // MARK: TAP EVENT
  113. func tapSwitchHeader(sender: Any) {
  114. let itemSizeStart = self.gridLayout.itemSize
  115. UIView.animate(withDuration: 0.0, animations: {
  116. if self.gridLayout.numItems == 1 && self.addWidth > 0 {
  117. self.addWidth = -10
  118. } else if itemSizeStart.width < 50 {
  119. self.addWidth = 10
  120. }
  121. repeat {
  122. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.addWidth
  123. } while (self.gridLayout.itemSize == itemSizeStart)
  124. self.collectionView.collectionViewLayout.invalidateLayout()
  125. })
  126. }
  127. func tapOrderHeader(sender: Any) {
  128. }
  129. func tapMoreHeader(sender: Any) {
  130. var menuView: DropdownMenu?
  131. if isEditMode {
  132. //let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  133. //let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "restore"), multiplier: 1, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_restore_selected_", comment: ""))
  134. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_trash_delete_selected_", comment: ""))
  135. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item2], selectedRow: -1)
  136. menuView?.token = "tapMoreHeaderMenuSelect"
  137. } else {
  138. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  139. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folderMedia"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_media_folder_", comment: ""))
  140. var item2: DropdownItem
  141. if filterTypeFileImage {
  142. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageno"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_show_", comment: ""))
  143. } else {
  144. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_hide_", comment: ""))
  145. }
  146. var item3: DropdownItem
  147. if filterTypeFileVideo {
  148. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videono"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_show_", comment: ""))
  149. } else {
  150. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videoyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_hide_", comment: ""))
  151. }
  152. menuView = DropdownMenu(navigationController: self.navigationController!, items: [item0,item1,item2,item3], selectedRow: -1)
  153. menuView?.token = "tapMoreHeaderMenu"
  154. }
  155. menuView?.delegate = self
  156. menuView?.rowHeight = 45
  157. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  158. menuView?.tableView.alwaysBounceVertical = false
  159. menuView?.tableViewBackgroundColor = UIColor.white
  160. let header = (sender as? UIButton)?.superview
  161. let headerRect = self.collectionView.convert(header!.bounds, from: self.view)
  162. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  163. menuView?.topOffsetY = CGFloat(menuOffsetY)
  164. menuView?.showMenu()
  165. }
  166. func tapMoreListItem(with fileID: String, sender: Any) {
  167. tapMoreGridItem(with: fileID, sender: sender)
  168. }
  169. func tapMoreGridItem(with fileID: String, sender: Any) {
  170. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  171. return
  172. }
  173. if !isEditMode {
  174. var items = [ActionSheetItem]()
  175. let appearanceDelete = ActionSheetItemAppearance.init()
  176. appearanceDelete.textColor = UIColor.red
  177. // 0 == CCMore, 1 = first NCOffline ....
  178. if (self == self.navigationController?.viewControllers[1]) {
  179. items.append(ActionSheetItem(title: NSLocalizedString("_remove_available_offline_", comment: ""), value: 0, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "offline"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)))
  180. }
  181. items.append(ActionSheetItem(title: NSLocalizedString("_share_", comment: ""), value: 1, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)))
  182. let itemDelete = ActionSheetItem(title: NSLocalizedString("_delete_", comment: ""), value: 2, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: UIColor.red))
  183. itemDelete.customAppearance = appearanceDelete
  184. items.append(itemDelete)
  185. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  186. actionSheet = ActionSheet(items: items) { sheet, item in
  187. if item.value as? Int == 0 {
  188. if metadata.directory {
  189. NCManageDatabase.sharedInstance.setDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!, offline: false, account: self.appDelegate.activeAccount)
  190. } else {
  191. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: false)
  192. }
  193. self.loadDatasource()
  194. }
  195. if item.value as? Int == 1 { self.appDelegate.activeMain.readShare(withAccount: self.appDelegate.activeAccount, openWindow: true, metadata: metadata) }
  196. if item.value as? Int == 2 { self.deleteItem(with: metadata, sender: sender) }
  197. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  198. }
  199. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: metadata.directory, iconName: metadata.iconName, fileID: metadata.fileID, fileNameView: metadata.fileNameView, text: metadata.fileNameView)
  200. actionSheet?.headerView = headerView
  201. actionSheet?.headerView?.frame.size.height = 50
  202. actionSheet?.present(in: self, from: sender as! UIButton)
  203. } else {
  204. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  205. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  206. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  207. }
  208. }
  209. // MARK: DROP-DOWN-MENU
  210. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  211. if dropdownMenu.token == "tapMoreHeaderMenu" {
  212. }
  213. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  214. }
  215. }
  216. // MARK: NC API
  217. func deleteItem(with metadata: tableMetadata, sender: Any) {
  218. var items = [ActionSheetItem]()
  219. guard let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == serverUrl", appDelegate.activeAccount, metadata.serverUrl)) else {
  220. return
  221. }
  222. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  223. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  224. actionSheet = ActionSheet(items: items) { sheet, item in
  225. if item is ActionSheetDangerButton {
  226. NCMainCommon.sharedInstance.deleteFile(metadatas: [metadata], e2ee: tableDirectory.e2eEncrypted, serverUrl: tableDirectory.serverUrl, folderFileID: tableDirectory.fileID) { (errorCode, message) in
  227. self.loadDatasource()
  228. }
  229. }
  230. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  231. }
  232. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: metadata.directory, iconName: metadata.iconName, fileID: metadata.fileID, fileNameView: metadata.fileNameView, text: metadata.fileNameView)
  233. actionSheet?.headerView = headerView
  234. actionSheet?.headerView?.frame.size.height = 50
  235. actionSheet?.present(in: self, from: sender as! UIButton)
  236. }
  237. func search(lteDate: Date, gteDate: Date, newDays: Bool, setDistantPast: Bool) {
  238. if appDelegate.activeAccount.count == 0 {
  239. return
  240. }
  241. if newDays {
  242. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  243. }
  244. if !newDays && (loadingSearch || isDistantPast) {
  245. return
  246. } else {
  247. loadingSearch = true
  248. }
  249. if setDistantPast {
  250. isDistantPast = true
  251. }
  252. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  253. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  254. self.loadingSearch = false
  255. self.refreshControl.endRefreshing()
  256. NCUtility.sharedInstance.stopActivityIndicator()
  257. if errorCode == 0 && account == self.appDelegate.activeAccount {
  258. var insertRecord = 0
  259. if metadatas != nil && metadatas!.count > 0 {
  260. insertRecord = NCManageDatabase.sharedInstance.createTablePhotos(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  261. self.loadDatasource()
  262. }
  263. if insertRecord > 0 {
  264. self.readRetry = 1
  265. }
  266. if insertRecord == 0 && newDays {
  267. self.readRetry += 1
  268. let value = self.stepDays * self.readRetry
  269. var newGteDate = Calendar.current.date(byAdding: .day, value: value, to: gteDate)!
  270. newGteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: newGteDate) ?? newGteDate
  271. if self.readRetry == 3 {
  272. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, newDays: newDays, setDistantPast: true)
  273. } else {
  274. self.search(lteDate: lteDate, gteDate: newGteDate, newDays: newDays, setDistantPast: false)
  275. }
  276. }
  277. }
  278. })
  279. }
  280. // MARK: DATASOURCE
  281. @objc func loadDatasource() {
  282. if appDelegate.activeAccount.count == 0 {
  283. return
  284. }
  285. DispatchQueue.global().async {
  286. if let metadatas = NCManageDatabase.sharedInstance.getTablePhotos(predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount)) {
  287. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: "date", filterFileID: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, activeAccount: self.appDelegate.activeAccount)
  288. } else {
  289. self.sectionDatasource = CCSectionDataSourceMetadata()
  290. var gteDate = Calendar.current.date(byAdding: .day, value: self.stepDays, to: Date())!
  291. gteDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate) ?? gteDate
  292. self.search(lteDate: Date(), gteDate: gteDate, newDays: true, setDistantPast: false)
  293. }
  294. DispatchQueue.main.async {
  295. self.collectionView?.reloadData()
  296. }
  297. }
  298. }
  299. // MARK: COLLECTIONVIEW METHODS
  300. public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  301. //caused by user
  302. selectSearchSections()
  303. }
  304. public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  305. if (!decelerate) {
  306. //cause by user
  307. selectSearchSections()
  308. }
  309. }
  310. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  311. if (indexPath.section == 0) {
  312. if kind == UICollectionView.elementKindSectionHeader {
  313. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  314. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGridChange"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  315. header.viewLabelSection.backgroundColor = .clear
  316. header.delegate = self
  317. header.setStatusButton(count: sectionDatasource.allFileID.count)
  318. header.buttonOrder.isHidden = true
  319. header.labelSection.isHidden = false
  320. header.buttonMore.isHidden = false
  321. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  322. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  323. return header
  324. } else {
  325. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  326. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  327. return footer
  328. }
  329. } else {
  330. if kind == UICollectionView.elementKindSectionHeader {
  331. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  332. header.backgroundColor = .clear
  333. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  334. return header
  335. } else {
  336. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  337. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  338. return footer
  339. }
  340. }
  341. }
  342. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  343. if section == 0 {
  344. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  345. } else {
  346. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  347. }
  348. }
  349. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  350. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  351. if (section == sections - 1) {
  352. return CGSize(width: collectionView.frame.width, height: footerHeight)
  353. } else {
  354. return CGSize(width: collectionView.frame.width, height: 0)
  355. }
  356. }
  357. func numberOfSections(in collectionView: UICollectionView) -> Int {
  358. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  359. return sections
  360. }
  361. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  362. let key = sectionDatasource.sections.object(at: section)
  363. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  364. return datasource.count
  365. }
  366. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  367. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  368. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  369. }
  370. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  371. 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)
  372. return cell
  373. }
  374. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  375. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  376. return
  377. }
  378. metadataPush = metadata
  379. if isEditMode {
  380. if let index = selectFileID.index(of: metadata.fileID) {
  381. selectFileID.remove(at: index)
  382. } else {
  383. selectFileID.append(metadata.fileID)
  384. }
  385. collectionView.reloadItems(at: [indexPath])
  386. return
  387. }
  388. performSegue(withIdentifier: "segueDetail", sender: self)
  389. }
  390. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  391. /*
  392. var section = indexPaths.last?.section ?? 0
  393. var gteDate = NSDate.distantPast
  394. let dateSection = sectionDatasource.sections.object(at: section) as! Date
  395. if let result = NCManageDatabase.sharedInstance.getTablePhotoLastDate(account: appDelegate.activeAccount) {
  396. if result.date as Date >= dateSection && fetchingDistantPast == false {
  397. if fetchingInsert == 0 {
  398. fetchingDistantPast = true
  399. } else {
  400. gteDate = Calendar.current.date(byAdding: .day, value: self.stepDays, to: result.date as Date)!
  401. }
  402. search(lteDate: result.date as Date, gteDate: gteDate, reiteration: true, activityIndicator: true, prefetching: true)
  403. }
  404. }
  405. */
  406. }
  407. // MARK: Utility
  408. func selectSearchSections() {
  409. let sections = NSMutableSet()
  410. let lastDate = NCManageDatabase.sharedInstance.getTablePhotoLastDate(account: self.appDelegate.activeAccount)
  411. var gteDate: Date?
  412. for item in collectionView.indexPathsForVisibleItems {
  413. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  414. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  415. sections.add(date)
  416. }
  417. }
  418. }
  419. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  420. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  421. }
  422. if sortedSections.count >= 1 {
  423. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  424. if lastDate == sortedSections.last as! Date {
  425. gteDate = Calendar.current.date(byAdding: .day, value: stepDays, to: sortedSections.last as! Date)!
  426. search(lteDate: lteDate, gteDate: gteDate!, newDays: true, setDistantPast: false)
  427. } else {
  428. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  429. search(lteDate: lteDate, gteDate: gteDate!, newDays: false, setDistantPast: false)
  430. }
  431. }
  432. }
  433. // MARK: SEGUE
  434. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  435. let photoDataSource: NSMutableArray = []
  436. for fileID: String in sectionDatasource.allFileID as! [String] {
  437. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: fileID) as! tableMetadata
  438. if metadata.typeFile == k_metadataTypeFile_image {
  439. photoDataSource.add(metadata)
  440. }
  441. }
  442. if let segueNavigationController = segue.destination as? UINavigationController {
  443. if let segueViewController = segueNavigationController.topViewController as? CCDetail {
  444. segueViewController.metadataDetail = metadataPush
  445. segueViewController.dateFilterQuery = nil
  446. segueViewController.photoDataSource = photoDataSource
  447. segueViewController.title = metadataPush!.fileNameView
  448. }
  449. }
  450. }
  451. }