NCMedia.swift 35 KB

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