NCMedia.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. private var gridLayout: NCGridMediaLayout!
  29. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. public var metadatas: [tableMetadata] = []
  31. private var metadataPush: tableMetadata?
  32. private var predicate: NSPredicate?
  33. private var isEditMode = false
  34. private var selectocId: [String] = []
  35. private var filterTypeFileImage = false;
  36. private var filterTypeFileVideo = false;
  37. private let kMaxImageGrid: CGFloat = 5
  38. private var cellHeigth: CGFloat = 0
  39. private var oldInProgress = false
  40. private var newInProgress = false
  41. private var lastContentOffsetY: CGFloat = 0
  42. struct cacheImages {
  43. static var cellPlayImage = UIImage()
  44. static var cellFavouriteImage = UIImage()
  45. }
  46. // MARK: - View Life Cycle
  47. required init?(coder aDecoder: NSCoder) {
  48. super.init(coder: aDecoder)
  49. appDelegate.activeMedia = self
  50. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  51. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: NSNotification.Name(rawValue: k_notificationCenter_applicationWillEnterForeground), object: nil)
  52. }
  53. override func viewDidLoad() {
  54. super.viewDidLoad()
  55. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  56. collectionView.alwaysBounceVertical = true
  57. collectionView.contentInset = UIEdgeInsets(top: 75, left: 0, bottom: 50, right: 0);
  58. gridLayout = NCGridMediaLayout()
  59. gridLayout.itemPerLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5))
  60. gridLayout.sectionHeadersPinToVisibleBounds = true
  61. collectionView.collectionViewLayout = gridLayout
  62. // empty Data Source
  63. collectionView.emptyDataSetDelegate = self
  64. collectionView.emptyDataSetSource = self
  65. // 3D Touch peek and pop
  66. if traitCollection.forceTouchCapability == .available {
  67. registerForPreviewing(with: self, sourceView: view)
  68. }
  69. // Notification
  70. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  71. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  72. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  73. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  74. mediaCommandView = Bundle.main.loadNibNamed("NCMediaCommandView", owner: self, options: nil)?.first as? NCMediaCommandView
  75. self.view.addSubview(mediaCommandView!)
  76. mediaCommandView?.mediaView = self
  77. mediaCommandView?.zoomInButton.isEnabled = !(self.gridLayout.itemPerLine == 1)
  78. mediaCommandView?.zoomOutButton.isEnabled = !(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1)
  79. mediaCommandView?.collapseControlButtonView(true)
  80. mediaCommandView?.translatesAutoresizingMaskIntoConstraints = false
  81. mediaCommandView?.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  82. mediaCommandView?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  83. mediaCommandView?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  84. mediaCommandView?.heightAnchor.constraint(equalToConstant: 150).isActive = true
  85. self.updateMediaControlVisibility()
  86. changeTheming()
  87. }
  88. override func viewWillAppear(_ animated: Bool) {
  89. super.viewWillAppear(animated)
  90. }
  91. override func viewDidAppear(_ animated: Bool) {
  92. super.viewDidAppear(animated)
  93. reloadDataSourceWithCompletion {
  94. self.searchNewPhotoVideo()
  95. }
  96. }
  97. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  98. super.viewWillTransition(to: size, with: coordinator)
  99. coordinator.animate(alongsideTransition: nil) { _ in
  100. self.reloadDataThenPerform { }
  101. }
  102. }
  103. override var preferredStatusBarStyle: UIStatusBarStyle {
  104. return .lightContent
  105. }
  106. //MARK: - Notification
  107. @objc func applicationWillEnterForeground() {
  108. if self.view.window != nil {
  109. self.viewDidAppear(false)
  110. }
  111. }
  112. //MARK: - Command
  113. func mediaCommandTitle() {
  114. mediaCommandView?.title.text = ""
  115. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  116. if let cell = visibleCells.first as? NCGridMediaCell {
  117. if cell.date != nil {
  118. mediaCommandView?.title.text = CCUtility.getTitleSectionDate(cell.date)
  119. }
  120. }
  121. }
  122. }
  123. @objc func zoomOutGrid() {
  124. UIView.animate(withDuration: 0.0, animations: {
  125. if(self.gridLayout.itemPerLine + 1 < self.kMaxImageGrid) {
  126. self.gridLayout.itemPerLine += 1
  127. self.mediaCommandView?.zoomInButton.isEnabled = true
  128. }
  129. if(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1) {
  130. self.mediaCommandView?.zoomOutButton.isEnabled = false
  131. }
  132. self.collectionView.collectionViewLayout.invalidateLayout()
  133. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  134. })
  135. }
  136. @objc func zoomInGrid() {
  137. UIView.animate(withDuration: 0.0, animations: {
  138. if(self.gridLayout.itemPerLine - 1 > 0) {
  139. self.gridLayout.itemPerLine -= 1
  140. self.mediaCommandView?.zoomOutButton.isEnabled = true
  141. }
  142. if(self.gridLayout.itemPerLine == 1) {
  143. self.mediaCommandView?.zoomInButton.isEnabled = false
  144. }
  145. self.collectionView.collectionViewLayout.invalidateLayout()
  146. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  147. })
  148. }
  149. @objc func openMenuButtonMore(_ sender: Any) {
  150. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  151. var actions: [NCMenuAction] = []
  152. if !isEditMode {
  153. if metadatas.count > 0 {
  154. actions.append(
  155. NCMenuAction(
  156. title: NSLocalizedString("_select_", comment: ""),
  157. icon: CCGraphics.changeThemingColorImage(UIImage(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  158. action: { menuAction in
  159. self.isEditMode = true
  160. }
  161. )
  162. )
  163. }
  164. actions.append(
  165. NCMenuAction(
  166. title: NSLocalizedString(filterTypeFileImage ? "_media_viewimage_show_" : "_media_viewimage_hide_", comment: ""),
  167. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileImage ? "imageno" : "imageyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  168. action: { menuAction in
  169. self.filterTypeFileImage = !self.filterTypeFileImage
  170. self.filterTypeFileVideo = false
  171. self.reloadDataSource()
  172. }
  173. )
  174. )
  175. actions.append(
  176. NCMenuAction(
  177. title: NSLocalizedString(filterTypeFileVideo ? "_media_viewvideo_show_" : "_media_viewvideo_hide_", comment: ""),
  178. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileVideo ? "videono" : "videoyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  179. action: { menuAction in
  180. self.filterTypeFileVideo = !self.filterTypeFileVideo
  181. self.filterTypeFileImage = false
  182. self.reloadDataSource()
  183. }
  184. )
  185. )
  186. } else {
  187. actions.append(
  188. NCMenuAction(
  189. title: NSLocalizedString("_deselect_", comment: ""),
  190. icon: CCGraphics.changeThemingColorImage(UIImage(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  191. action: { menuAction in
  192. self.isEditMode = false
  193. self.selectocId.removeAll()
  194. self.reloadDataThenPerform { }
  195. }
  196. )
  197. )
  198. actions.append(
  199. NCMenuAction(
  200. title: NSLocalizedString("_delete_", comment: ""),
  201. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  202. action: { menuAction in
  203. self.isEditMode = false
  204. for ocId in self.selectocId {
  205. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  206. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.activeAccount, url: self.appDelegate.activeUrl) { (errorCode, errorDescription) in }
  207. }
  208. }
  209. }
  210. )
  211. )
  212. }
  213. mainMenuViewController.actions = actions
  214. let menuPanelController = NCMenuPanelController()
  215. menuPanelController.parentPresenter = self
  216. menuPanelController.delegate = mainMenuViewController
  217. menuPanelController.set(contentViewController: mainMenuViewController)
  218. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  219. self.present(menuPanelController, animated: true, completion: nil)
  220. }
  221. //MARK: - NotificationCenter
  222. @objc func changeTheming() {
  223. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  224. cacheImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  225. cacheImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  226. self.navigationController?.setNavigationBarHidden(true, animated: false)
  227. }
  228. @objc func deleteFile(_ notification: NSNotification) {
  229. if let userInfo = notification.userInfo as NSDictionary? {
  230. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  231. if metadata.account == appDelegate.activeAccount {
  232. let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == metadata.ocId }
  233. let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
  234. self.metadatas = metadatas
  235. if let row = indexes.first {
  236. let indexPath = IndexPath(row: row, section: 0)
  237. collectionView?.deleteItems(at: [indexPath])
  238. }
  239. self.updateMediaControlVisibility()
  240. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  241. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  242. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  243. }
  244. }
  245. }
  246. }
  247. }
  248. @objc func moveFile(_ notification: NSNotification) {
  249. if let userInfo = notification.userInfo as NSDictionary? {
  250. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  251. if metadata.account == appDelegate.activeAccount {
  252. self.reloadDataSourceWithCompletion() {
  253. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  254. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  255. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  256. }
  257. }
  258. }
  259. }
  260. }
  261. }
  262. @objc func renameFile(_ notification: NSNotification) {
  263. if let userInfo = notification.userInfo as NSDictionary? {
  264. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  265. if metadata.account == appDelegate.activeAccount {
  266. self.reloadDataSourceWithCompletion() {
  267. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  268. let userInfo: [String : Any] = ["metadata": metadata, "type": "rename"]
  269. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  270. }
  271. }
  272. }
  273. }
  274. }
  275. }
  276. // MARK: DZNEmpty
  277. func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
  278. return 0
  279. }
  280. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  281. return NCBrandColor.sharedInstance.backgroundView
  282. }
  283. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  284. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  285. }
  286. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  287. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  288. if oldInProgress || newInProgress {
  289. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  290. }
  291. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  292. return NSAttributedString.init(string: text, attributes: attributes)
  293. }
  294. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  295. return true
  296. }
  297. // MARK: SEGUE
  298. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  299. if let segueNavigationController = segue.destination as? UINavigationController {
  300. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  301. segueViewController.metadata = metadataPush
  302. segueViewController.metadatas = metadatas
  303. segueViewController.mediaFilterImage = true
  304. }
  305. }
  306. }
  307. }
  308. // MARK: - 3D Touch peek and pop
  309. extension NCMedia: UIViewControllerPreviewingDelegate {
  310. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  311. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  312. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  313. let metadata = metadatas[indexPath.row]
  314. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  315. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  316. previewingContext.sourceRect = cell.frame
  317. viewController.metadata = metadata
  318. viewController.imageFile = cell.imageItem.image
  319. viewController.showOpenIn = true
  320. viewController.showShare = false
  321. viewController.showOpenQuickLook = false
  322. return viewController
  323. }
  324. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  325. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  326. collectionView(collectionView, didSelectItemAt: indexPath)
  327. }
  328. }
  329. // MARK: - Collection View
  330. extension NCMedia: UICollectionViewDelegate {
  331. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  332. let metadata = metadatas[indexPath.row]
  333. metadataPush = metadata
  334. if isEditMode {
  335. if let index = selectocId.firstIndex(of: metadata.ocId) {
  336. selectocId.remove(at: index)
  337. } else {
  338. selectocId.append(metadata.ocId)
  339. }
  340. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  341. collectionView.reloadItems(at: [indexPath])
  342. }
  343. return
  344. }
  345. performSegue(withIdentifier: "segueDetail", sender: self)
  346. }
  347. }
  348. extension NCMedia: UICollectionViewDataSource {
  349. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  350. CATransaction.begin()
  351. CATransaction.setCompletionBlock(closure)
  352. collectionView?.reloadData()
  353. CATransaction.commit()
  354. }
  355. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  356. return metadatas.count
  357. }
  358. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  359. if indexPath.row < self.metadatas.count {
  360. let metadata = self.metadatas[indexPath.row]
  361. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  362. NCOperationQueue.shared.readFileForMedia(metadata: metadata)
  363. }
  364. }
  365. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  366. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  367. let metadata = metadatas[indexPath.row]
  368. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  369. NCOperationQueue.shared.cancelReadFileForMedia(metadata: metadata)
  370. }
  371. }
  372. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  373. let metadata = metadatas[indexPath.row]
  374. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  375. self.cellHeigth = cell.frame.size.height
  376. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  377. cell.imageItem.backgroundColor = nil
  378. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  379. } else if(!metadata.hasPreview) {
  380. cell.imageItem.backgroundColor = nil
  381. if metadata.iconName.count > 0 {
  382. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  383. } else {
  384. cell.imageItem.image = UIImage.init(named: "file")
  385. }
  386. }
  387. cell.date = metadata.date as Date
  388. // image status
  389. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  390. cell.imageStatus.image = cacheImages.cellPlayImage
  391. }
  392. // image Local
  393. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  394. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  395. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  396. else { cell.imageLocal.image = UIImage.init(named: "local") }
  397. }
  398. // image Favorite
  399. if metadata.favorite {
  400. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  401. }
  402. if isEditMode {
  403. cell.imageSelect.isHidden = false
  404. if selectocId.contains(metadata.ocId) {
  405. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  406. cell.imageVisualEffect.isHidden = false
  407. cell.imageVisualEffect.alpha = 0.4
  408. } else {
  409. cell.imageSelect.isHidden = true
  410. cell.imageVisualEffect.isHidden = true
  411. }
  412. } else {
  413. cell.imageSelect.isHidden = true
  414. cell.imageVisualEffect.isHidden = true
  415. }
  416. return cell
  417. }
  418. }
  419. extension NCMedia: UICollectionViewDelegateFlowLayout {
  420. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  421. return CGSize(width: collectionView.frame.width, height: 0)
  422. }
  423. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  424. return CGSize(width: collectionView.frame.width, height: 0)
  425. }
  426. }
  427. // MARK: - NC API & Algorithm
  428. extension NCMedia {
  429. @objc func reloadDataSource() {
  430. self.reloadDataSourceWithCompletion { }
  431. }
  432. private func reloadDataSourceWithCompletion(_ completion: @escaping () -> Void) {
  433. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) { return }
  434. if filterTypeFileImage {
  435. predicate = NSPredicate(format: "account == %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.activeAccount, k_metadataTypeFile_video)
  436. } else if filterTypeFileVideo {
  437. predicate = NSPredicate(format: "account == %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.activeAccount, k_metadataTypeFile_image)
  438. } else {
  439. predicate = NSPredicate(format: "account == %@ AND (typeFile == %@ OR typeFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.activeAccount, k_metadataTypeFile_image, k_metadataTypeFile_video)
  440. }
  441. NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicate!) { (metadatas) in
  442. DispatchQueue.main.sync {
  443. self.metadatas = metadatas
  444. self.updateMediaControlVisibility()
  445. self.reloadDataThenPerform {
  446. self.mediaCommandTitle()
  447. completion()
  448. }
  449. }
  450. }
  451. }
  452. func updateMediaControlVisibility() {
  453. if self.metadatas.count == 0 {
  454. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  455. self.mediaCommandView?.isHidden = true
  456. } else {
  457. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  458. self.mediaCommandView?.isHidden = false
  459. }
  460. } else {
  461. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  462. self.mediaCommandView?.isHidden = false
  463. }
  464. }
  465. private func searchOldPhotoVideo(value: Int = -30) {
  466. if oldInProgress { return }
  467. else { oldInProgress = true }
  468. collectionView.reloadData()
  469. var lessDate = Date()
  470. var greaterDate: Date
  471. if metadatas.count > 0 {
  472. lessDate = metadatas.last!.date as Date
  473. }
  474. if value == -999 {
  475. greaterDate = Date.distantPast
  476. } else {
  477. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  478. }
  479. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  480. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: height + 50)
  481. NCCommunication.shared.searchMedia(lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  482. self.oldInProgress = false
  483. NCUtility.sharedInstance.stopActivityIndicator()
  484. self.collectionView.reloadData()
  485. if errorCode == 0 && account == self.appDelegate.activeAccount {
  486. if files?.count ?? 0 > 0 {
  487. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  488. self.reloadDataSource()
  489. } else {
  490. if value == -30 {
  491. self.searchOldPhotoVideo(value: -90)
  492. } else if value == -90 {
  493. self.searchOldPhotoVideo(value: -180)
  494. } else if value == -180 {
  495. self.searchOldPhotoVideo(value: -999)
  496. }
  497. }
  498. }
  499. }
  500. }
  501. @objc func searchNewPhotoVideo() {
  502. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  503. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  504. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  505. if let cell = visibleCells.first as? NCGridMediaCell {
  506. if cell.date != nil {
  507. if cell.date != metadatas.first?.date as Date? {
  508. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  509. }
  510. }
  511. }
  512. if let cell = visibleCells.last as? NCGridMediaCell {
  513. if cell.date != nil {
  514. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  515. }
  516. }
  517. }
  518. newInProgress = true
  519. collectionView.reloadData()
  520. NCCommunication.shared.searchMedia(lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  521. self.newInProgress = false
  522. if errorCode == 0 && account == self.appDelegate.activeAccount && files?.count ?? 0 > 0 {
  523. DispatchQueue.global().async {
  524. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  525. let newPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  526. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: newPredicate, sorted: nil, ascending: false){
  527. let etagsMetadatas = Array(metadatas.map { $0.etag })
  528. let etagsFiles = Array(files!.map { $0.etag })
  529. for etag in etagsFiles {
  530. if !etagsMetadatas.contains(etag) {
  531. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  532. self.reloadDataSource()
  533. break;
  534. }
  535. }
  536. } else {
  537. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  538. self.reloadDataSource()
  539. }
  540. }
  541. } else if errorCode == 0 && files?.count ?? 0 == 0 && self.metadatas.count == 0 {
  542. self.searchOldPhotoVideo()
  543. }
  544. }
  545. }
  546. private func downloadThumbnail() {
  547. guard let collectionView = self.collectionView else { return }
  548. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  549. for indexPath in collectionView.indexPathsForVisibleItems {
  550. let metadata = self.metadatas[indexPath.row]
  551. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  552. }
  553. }
  554. }
  555. }
  556. // MARK: - ScrollView
  557. extension NCMedia: UIScrollViewDelegate {
  558. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  559. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  560. mediaCommandTitle()
  561. lastContentOffsetY = scrollView.contentOffset.y
  562. }
  563. }
  564. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  565. mediaCommandView?.collapseControlButtonView(true)
  566. }
  567. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  568. if !decelerate {
  569. self.searchNewPhotoVideo()
  570. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  571. searchOldPhotoVideo()
  572. }
  573. }
  574. }
  575. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  576. self.searchNewPhotoVideo()
  577. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  578. searchOldPhotoVideo()
  579. }
  580. }
  581. }
  582. // MARK: - Media Command View
  583. class NCMediaCommandView: UIView {
  584. @IBOutlet weak var moreView: UIVisualEffectView!
  585. @IBOutlet weak var gridSwitchButton: UIButton!
  586. @IBOutlet weak var separatorView: UIView!
  587. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  588. @IBOutlet weak var zoomInButton: UIButton!
  589. @IBOutlet weak var zoomOutButton: UIButton!
  590. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  591. @IBOutlet weak var title : UILabel!
  592. var mediaView:NCMedia?
  593. private let gradient: CAGradientLayer = CAGradientLayer()
  594. override func awakeFromNib() {
  595. moreView.layer.cornerRadius = 20
  596. moreView.layer.masksToBounds = true
  597. controlButtonView.layer.cornerRadius = 20
  598. controlButtonView.layer.masksToBounds = true
  599. gradient.frame = bounds
  600. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  601. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  602. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  603. layer.insertSublayer(gradient, at: 0)
  604. title.text = ""
  605. }
  606. func toggleEmptyView(isEmpty: Bool) {
  607. if isEmpty {
  608. UIView.animate(withDuration: 0.3) {
  609. self.moreView.effect = UIBlurEffect(style: .dark)
  610. self.gradient.isHidden = true
  611. self.controlButtonView.isHidden = true
  612. }
  613. } else {
  614. UIView.animate(withDuration: 0.3) {
  615. self.moreView.effect = UIBlurEffect(style: .regular)
  616. self.gradient.isHidden = false
  617. self.controlButtonView.isHidden = false
  618. }
  619. }
  620. }
  621. @IBAction func moreButtonPressed(_ sender: UIButton) {
  622. mediaView?.openMenuButtonMore(sender)
  623. }
  624. @IBAction func zoomInPressed(_ sender: UIButton) {
  625. mediaView?.zoomInGrid()
  626. }
  627. @IBAction func zoomOutPressed(_ sender: UIButton) {
  628. mediaView?.zoomOutGrid()
  629. }
  630. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  631. self.collapseControlButtonView(false)
  632. }
  633. func collapseControlButtonView(_ collapse: Bool) {
  634. if (collapse) {
  635. self.buttonControlWidthConstraint.constant = 40
  636. UIView.animate(withDuration: 0.25) {
  637. self.zoomOutButton.isHidden = true
  638. self.zoomInButton.isHidden = true
  639. self.separatorView.isHidden = true
  640. self.gridSwitchButton.isHidden = false
  641. self.layoutIfNeeded()
  642. }
  643. } else {
  644. self.buttonControlWidthConstraint.constant = 80
  645. UIView.animate(withDuration: 0.25) {
  646. self.zoomOutButton.isHidden = false
  647. self.zoomInButton.isHidden = false
  648. self.separatorView.isHidden = false
  649. self.gridSwitchButton.isHidden = true
  650. self.layoutIfNeeded()
  651. }
  652. }
  653. }
  654. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  655. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  656. }
  657. override func layoutSublayers(of layer: CALayer) {
  658. super.layoutSublayers(of: layer)
  659. gradient.frame = bounds
  660. }
  661. }