NCMedia.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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 NCCommunication
  25. class NCMedia: UIViewController, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  26. @IBOutlet weak var collectionView : UICollectionView!
  27. //Grid control buttons
  28. private var plusButton: UIBarButtonItem!
  29. private var separatorButton: UIBarButtonItem!
  30. private var minusButton: UIBarButtonItem!
  31. private var gridButton: UIBarButtonItem!
  32. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. var sectionDatasource = CCSectionDataSourceMetadata()
  34. private var metadataPush: tableMetadata?
  35. private var isEditMode = false
  36. private var selectocId: [String] = []
  37. private var filterTypeFileImage = false;
  38. private var filterTypeFileVideo = false;
  39. private var autoUploadFileName = ""
  40. private var autoUploadDirectory = ""
  41. private var gridLayout: NCGridMediaLayout!
  42. private let sectionHeaderHeight: CGFloat = 10
  43. private let footerHeight: CGFloat = 50
  44. private var stepImageWidth: CGFloat = 10
  45. private let kMaxImageGrid: CGFloat = 5
  46. private var isDistantPast = false
  47. private let refreshControl = UIRefreshControl()
  48. private var loadingSearch = false
  49. struct cacheImages {
  50. static var cellPlayImage = UIImage()
  51. static var cellFavouriteImage = UIImage()
  52. }
  53. required init?(coder aDecoder: NSCoder) {
  54. super.init(coder: aDecoder)
  55. appDelegate.activeMedia = self
  56. }
  57. override func viewDidLoad() {
  58. super.viewDidLoad()
  59. self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: CCGraphics.changeThemingColorImage(UIImage(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(touchUpInsideMenuButtonMore))
  60. // Cell
  61. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  62. // Header
  63. collectionView.register(UINib.init(nibName: "NCSectionMediaHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  64. // Footer
  65. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  66. collectionView.alwaysBounceVertical = true
  67. collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0);
  68. gridLayout = NCGridMediaLayout()
  69. gridLayout.itemPerLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5))
  70. gridLayout.sectionHeadersPinToVisibleBounds = true
  71. collectionView.collectionViewLayout = gridLayout
  72. // Add Refresh Control
  73. collectionView.refreshControl = refreshControl
  74. // empty Data Source
  75. collectionView.emptyDataSetDelegate = self
  76. collectionView.emptyDataSetSource = self
  77. // 3D Touch peek and pop
  78. if traitCollection.forceTouchCapability == .available {
  79. registerForPreviewing(with: self, sourceView: view)
  80. }
  81. // Notification
  82. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  83. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  84. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  85. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  86. plusButton = UIBarButtonItem(title: " + ", style: .plain, target: self, action: #selector(dezoomGrid))
  87. plusButton.isEnabled = !(self.gridLayout.itemPerLine == 1)
  88. separatorButton = UIBarButtonItem(title: "/", style: .plain, target: nil, action: nil)
  89. separatorButton.isEnabled = false
  90. separatorButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : NCBrandColor.sharedInstance.brandElement], for: .disabled)
  91. minusButton = UIBarButtonItem(title: " - ", style: .plain, target: self, action: #selector(zoomGrid))
  92. minusButton.isEnabled = !(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1)
  93. gridButton = UIBarButtonItem(image: CCGraphics.changeThemingColorImage(UIImage(named: "grid"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(enableZoomGridButtons))
  94. self.navigationItem.leftBarButtonItem = gridButton
  95. reloadDataSource()
  96. changeTheming()
  97. }
  98. @objc func enableZoomGridButtons() {
  99. self.navigationItem.setLeftBarButtonItems([plusButton,separatorButton,minusButton], animated: true)
  100. }
  101. @objc func removeZoomGridButtons() {
  102. if self.navigationItem.leftBarButtonItems?.count != 1 {
  103. self.navigationItem.setLeftBarButtonItems([gridButton], animated: true)
  104. }
  105. }
  106. @objc func zoomGrid() {
  107. UIView.animate(withDuration: 0.0, animations: {
  108. if(self.gridLayout.itemPerLine + 1 < self.kMaxImageGrid) {
  109. self.gridLayout.itemPerLine += 1
  110. self.plusButton.isEnabled = true
  111. }
  112. if(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1) {
  113. self.minusButton.isEnabled = false
  114. }
  115. self.collectionView.collectionViewLayout.invalidateLayout()
  116. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  117. })
  118. }
  119. @objc func dezoomGrid() {
  120. UIView.animate(withDuration: 0.0, animations: {
  121. if(self.gridLayout.itemPerLine - 1 > 0) {
  122. self.gridLayout.itemPerLine -= 1
  123. self.minusButton.isEnabled = true
  124. }
  125. if(self.gridLayout.itemPerLine == 1) {
  126. self.plusButton.isEnabled = false
  127. }
  128. self.collectionView.collectionViewLayout.invalidateLayout()
  129. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  130. })
  131. }
  132. override func viewWillAppear(_ animated: Bool) {
  133. super.viewWillAppear(animated)
  134. // Configure Refresh Control
  135. refreshControl.tintColor = .lightGray
  136. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  137. refreshControl.addTarget(self, action: #selector(searchNewPhotoVideo), for: .valueChanged)
  138. // get auto upload folder
  139. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  140. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  141. // Title
  142. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  143. }
  144. override func viewDidAppear(_ animated: Bool) {
  145. super.viewDidAppear(animated)
  146. searchNewPhotoVideo()
  147. }
  148. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  149. super.viewWillTransition(to: size, with: coordinator)
  150. coordinator.animate(alongsideTransition: nil) { _ in
  151. self.reloadDataThenPerform { }
  152. }
  153. }
  154. //MARK: - NotificationCenter
  155. @objc func changeTheming() {
  156. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  157. refreshControl.tintColor = .lightGray
  158. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  159. cacheImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  160. cacheImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  161. }
  162. @objc func deleteFile(_ notification: NSNotification) {
  163. if let userInfo = notification.userInfo as NSDictionary? {
  164. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  165. self.reloadDataSource()
  166. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  167. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  168. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  169. }
  170. }
  171. }
  172. }
  173. @objc func moveFile(_ notification: NSNotification) {
  174. if let userInfo = notification.userInfo as NSDictionary? {
  175. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  176. self.reloadDataSource()
  177. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  178. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  179. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  180. }
  181. }
  182. }
  183. }
  184. @objc func renameFile(_ notification: NSNotification) {
  185. if let userInfo = notification.userInfo as NSDictionary? {
  186. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  187. self.reloadDataSource()
  188. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  189. let userInfo: [String : Any] = ["metadata": metadata, "type": "rename"]
  190. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  191. }
  192. }
  193. }
  194. }
  195. // MARK: DZNEmpty
  196. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  197. return NCBrandColor.sharedInstance.backgroundView
  198. }
  199. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  200. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  201. }
  202. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  203. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  204. if loadingSearch {
  205. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  206. }
  207. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  208. return NSAttributedString.init(string: text, attributes: attributes)
  209. }
  210. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  211. return true
  212. }
  213. // MARK: IBAction
  214. @objc func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  215. UIView.animate(withDuration: 0.0, animations: {
  216. if(self.gridLayout.itemPerLine + 1 < self.kMaxImageGrid && self.gridLayout.increasing) {
  217. self.gridLayout.itemPerLine+=1
  218. } else {
  219. self.gridLayout.increasing = false
  220. self.gridLayout.itemPerLine-=1
  221. }
  222. if(self.gridLayout.itemPerLine == 0) {
  223. self.gridLayout.increasing = true
  224. self.gridLayout.itemPerLine = 2
  225. }
  226. self.collectionView.collectionViewLayout.invalidateLayout()
  227. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  228. })
  229. }
  230. @objc func touchUpInsideMenuButtonMore(_ sender: Any) {
  231. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  232. var actions: [NCMenuAction] = []
  233. if !isEditMode {
  234. actions.append(
  235. NCMenuAction(
  236. title: NSLocalizedString("_select_", comment: ""),
  237. icon: CCGraphics.changeThemingColorImage(UIImage(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  238. action: { menuAction in
  239. self.isEditMode = true
  240. }
  241. )
  242. )
  243. actions.append(
  244. NCMenuAction(
  245. title: NSLocalizedString(filterTypeFileImage ? "_media_viewimage_show_" : "_media_viewimage_hide_", comment: ""),
  246. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileImage ? "imageno" : "imageyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  247. action: { menuAction in
  248. self.filterTypeFileImage = !self.filterTypeFileImage
  249. self.reloadDataSource()
  250. }
  251. )
  252. )
  253. actions.append(
  254. NCMenuAction(
  255. title: NSLocalizedString(filterTypeFileVideo ? "_media_viewvideo_show_" : "_media_viewvideo_hide_", comment: ""),
  256. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileVideo ? "videono" : "videoyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  257. action: { menuAction in
  258. self.filterTypeFileVideo = !self.filterTypeFileVideo
  259. self.reloadDataSource()
  260. }
  261. )
  262. )
  263. } else {
  264. actions.append(
  265. NCMenuAction(
  266. title: NSLocalizedString("_deselect_", comment: ""),
  267. icon: CCGraphics.changeThemingColorImage(UIImage(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  268. action: { menuAction in
  269. self.isEditMode = false
  270. self.selectocId.removeAll()
  271. self.reloadDataThenPerform {
  272. }
  273. }
  274. )
  275. )
  276. actions.append(
  277. NCMenuAction(
  278. title: NSLocalizedString("_delete_", comment: ""),
  279. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  280. action: { menuAction in
  281. self.deleteItems()
  282. }
  283. )
  284. )
  285. }
  286. mainMenuViewController.actions = actions
  287. let menuPanelController = NCMenuPanelController()
  288. menuPanelController.parentPresenter = self
  289. menuPanelController.delegate = mainMenuViewController
  290. menuPanelController.set(contentViewController: mainMenuViewController)
  291. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  292. self.present(menuPanelController, animated: true, completion: nil)
  293. }
  294. // MARK: SEGUE
  295. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  296. if let segueNavigationController = segue.destination as? UINavigationController {
  297. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  298. segueViewController.metadata = metadataPush
  299. segueViewController.metadatas = sectionDatasource.metadatas as! [tableMetadata]
  300. segueViewController.mediaFilterImage = true
  301. }
  302. }
  303. }
  304. }
  305. // MARK: - 3D Touch peek and pop
  306. extension NCMedia: UIViewControllerPreviewingDelegate {
  307. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  308. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  309. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  310. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else { return nil }
  311. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  312. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  313. previewingContext.sourceRect = cell.frame
  314. viewController.metadata = metadata
  315. viewController.imageFile = cell.imageItem.image
  316. viewController.showOpenIn = true
  317. viewController.showShare = false
  318. viewController.showOpenQuickLook = false
  319. return viewController
  320. }
  321. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  322. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  323. collectionView(collectionView, didSelectItemAt: indexPath)
  324. }
  325. }
  326. // MARK: - Collection View
  327. extension NCMedia: UICollectionViewDelegate {
  328. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  329. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  330. return
  331. }
  332. metadataPush = metadata
  333. if isEditMode {
  334. if let index = selectocId.firstIndex(of: metadata.ocId) {
  335. selectocId.remove(at: index)
  336. } else {
  337. selectocId.append(metadata.ocId)
  338. }
  339. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  340. collectionView.reloadItems(at: [indexPath])
  341. }
  342. return
  343. }
  344. performSegue(withIdentifier: "segueDetail", sender: self)
  345. }
  346. }
  347. extension NCMedia: UICollectionViewDataSource {
  348. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  349. CATransaction.begin()
  350. CATransaction.setCompletionBlock(closure)
  351. collectionView?.reloadData()
  352. CATransaction.commit()
  353. }
  354. func updateLabelDate() {
  355. if let cell = collectionView?.visibleCells.first as? NCGridMediaCell {
  356. if cell.date != nil {
  357. //self.dataLabel.text = CCUtility.getTitleSectionDate(cell.date)
  358. }
  359. }
  360. }
  361. /*
  362. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  363. switch kind {
  364. case UICollectionView.elementKindSectionFooter:
  365. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  366. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  367. return footer
  368. default:
  369. return UICollectionReusableView()
  370. }
  371. /*
  372. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  373. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  374. header.labelSection.textColor = .white
  375. header.labelHeightConstraint.constant = 20
  376. header.labelSection.layer.cornerRadius = 10
  377. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  378. let width = header.labelSection.intrinsicContentSize.width + 30
  379. let leading = collectionView.bounds.width / 2 - width / 2
  380. header.labelWidthConstraint.constant = width
  381. header.labelLeadingConstraint.constant = leading
  382. return header
  383. */
  384. }
  385. */
  386. func numberOfSections(in collectionView: UICollectionView) -> Int {
  387. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  388. return sections
  389. }
  390. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  391. var numberOfItemsInSection: Int = 0
  392. if section < sectionDatasource.sections.count {
  393. let key = sectionDatasource.sections.object(at: section)
  394. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  395. numberOfItemsInSection = datasource.count
  396. }
  397. return numberOfItemsInSection
  398. }
  399. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  400. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  401. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  402. }
  403. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  404. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  405. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  406. cell.imageItem.backgroundColor = nil
  407. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  408. } else if(!metadata.hasPreview) {
  409. cell.imageItem.backgroundColor = nil
  410. if metadata.iconName.count > 0 {
  411. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  412. } else {
  413. cell.imageItem.image = UIImage.init(named: "file")
  414. }
  415. }
  416. cell.date = metadata.date as Date
  417. // image status
  418. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  419. cell.imageStatus.image = cacheImages.cellPlayImage
  420. }
  421. // image Local
  422. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  423. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  424. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  425. else { cell.imageLocal.image = UIImage.init(named: "local") }
  426. }
  427. // image Favorite
  428. if metadata.favorite {
  429. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  430. }
  431. if isEditMode {
  432. cell.imageSelect.isHidden = false
  433. if selectocId.contains(metadata.ocId) {
  434. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  435. cell.imageVisualEffect.isHidden = false
  436. cell.imageVisualEffect.alpha = 0.4
  437. } else {
  438. cell.imageSelect.isHidden = true
  439. cell.imageVisualEffect.isHidden = true
  440. }
  441. } else {
  442. cell.imageSelect.isHidden = true
  443. cell.imageVisualEffect.isHidden = true
  444. }
  445. return cell
  446. }
  447. }
  448. extension NCMedia: UICollectionViewDelegateFlowLayout {
  449. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  450. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  451. }
  452. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  453. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  454. if (section == sections - 1) {
  455. return CGSize(width: collectionView.frame.width, height: footerHeight)
  456. } else {
  457. return CGSize(width: collectionView.frame.width, height: 0)
  458. }
  459. }
  460. }
  461. // MARK: - NC API & Algorithm
  462. extension NCMedia {
  463. public func reloadDataSource() {
  464. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  465. return
  466. }
  467. DispatchQueue.global().async {
  468. let metadatas = NCManageDatabase.sharedInstance.getMetadatasMedia(account: self.appDelegate.activeAccount)
  469. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, filterLivePhoto: true, sorted: "date", ascending: false, activeAccount: self.appDelegate.activeAccount)
  470. DispatchQueue.main.async {
  471. self.reloadDataThenPerform {
  472. self.updateLabelDate()
  473. }
  474. }
  475. }
  476. }
  477. @objc func searchNewPhotoVideo() {
  478. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  479. //let elementDate = "nc:upload_time/"
  480. //let lteDate: Int = Int(Date().timeIntervalSince1970)
  481. //let gteDate: Int = Int(fromDate!.timeIntervalSince1970)
  482. guard let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: Date()) else { return }
  483. guard var gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  484. if let date = tableAccount?.dateUpdateMedia {
  485. gteDate = date as Date
  486. }
  487. NCCommunication.shared.searchMedia(lteDate: lteDate, gteDate: gteDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  488. if errorCode == 0 && files != nil && files!.count > 0 {
  489. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  490. NCManageDatabase.sharedInstance.setAccountDateLteMedia(date: files?.last?.date)
  491. NCManageDatabase.sharedInstance.setAccountDateUpdateMedia()
  492. }
  493. self.refreshControl.endRefreshing()
  494. self.reloadDataSource()
  495. }
  496. }
  497. private func searchOldPhotoVideo(gteDate: Date? = nil) {
  498. var lteDate = Date()
  499. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  500. if let date = tableAccount?.dateLteMedia {
  501. lteDate = date as Date
  502. }
  503. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  504. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: height + 50)
  505. var gteDate = gteDate
  506. if gteDate == nil {
  507. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: lteDate)
  508. }
  509. NCCommunication.shared.searchMedia(lteDate: lteDate, gteDate: gteDate!, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  510. if errorCode == 0 {
  511. if files != nil && files!.count > 0 {
  512. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  513. NCManageDatabase.sharedInstance.setAccountDateLteMedia(date: files?.last?.date)
  514. NCManageDatabase.sharedInstance.setAccountDateUpdateMedia()
  515. self.reloadDataSource()
  516. } else {
  517. if gteDate == Calendar.current.date(byAdding: .day, value: -30, to: lteDate) {
  518. self.searchOldPhotoVideo(gteDate: Calendar.current.date(byAdding: .day, value: -90, to: lteDate))
  519. } else if gteDate == Calendar.current.date(byAdding: .day, value: -90, to: lteDate) {
  520. self.searchOldPhotoVideo(gteDate: Date.distantPast)
  521. }
  522. }
  523. }
  524. NCUtility.sharedInstance.stopActivityIndicator()
  525. }
  526. }
  527. func deleteItems() {
  528. self.isEditMode = false
  529. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  530. return
  531. }
  532. // copy in arrayDeleteMetadata
  533. for ocId in selectocId {
  534. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  535. appDelegate.arrayDeleteMetadata.add(metadata)
  536. }
  537. }
  538. if let metadata = appDelegate.arrayDeleteMetadata.firstObject {
  539. appDelegate.arrayDeleteMetadata.removeObject(at: 0)
  540. NCNetworking.shared.deleteMetadata(metadata as! tableMetadata, account: appDelegate.activeAccount, url: appDelegate.activeUrl) { (errorCode, errorDescription) in }
  541. }
  542. }
  543. private func downloadThumbnail() {
  544. guard let collectionView = self.collectionView else { return }
  545. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  546. for item in collectionView.indexPathsForVisibleItems {
  547. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  548. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: item)
  549. }
  550. }
  551. }
  552. }
  553. private func removeDeletedFile() {
  554. guard let collectionView = self.collectionView else { return }
  555. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  556. for item in collectionView.indexPathsForVisibleItems {
  557. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  558. NCOperationQueue.shared.removeDeletedFile(metadata: metadata)
  559. }
  560. }
  561. }
  562. }
  563. }
  564. // MARK: - ScrollView
  565. extension NCMedia: UIScrollViewDelegate {
  566. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  567. self.removeZoomGridButtons()
  568. updateLabelDate()
  569. }
  570. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  571. if !decelerate {
  572. self.removeDeletedFile()
  573. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  574. searchOldPhotoVideo()
  575. }
  576. }
  577. }
  578. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  579. self.removeDeletedFile()
  580. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  581. searchOldPhotoVideo()
  582. }
  583. }
  584. }