NCMedia.swift 35 KB

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