NCMedia.swift 33 KB

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