NCMedia.swift 35 KB

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