NCMedia.swift 32 KB

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