NCMedia.swift 34 KB

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