NCMedia.swift 35 KB

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