NCMedia.swift 35 KB

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