NCMedia.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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: 0, 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. if self.metadatas.count == 0 {
  84. self.mediaCommandView?.isHidden = true
  85. }
  86. changeTheming()
  87. }
  88. override func viewWillAppear(_ animated: Bool) {
  89. super.viewWillAppear(animated)
  90. }
  91. override func viewDidAppear(_ animated: Bool) {
  92. super.viewDidAppear(animated)
  93. mediaCommandTitle()
  94. readFiles()
  95. searchNewPhotoVideo()
  96. }
  97. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  98. super.viewWillTransition(to: size, with: coordinator)
  99. coordinator.animate(alongsideTransition: nil) { _ in
  100. self.reloadDataThenPerform { }
  101. }
  102. }
  103. override var preferredStatusBarStyle: UIStatusBarStyle {
  104. return .lightContent
  105. }
  106. //MARK: - Command
  107. func mediaCommandTitle() {
  108. mediaCommandView?.title.text = ""
  109. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  110. if let cell = visibleCells.first as? NCGridMediaCell {
  111. if cell.date != nil {
  112. mediaCommandView?.title.text = CCUtility.getTitleSectionDate(cell.date)
  113. }
  114. }
  115. }
  116. }
  117. @objc func zoomOutGrid() {
  118. UIView.animate(withDuration: 0.0, animations: {
  119. if(self.gridLayout.itemPerLine + 1 < self.kMaxImageGrid) {
  120. self.gridLayout.itemPerLine += 1
  121. self.mediaCommandView?.zoomInButton.isEnabled = true
  122. }
  123. if(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1) {
  124. self.mediaCommandView?.zoomOutButton.isEnabled = false
  125. }
  126. self.collectionView.collectionViewLayout.invalidateLayout()
  127. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  128. })
  129. }
  130. @objc func zoomInGrid() {
  131. UIView.animate(withDuration: 0.0, animations: {
  132. if(self.gridLayout.itemPerLine - 1 > 0) {
  133. self.gridLayout.itemPerLine -= 1
  134. self.mediaCommandView?.zoomOutButton.isEnabled = true
  135. }
  136. if(self.gridLayout.itemPerLine == 1) {
  137. self.mediaCommandView?.zoomInButton.isEnabled = false
  138. }
  139. self.collectionView.collectionViewLayout.invalidateLayout()
  140. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  141. })
  142. }
  143. @objc func openMenuButtonMore(_ sender: Any) {
  144. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  145. var actions: [NCMenuAction] = []
  146. if !isEditMode {
  147. actions.append(
  148. NCMenuAction(
  149. title: NSLocalizedString("_select_", comment: ""),
  150. icon: CCGraphics.changeThemingColorImage(UIImage(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  151. action: { menuAction in
  152. self.isEditMode = true
  153. }
  154. )
  155. )
  156. 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. let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
  224. self.metadatas = metadatas
  225. if self.metadatas.count > 0 {
  226. self.mediaCommandView?.isHidden = false
  227. } else {
  228. self.mediaCommandView?.isHidden = true
  229. }
  230. self.reloadDataSource()
  231. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  232. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  233. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  234. }
  235. }
  236. }
  237. }
  238. @objc func moveFile(_ notification: NSNotification) {
  239. if let userInfo = notification.userInfo as NSDictionary? {
  240. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  241. self.reloadDataSource()
  242. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  243. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  244. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  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. self.reloadDataSource()
  253. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  254. let userInfo: [String : Any] = ["metadata": metadata, "type": "rename"]
  255. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  256. }
  257. }
  258. }
  259. }
  260. // MARK: DZNEmpty
  261. func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
  262. return 0
  263. }
  264. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  265. return NCBrandColor.sharedInstance.backgroundView
  266. }
  267. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  268. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  269. }
  270. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  271. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  272. if oldInProgress || newInProgress {
  273. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  274. }
  275. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  276. return NSAttributedString.init(string: text, attributes: attributes)
  277. }
  278. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  279. return true
  280. }
  281. // MARK: SEGUE
  282. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  283. if let segueNavigationController = segue.destination as? UINavigationController {
  284. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  285. segueViewController.metadata = metadataPush
  286. segueViewController.metadatas = metadatas
  287. segueViewController.mediaFilterImage = true
  288. }
  289. }
  290. }
  291. }
  292. // MARK: - 3D Touch peek and pop
  293. extension NCMedia: UIViewControllerPreviewingDelegate {
  294. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  295. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  296. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  297. let metadata = metadatas[indexPath.row]
  298. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  299. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  300. previewingContext.sourceRect = cell.frame
  301. viewController.metadata = metadata
  302. viewController.imageFile = cell.imageItem.image
  303. viewController.showOpenIn = true
  304. viewController.showShare = false
  305. viewController.showOpenQuickLook = false
  306. return viewController
  307. }
  308. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  309. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  310. collectionView(collectionView, didSelectItemAt: indexPath)
  311. }
  312. }
  313. // MARK: - Collection View
  314. extension NCMedia: UICollectionViewDelegate {
  315. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  316. let metadata = metadatas[indexPath.row]
  317. metadataPush = metadata
  318. if isEditMode {
  319. if let index = selectocId.firstIndex(of: metadata.ocId) {
  320. selectocId.remove(at: index)
  321. } else {
  322. selectocId.append(metadata.ocId)
  323. }
  324. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  325. collectionView.reloadItems(at: [indexPath])
  326. }
  327. return
  328. }
  329. performSegue(withIdentifier: "segueDetail", sender: self)
  330. }
  331. }
  332. extension NCMedia: UICollectionViewDataSource {
  333. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  334. CATransaction.begin()
  335. CATransaction.setCompletionBlock(closure)
  336. collectionView?.reloadData()
  337. CATransaction.commit()
  338. }
  339. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  340. return metadatas.count
  341. }
  342. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  343. if indexPath.row < metadatas.count {
  344. let metadata = metadatas[indexPath.row]
  345. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  346. }
  347. }
  348. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  349. if indexPath.row < metadatas.count {
  350. let metadata = metadatas[indexPath.row]
  351. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  352. }
  353. }
  354. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  355. let metadata = metadatas[indexPath.row]
  356. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  357. self.cellHeigth = cell.frame.size.height
  358. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  359. cell.imageItem.backgroundColor = nil
  360. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  361. } else if(!metadata.hasPreview) {
  362. cell.imageItem.backgroundColor = nil
  363. if metadata.iconName.count > 0 {
  364. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  365. } else {
  366. cell.imageItem.image = UIImage.init(named: "file")
  367. }
  368. }
  369. cell.date = metadata.date as Date
  370. // image status
  371. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  372. cell.imageStatus.image = cacheImages.cellPlayImage
  373. }
  374. // image Local
  375. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  376. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  377. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  378. else { cell.imageLocal.image = UIImage.init(named: "local") }
  379. }
  380. // image Favorite
  381. if metadata.favorite {
  382. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  383. }
  384. if isEditMode {
  385. cell.imageSelect.isHidden = false
  386. if selectocId.contains(metadata.ocId) {
  387. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  388. cell.imageVisualEffect.isHidden = false
  389. cell.imageVisualEffect.alpha = 0.4
  390. } else {
  391. cell.imageSelect.isHidden = true
  392. cell.imageVisualEffect.isHidden = true
  393. }
  394. } else {
  395. cell.imageSelect.isHidden = true
  396. cell.imageVisualEffect.isHidden = true
  397. }
  398. return cell
  399. }
  400. }
  401. extension NCMedia: UICollectionViewDelegateFlowLayout {
  402. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  403. return CGSize(width: collectionView.frame.width, height: 0)
  404. }
  405. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  406. return CGSize(width: collectionView.frame.width, height: 0)
  407. }
  408. }
  409. // MARK: - NC API & Algorithm
  410. extension NCMedia {
  411. @objc func reloadDataSource() {
  412. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  413. return
  414. }
  415. var predicate: NSPredicate?
  416. if filterTypeFileImage {
  417. predicate = NSPredicate(format: "account == %@ AND typeFile == %@", appDelegate.activeAccount, k_metadataTypeFile_video)
  418. } else if filterTypeFileVideo {
  419. predicate = NSPredicate(format: "account == %@ AND typeFile == %@", appDelegate.activeAccount, k_metadataTypeFile_image)
  420. } else {
  421. predicate = NSPredicate(format: "account == %@ AND (typeFile == %@ OR typeFile == %@)", appDelegate.activeAccount, k_metadataTypeFile_image, k_metadataTypeFile_video)
  422. }
  423. NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicate!) { (metadatas) in
  424. DispatchQueue.main.sync {
  425. self.metadatas = metadatas
  426. if self.metadatas.count > 0 {
  427. self.mediaCommandView?.isHidden = false
  428. } else {
  429. self.mediaCommandView?.isHidden = true
  430. }
  431. self.reloadDataThenPerform {
  432. self.mediaCommandTitle()
  433. }
  434. }
  435. }
  436. }
  437. @objc func searchNewPhotoVideo() {
  438. if newInProgress { return }
  439. else { newInProgress = true }
  440. collectionView.reloadData()
  441. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  442. //let elementDate = "nc:upload_time/"
  443. //let lteDate: Int = Int(Date().timeIntervalSince1970)
  444. //let gteDate: Int = Int(fromDate!.timeIntervalSince1970)
  445. guard let lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  446. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  447. if let date = tableAccount?.dateUpdateNewMedia {
  448. greaterDate = date as Date
  449. }
  450. NCCommunication.shared.searchMedia(lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  451. self.newInProgress = false
  452. self.collectionView.reloadData()
  453. if errorCode == 0 && files?.count ?? 0 > 0 {
  454. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  455. if tableAccount?.dateLessMedia == nil {
  456. NCManageDatabase.sharedInstance.setAccountDateLessMedia(date: files?.last?.date)
  457. }
  458. NCManageDatabase.sharedInstance.setAccountDateUpdateNewMedia()
  459. self.reloadDataSource()
  460. }
  461. if errorCode == 0 && files?.count ?? 0 == 0 && self.metadatas.count == 0 {
  462. self.searchOldPhotoVideo()
  463. }
  464. }
  465. }
  466. private func searchOldPhotoVideo(value: Int = -30) {
  467. if oldInProgress { return }
  468. else { oldInProgress = true }
  469. collectionView.reloadData()
  470. var lessDate = Date()
  471. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  472. if let date = tableAccount?.dateLessMedia {
  473. lessDate = date as Date
  474. }
  475. var greaterDate: Date
  476. if value == -999 {
  477. greaterDate = Date.distantPast
  478. } else {
  479. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  480. }
  481. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  482. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: height + 50)
  483. NCCommunication.shared.searchMedia(lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  484. self.oldInProgress = false
  485. NCUtility.sharedInstance.stopActivityIndicator()
  486. self.collectionView.reloadData()
  487. if errorCode == 0 {
  488. if files?.count ?? 0 > 0 {
  489. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  490. NCManageDatabase.sharedInstance.setAccountDateLessMedia(date: files?.last?.date)
  491. self.reloadDataSource()
  492. } else {
  493. if value == -30 {
  494. self.searchOldPhotoVideo(value: -90)
  495. } else if value == -90 {
  496. self.searchOldPhotoVideo(value: -180)
  497. } else if value == -180 {
  498. self.searchOldPhotoVideo(value: -999)
  499. }
  500. }
  501. }
  502. }
  503. }
  504. private func downloadThumbnail() {
  505. guard let collectionView = self.collectionView else { return }
  506. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  507. for indexPath in collectionView.indexPathsForVisibleItems {
  508. let metadata = self.metadatas[indexPath.row]
  509. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  510. }
  511. }
  512. }
  513. private func readFiles() {
  514. guard let collectionView = self.collectionView else { return }
  515. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  516. for indexPath in collectionView.indexPathsForVisibleItems {
  517. let metadata = self.metadatas[indexPath.row]
  518. NCOperationQueue.shared.readFileForMedia(metadata: metadata)
  519. }
  520. }
  521. }
  522. }
  523. // MARK: - ScrollView
  524. extension NCMedia: UIScrollViewDelegate {
  525. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  526. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  527. mediaCommandTitle()
  528. lastContentOffsetY = scrollView.contentOffset.y
  529. }
  530. }
  531. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  532. mediaCommandView?.collapseControlButtonView(true)
  533. }
  534. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  535. if !decelerate {
  536. self.readFiles()
  537. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  538. searchOldPhotoVideo()
  539. }
  540. }
  541. }
  542. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  543. self.readFiles()
  544. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  545. searchOldPhotoVideo()
  546. }
  547. }
  548. }
  549. // MARK: - Media Command View
  550. class NCMediaCommandView: UIView {
  551. @IBOutlet weak var moreView: UIVisualEffectView!
  552. @IBOutlet weak var gridSwitchButton: UIButton!
  553. @IBOutlet weak var separatorView: UIView!
  554. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  555. @IBOutlet weak var zoomInButton: UIButton!
  556. @IBOutlet weak var zoomOutButton: UIButton!
  557. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  558. @IBOutlet weak var title : UILabel!
  559. var mediaView:NCMedia?
  560. private let gradient: CAGradientLayer = CAGradientLayer()
  561. override func awakeFromNib() {
  562. moreView.layer.cornerRadius = 20
  563. moreView.layer.masksToBounds = true
  564. controlButtonView.layer.cornerRadius = 20
  565. controlButtonView.layer.masksToBounds = true
  566. gradient.frame = bounds
  567. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  568. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  569. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  570. layer.insertSublayer(gradient, at: 0)
  571. title.text = ""
  572. }
  573. @IBAction func moreButtonPressed(_ sender: UIButton) {
  574. mediaView?.openMenuButtonMore(sender)
  575. }
  576. @IBAction func zoomInPressed(_ sender: UIButton) {
  577. mediaView?.zoomInGrid()
  578. }
  579. @IBAction func zoomOutPressed(_ sender: UIButton) {
  580. mediaView?.zoomOutGrid()
  581. }
  582. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  583. self.collapseControlButtonView(false)
  584. }
  585. func collapseControlButtonView(_ collapse: Bool) {
  586. if (collapse) {
  587. self.buttonControlWidthConstraint.constant = 40
  588. UIView.animate(withDuration: 0.25) {
  589. self.zoomOutButton.isHidden = true
  590. self.zoomInButton.isHidden = true
  591. self.separatorView.isHidden = true
  592. self.gridSwitchButton.isHidden = false
  593. self.layoutIfNeeded()
  594. }
  595. } else {
  596. self.buttonControlWidthConstraint.constant = 80
  597. UIView.animate(withDuration: 0.25) {
  598. self.zoomOutButton.isHidden = false
  599. self.zoomInButton.isHidden = false
  600. self.separatorView.isHidden = false
  601. self.gridSwitchButton.isHidden = true
  602. self.layoutIfNeeded()
  603. }
  604. }
  605. }
  606. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  607. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  608. }
  609. override func layoutSublayers(of layer: CALayer) {
  610. super.layoutSublayers(of: layer)
  611. gradient.frame = bounds
  612. }
  613. }