NCMedia.swift 34 KB

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