NCMedia.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  339. let metadata = metadatas[indexPath.row]
  340. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  341. }
  342. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  343. let metadata = metadatas[indexPath.row]
  344. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  345. }
  346. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  347. let metadata = metadatas[indexPath.row]
  348. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  349. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  350. cell.imageItem.backgroundColor = nil
  351. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  352. } else if(!metadata.hasPreview) {
  353. cell.imageItem.backgroundColor = nil
  354. if metadata.iconName.count > 0 {
  355. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  356. } else {
  357. cell.imageItem.image = UIImage.init(named: "file")
  358. }
  359. }
  360. cell.date = metadata.date as Date
  361. // image status
  362. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  363. cell.imageStatus.image = cacheImages.cellPlayImage
  364. }
  365. // image Local
  366. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  367. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  368. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  369. else { cell.imageLocal.image = UIImage.init(named: "local") }
  370. }
  371. // image Favorite
  372. if metadata.favorite {
  373. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  374. }
  375. if isEditMode {
  376. cell.imageSelect.isHidden = false
  377. if selectocId.contains(metadata.ocId) {
  378. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  379. cell.imageVisualEffect.isHidden = false
  380. cell.imageVisualEffect.alpha = 0.4
  381. } else {
  382. cell.imageSelect.isHidden = true
  383. cell.imageVisualEffect.isHidden = true
  384. }
  385. } else {
  386. cell.imageSelect.isHidden = true
  387. cell.imageVisualEffect.isHidden = true
  388. }
  389. return cell
  390. }
  391. }
  392. extension NCMedia: UICollectionViewDelegateFlowLayout {
  393. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  394. return CGSize(width: collectionView.frame.width, height: 0)
  395. }
  396. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  397. return CGSize(width: collectionView.frame.width, height: 0)
  398. }
  399. }
  400. // MARK: - NC API & Algorithm
  401. extension NCMedia {
  402. @objc func reloadDataSource() {
  403. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  404. return
  405. }
  406. var predicate: NSPredicate?
  407. if filterTypeFileImage && filterTypeFileVideo { // HAS SENSE ???
  408. predicate = NSPredicate(format: "account == %@ AND typeFile == ''", appDelegate.activeAccount)
  409. } else if filterTypeFileImage {
  410. predicate = NSPredicate(format: "account == %@ AND typeFile == %@", appDelegate.activeAccount, k_metadataTypeFile_video)
  411. } else if filterTypeFileVideo {
  412. predicate = NSPredicate(format: "account == %@ AND typeFile == %@", appDelegate.activeAccount, k_metadataTypeFile_image)
  413. } else {
  414. predicate = NSPredicate(format: "account == %@ AND (typeFile == %@ OR typeFile == %@)", appDelegate.activeAccount, k_metadataTypeFile_image, k_metadataTypeFile_video)
  415. }
  416. NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicate!) { (metadatas) in
  417. DispatchQueue.main.async {
  418. self.metadatas = metadatas
  419. if self.metadatas.count > 0 {
  420. self.mediaCommandView?.isHidden = false
  421. } else {
  422. self.mediaCommandView?.isHidden = true
  423. }
  424. self.reloadDataThenPerform {
  425. self.mediaCommandTitle()
  426. }
  427. }
  428. }
  429. }
  430. @objc func searchNewPhotoVideo() {
  431. if newInProgress { return }
  432. else { newInProgress = true }
  433. collectionView.reloadData()
  434. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  435. //let elementDate = "nc:upload_time/"
  436. //let lteDate: Int = Int(Date().timeIntervalSince1970)
  437. //let gteDate: Int = Int(fromDate!.timeIntervalSince1970)
  438. guard let lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  439. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  440. if let date = tableAccount?.dateUpdateNewMedia {
  441. greaterDate = date as Date
  442. }
  443. NCCommunication.shared.searchMedia(lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  444. self.newInProgress = false
  445. self.collectionView.reloadData()
  446. if errorCode == 0 && files != nil && files!.count > 0 {
  447. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  448. if tableAccount?.dateLessMedia == nil {
  449. NCManageDatabase.sharedInstance.setAccountDateLessMedia(date: files?.last?.date)
  450. }
  451. NCManageDatabase.sharedInstance.setAccountDateUpdateNewMedia()
  452. self.reloadDataSource()
  453. }
  454. }
  455. }
  456. private func searchOldPhotoVideo(greaterDate: Date? = nil) {
  457. if oldInProgress { return }
  458. else { oldInProgress = true }
  459. collectionView.reloadData()
  460. var lessDate = Date()
  461. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  462. if let date = tableAccount?.dateLessMedia {
  463. lessDate = date as Date
  464. }
  465. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  466. var greaterDate = greaterDate
  467. if greaterDate == nil {
  468. greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: lessDate)
  469. }
  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 {
  476. if files != nil && files!.count > 0 {
  477. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  478. NCManageDatabase.sharedInstance.setAccountDateLessMedia(date: files?.last?.date)
  479. self.reloadDataSource()
  480. } else {
  481. if greaterDate == Calendar.current.date(byAdding: .day, value: -30, to: lessDate) {
  482. self.searchOldPhotoVideo(greaterDate: Calendar.current.date(byAdding: .day, value: -90, to: lessDate))
  483. } else if greaterDate == Calendar.current.date(byAdding: .day, value: -90, to: lessDate) {
  484. self.searchOldPhotoVideo(greaterDate: Calendar.current.date(byAdding: .day, value: -180, to: lessDate))
  485. } else {
  486. self.searchOldPhotoVideo(greaterDate: Date.distantPast)
  487. }
  488. }
  489. }
  490. }
  491. }
  492. private func downloadThumbnail() {
  493. guard let collectionView = self.collectionView else { return }
  494. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  495. for indexPath in collectionView.indexPathsForVisibleItems {
  496. let metadata = self.metadatas[indexPath.row]
  497. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  498. }
  499. }
  500. }
  501. private func readFiles() {
  502. guard let collectionView = self.collectionView else { return }
  503. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  504. for indexPath in collectionView.indexPathsForVisibleItems {
  505. let metadata = self.metadatas[indexPath.row]
  506. NCOperationQueue.shared.readFileForMedia(metadata: metadata)
  507. }
  508. }
  509. }
  510. }
  511. // MARK: - ScrollView
  512. extension NCMedia: UIScrollViewDelegate {
  513. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  514. mediaCommandTitle()
  515. mediaCommandView?.collapseControlButtonView(true)
  516. }
  517. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  518. if !decelerate {
  519. self.readFiles()
  520. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  521. searchOldPhotoVideo()
  522. }
  523. }
  524. }
  525. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  526. self.readFiles()
  527. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  528. searchOldPhotoVideo()
  529. }
  530. }
  531. }
  532. // MARK: - Media Command View
  533. class NCMediaCommandView: UIView {
  534. @IBOutlet weak var moreView: UIVisualEffectView!
  535. @IBOutlet weak var gridSwitchButton: UIButton!
  536. @IBOutlet weak var separatorView: UIView!
  537. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  538. @IBOutlet weak var zoomInButton: UIButton!
  539. @IBOutlet weak var zoomOutButton: UIButton!
  540. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  541. @IBOutlet weak var title : UILabel!
  542. var mediaView:NCMedia?
  543. private let gradient: CAGradientLayer = CAGradientLayer()
  544. override func awakeFromNib() {
  545. moreView.layer.cornerRadius = 20
  546. moreView.layer.masksToBounds = true
  547. controlButtonView.layer.cornerRadius = 20
  548. controlButtonView.layer.masksToBounds = true
  549. gradient.frame = bounds
  550. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  551. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  552. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  553. layer.insertSublayer(gradient, at: 0)
  554. title.text = ""
  555. }
  556. @IBAction func moreButtonPressed(_ sender: UIButton) {
  557. mediaView?.openMenuButtonMore(sender)
  558. }
  559. @IBAction func zoomInPressed(_ sender: UIButton) {
  560. mediaView?.zoomInGrid()
  561. }
  562. @IBAction func zoomOutPressed(_ sender: UIButton) {
  563. mediaView?.zoomOutGrid()
  564. }
  565. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  566. self.collapseControlButtonView(false)
  567. }
  568. func collapseControlButtonView(_ collapse: Bool) {
  569. if (collapse) {
  570. self.buttonControlWidthConstraint.constant = 40
  571. UIView.animate(withDuration: 0.25) {
  572. self.zoomOutButton.isHidden = true
  573. self.zoomInButton.isHidden = true
  574. self.separatorView.isHidden = true
  575. self.gridSwitchButton.isHidden = false
  576. self.layoutIfNeeded()
  577. }
  578. } else {
  579. self.buttonControlWidthConstraint.constant = 80
  580. UIView.animate(withDuration: 0.25) {
  581. self.zoomOutButton.isHidden = false
  582. self.zoomInButton.isHidden = false
  583. self.separatorView.isHidden = false
  584. self.gridSwitchButton.isHidden = true
  585. self.layoutIfNeeded()
  586. }
  587. }
  588. }
  589. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  590. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  591. }
  592. override func layoutSublayers(of layer: CALayer) {
  593. super.layoutSublayers(of: layer)
  594. gradient.frame = bounds
  595. }
  596. }