NCMedia.swift 35 KB

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