NCMedia.swift 35 KB

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