NCMedia.swift 36 KB

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