NCMedia.swift 33 KB

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