NCMedia.swift 35 KB

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