NCMedia.swift 33 KB

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