NCMedia.swift 39 KB

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