NCMedia.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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 Sheeeeeeeeet
  25. import FastScroll
  26. class NCMedia: UIViewController, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, NCSelectDelegate {
  27. @IBOutlet weak var collectionView : FastScrollCollectionView!
  28. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. var sectionDatasource = CCSectionDataSourceMetadata()
  30. private var metadataPush: tableMetadata?
  31. private var isEditMode = false
  32. private var selectocId = [String]()
  33. private var filterTypeFileImage = false;
  34. private var filterTypeFileVideo = false;
  35. private var autoUploadFileName = ""
  36. private var autoUploadDirectory = ""
  37. private var gridLayout: NCGridMediaLayout!
  38. private var actionSheet: ActionSheet?
  39. private let sectionHeaderHeight: CGFloat = 50
  40. private let footerHeight: CGFloat = 50
  41. private var stepImageWidth: CGFloat = 10
  42. private var isDistantPast = false
  43. private let refreshControl = UIRefreshControl()
  44. private var loadingSearch = false
  45. required init?(coder aDecoder: NSCoder) {
  46. super.init(coder: aDecoder)
  47. appDelegate.activeMedia = self
  48. }
  49. override func viewDidLoad() {
  50. super.viewDidLoad()
  51. 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))
  52. 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))
  53. // Cell
  54. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  55. // Header
  56. collectionView.register(UINib.init(nibName: "NCSectionMediaHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  57. // Footer
  58. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  59. collectionView.alwaysBounceVertical = true
  60. gridLayout = NCGridMediaLayout()
  61. gridLayout.preferenceWidth = CGFloat(CCUtility.getMediaWidthImage())
  62. gridLayout.sectionHeadersPinToVisibleBounds = true
  63. collectionView.collectionViewLayout = gridLayout
  64. // Add Refresh Control
  65. collectionView.refreshControl = refreshControl
  66. // empty Data Source
  67. collectionView.emptyDataSetDelegate = self
  68. collectionView.emptyDataSetSource = self
  69. // 3D Touch peek and pop
  70. if traitCollection.forceTouchCapability == .available {
  71. registerForPreviewing(with: self, sourceView: view)
  72. }
  73. // Notification
  74. NotificationCenter.default.addObserver(self, selector: #selector(self.deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  75. NotificationCenter.default.addObserver(self, selector: #selector(self.changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  76. NotificationCenter.default.addObserver(self, selector: #selector(self.moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  77. NotificationCenter.default.addObserver(self, selector: #selector(self.renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  78. // changeTheming
  79. changeTheming()
  80. }
  81. override func viewWillAppear(_ animated: Bool) {
  82. super.viewWillAppear(animated)
  83. // Configure Refresh Control
  84. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  85. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  86. refreshControl.addTarget(self, action: #selector(loadNetworkDatasource), for: .valueChanged)
  87. // get auto upload folder
  88. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  89. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  90. // Title
  91. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  92. // Fast Scrool
  93. configFastScroll()
  94. // Reload Data Source
  95. self.reloadDataSource(loadNetworkDatasource: true) { }
  96. }
  97. override func viewDidAppear(_ animated: Bool) {
  98. super.viewDidAppear(animated)
  99. collectionView?.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.collectionView?.reloadDataThenPerform {
  107. self.downloadThumbnail()
  108. }
  109. self.actionSheet?.viewDidLayoutSubviews()
  110. }
  111. }
  112. //MARK: - NotificationCenter
  113. @objc func changeTheming() {
  114. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  115. }
  116. @objc func deleteFile(_ notification: NSNotification) {
  117. if let userInfo = notification.userInfo as NSDictionary? {
  118. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  119. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  120. self.reloadDataSource(loadNetworkDatasource: false) {
  121. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  122. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  123. }
  124. }
  125. }
  126. }
  127. }
  128. @objc func moveFile(_ notification: NSNotification) {
  129. if let userInfo = notification.userInfo as NSDictionary? {
  130. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  131. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  132. self.reloadDataSource(loadNetworkDatasource: false) {
  133. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  134. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  135. }
  136. }
  137. }
  138. }
  139. }
  140. @objc func renameFile(_ notification: NSNotification) {
  141. if let userInfo = notification.userInfo as NSDictionary? {
  142. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  143. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  144. self.reloadDataSource(loadNetworkDatasource: false) {
  145. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "rename"]
  146. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  147. }
  148. }
  149. }
  150. }
  151. }
  152. // MARK: DZNEmpty
  153. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  154. return NCBrandColor.sharedInstance.backgroundView
  155. }
  156. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  157. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  158. }
  159. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  160. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  161. if loadingSearch {
  162. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  163. }
  164. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  165. return NSAttributedString.init(string: text, attributes: attributes)
  166. }
  167. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  168. return true
  169. }
  170. // MARK: IBAction
  171. @objc func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  172. let itemSizeStart = self.gridLayout.itemSize
  173. UIView.animate(withDuration: 0.0, animations: {
  174. if self.gridLayout.numItems == 1 && self.stepImageWidth > 0 {
  175. self.stepImageWidth = -10
  176. } else if itemSizeStart.width < 50 {
  177. self.stepImageWidth = 10
  178. }
  179. repeat {
  180. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.stepImageWidth
  181. } while (self.gridLayout.itemSize == itemSizeStart)
  182. CCUtility.setMediaWidthImage(Int(self.gridLayout?.preferenceWidth ?? 80))
  183. self.collectionView.collectionViewLayout.invalidateLayout()
  184. if self.stepImageWidth < 0 {
  185. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  186. self.selectSearchSections()
  187. }
  188. }
  189. })
  190. }
  191. @objc func touchUpInsideMenuButtonMore(_ sender: Any) {
  192. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  193. var actions = [NCMenuAction]()
  194. if !isEditMode {
  195. actions.append(
  196. NCMenuAction(
  197. title: NSLocalizedString("_select_", comment: ""),
  198. icon: CCGraphics.changeThemingColorImage(UIImage(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  199. action: { menuAction in
  200. self.isEditMode = true
  201. }
  202. )
  203. )
  204. actions.append(
  205. NCMenuAction(
  206. title: NSLocalizedString("_select_media_folder_", comment: ""),
  207. icon: CCGraphics.changeThemingColorImage(UIImage(named: "folderAutomaticUpload"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  208. action: { menuAction in
  209. self.selectStartDirectoryPhotosTab()
  210. }
  211. )
  212. )
  213. actions.append(
  214. NCMenuAction(
  215. title: NSLocalizedString(filterTypeFileImage ? "_media_viewimage_show_" : "_media_viewimage_hide_", comment: ""),
  216. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileImage ? "imageno" : "imageyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  217. action: { menuAction in
  218. self.filterTypeFileImage = !self.filterTypeFileImage
  219. self.reloadDataSource(loadNetworkDatasource: false) { }
  220. }
  221. )
  222. )
  223. actions.append(
  224. NCMenuAction(
  225. title: NSLocalizedString(filterTypeFileVideo ? "_media_viewvideo_show_" : "_media_viewvideo_hide_", comment: ""),
  226. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileVideo ? "videono" : "videoyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  227. action: { menuAction in
  228. self.filterTypeFileVideo = !self.filterTypeFileVideo
  229. self.reloadDataSource(loadNetworkDatasource: false) { }
  230. }
  231. )
  232. )
  233. } else {
  234. actions.append(
  235. NCMenuAction(
  236. title: NSLocalizedString("_cancel_", comment: ""),
  237. icon: CCGraphics.changeThemingColorImage(UIImage(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  238. action: { menuAction in
  239. self.isEditMode = false
  240. self.selectocId.removeAll()
  241. self.collectionView?.reloadDataThenPerform {
  242. self.downloadThumbnail()
  243. }
  244. }
  245. )
  246. )
  247. actions.append(
  248. NCMenuAction(
  249. title: NSLocalizedString("_delete_", comment: ""),
  250. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  251. action: { menuAction in
  252. self.deleteItems()
  253. }
  254. )
  255. )
  256. }
  257. mainMenuViewController.actions = actions
  258. let menuPanelController = NCMenuPanelController()
  259. menuPanelController.parentPresenter = self
  260. menuPanelController.delegate = mainMenuViewController
  261. menuPanelController.set(contentViewController: mainMenuViewController)
  262. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  263. self.present(menuPanelController, animated: true, completion: nil)
  264. }
  265. // MARK: Select Directory
  266. func selectStartDirectoryPhotosTab() {
  267. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  268. let viewController = navigationController.topViewController as! NCSelect
  269. viewController.delegate = self
  270. viewController.hideButtonCreateFolder = true
  271. viewController.includeDirectoryE2EEncryption = false
  272. viewController.includeImages = false
  273. viewController.layoutViewSelect = k_layout_view_move
  274. viewController.selectFile = false
  275. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  276. viewController.type = "mediaFolder"
  277. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  278. self.present(navigationController, animated: true, completion: nil)
  279. }
  280. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  281. let oldStartDirectoryMediaTabView = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  282. if serverUrl != nil && serverUrl != oldStartDirectoryMediaTabView {
  283. // Save Start Directory
  284. NCManageDatabase.sharedInstance.setAccountStartDirectoryMediaTabView(serverUrl!)
  285. //
  286. NCManageDatabase.sharedInstance.clearTable(tableMedia.self, account: appDelegate.activeAccount)
  287. self.sectionDatasource = CCSectionDataSourceMetadata()
  288. //
  289. loadNetworkDatasource()
  290. }
  291. }
  292. // MARK: SEGUE
  293. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  294. let photoDataSource: NSMutableArray = []
  295. for ocId: String in sectionDatasource.allOcId as! [String] {
  296. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: ocId) as! tableMetadata
  297. if metadata.typeFile == k_metadataTypeFile_image {
  298. photoDataSource.add(metadata)
  299. }
  300. }
  301. if let segueNavigationController = segue.destination as? UINavigationController {
  302. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  303. segueViewController.metadata = metadataPush
  304. segueViewController.metadatas = sectionDatasource.metadatas as! [tableMetadata]
  305. segueViewController.mediaFilterImage = true
  306. }
  307. }
  308. }
  309. }
  310. // MARK: - 3D Touch peek and pop
  311. extension NCMedia: UIViewControllerPreviewingDelegate {
  312. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  313. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  314. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  315. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else { return nil }
  316. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  317. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  318. previewingContext.sourceRect = cell.frame
  319. viewController.metadata = metadata
  320. viewController.imageFile = cell.imageItem.image
  321. viewController.showOpenIn = true
  322. viewController.showShare = false
  323. viewController.showOpenInternalViewer = false
  324. return viewController
  325. }
  326. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  327. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  328. collectionView(collectionView, didSelectItemAt: indexPath)
  329. }
  330. }
  331. // MARK: - Collection View
  332. extension NCMedia: UICollectionViewDelegate {
  333. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  334. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  335. return
  336. }
  337. metadataPush = metadata
  338. if isEditMode {
  339. if let index = selectocId.firstIndex(of: metadata.ocId) {
  340. selectocId.remove(at: index)
  341. } else {
  342. selectocId.append(metadata.ocId)
  343. }
  344. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  345. collectionView.reloadItems(at: [indexPath])
  346. }
  347. return
  348. }
  349. performSegue(withIdentifier: "segueDetail", sender: self)
  350. }
  351. }
  352. extension NCMedia: UICollectionViewDataSource {
  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.collectionView?.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. for ocId in selectocId {
  434. if let metadata = NCManageDatabase.sharedInstance.getMedia(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  435. NCNetworking.sharedInstance.deleteMetadata(metadata, user: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: appDelegate.activeUrl) { (errorCode, errorDescription) in }
  436. }
  437. }
  438. }
  439. func search(lteDate: Date, gteDate: Date, addPast: Bool, insertPrevius: Int,setDistantPast: Bool, debug: String) {
  440. // ----- DEBUG -----
  441. #if DEBUG
  442. let dateFormatter = DateFormatter()
  443. dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
  444. print("[LOG] Search: addPast \(addPast), distantPass: \(setDistantPast), Lte: " + dateFormatter.string(from: lteDate) + " - Gte: " + dateFormatter.string(from: gteDate) + " DEBUG: " + debug)
  445. #endif
  446. // -----------------
  447. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  448. return
  449. }
  450. if addPast && loadingSearch {
  451. return
  452. }
  453. if setDistantPast {
  454. isDistantPast = true
  455. }
  456. if addPast {
  457. //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)
  458. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  459. }
  460. loadingSearch = true
  461. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  462. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  463. self.refreshControl.endRefreshing()
  464. NCUtility.sharedInstance.stopActivityIndicator()
  465. //self.navigationItem.titleView = nil
  466. //self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  467. if errorCode == 0 && account == self.appDelegate.activeAccount {
  468. var isDifferent: Bool = false
  469. var newInsert: Int = 0
  470. let totalDistance = Calendar.current.dateComponents([Calendar.Component.day], from: gteDate, to: lteDate).value(for: .day) ?? 0
  471. let difference = NCManageDatabase.sharedInstance.createTableMedia(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  472. isDifferent = difference.isDifferent
  473. newInsert = difference.newInsert
  474. self.loadingSearch = false
  475. print("[LOG] Search: Totale Distance \(totalDistance) - It's Different \(isDifferent) - New insert \(newInsert)")
  476. if isDifferent {
  477. self.reloadDataSource(loadNetworkDatasource: false) { }
  478. }
  479. if (isDifferent == false || newInsert+insertPrevius < 100) && addPast && setDistantPast == false {
  480. switch totalDistance {
  481. case 0...89:
  482. if var gteDate90 = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  483. gteDate90 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate90) ?? Date()
  484. self.search(lteDate: lteDate, gteDate: gteDate90, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -90 gg")
  485. }
  486. case 90...179:
  487. if var gteDate180 = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  488. gteDate180 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate180) ?? Date()
  489. self.search(lteDate: lteDate, gteDate: gteDate180, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -180 gg")
  490. }
  491. case 180...364:
  492. if var gteDate365 = Calendar.current.date(byAdding: .day, value: -365, to: gteDate) {
  493. gteDate365 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate365) ?? Date()
  494. self.search(lteDate: lteDate, gteDate: gteDate365, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -365 gg")
  495. }
  496. default:
  497. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: true, debug: "search recursive distant pass")
  498. }
  499. }
  500. self.collectionView?.reloadDataThenPerform {
  501. self.downloadThumbnail()
  502. }
  503. } else {
  504. self.loadingSearch = false
  505. self.reloadDataSource(loadNetworkDatasource: false) { }
  506. }
  507. })
  508. }
  509. @objc private func loadNetworkDatasource() {
  510. isDistantPast = false
  511. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  512. return
  513. }
  514. if sectionDatasource.allRecordsDataSource.count == 0 {
  515. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  516. search(lteDate: Date(), gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) today, -30 gg")
  517. } else {
  518. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  519. search(lteDate: Date(), gteDate: gteDate, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search today, first date record")
  520. }
  521. collectionView?.reloadDataThenPerform {
  522. self.downloadThumbnail()
  523. }
  524. }
  525. private func selectSearchSections() {
  526. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  527. return
  528. }
  529. let sections = NSMutableSet()
  530. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  531. var gteDate: Date?
  532. for item in collectionView.indexPathsForVisibleItems {
  533. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  534. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  535. sections.add(date)
  536. }
  537. }
  538. }
  539. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  540. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  541. }
  542. if sortedSections.count >= 1 {
  543. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  544. if lastDate == sortedSections.last as! Date {
  545. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  546. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) last record, -30 gg")
  547. } else {
  548. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  549. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search [refresh window]")
  550. }
  551. }
  552. }
  553. private func downloadThumbnail() {
  554. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  555. for item in self.collectionView.indexPathsForVisibleItems {
  556. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  557. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: self.collectionView as Any, indexPath: item)
  558. }
  559. }
  560. }
  561. }
  562. }
  563. // MARK: - FastScroll - ScrollView
  564. extension NCMedia: UIScrollViewDelegate {
  565. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  566. collectionView.scrollViewDidScroll(scrollView)
  567. }
  568. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  569. collectionView.scrollViewWillBeginDragging(scrollView)
  570. }
  571. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  572. collectionView.scrollViewDidEndDecelerating(scrollView)
  573. }
  574. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  575. collectionView.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
  576. }
  577. func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
  578. selectSearchSections()
  579. }
  580. }
  581. extension NCMedia: FastScrollCollectionViewDelegate {
  582. fileprivate func configFastScroll() {
  583. collectionView.fastScrollDelegate = self
  584. //bubble
  585. collectionView.deactivateBubble = true
  586. collectionView.bubbleFocus = .dynamic
  587. collectionView.bubbleTextSize = 14.0
  588. collectionView.bubbleMarginRight = 50.0
  589. collectionView.bubbleColor = UIColor(red: 38.0 / 255.0, green: 48.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
  590. //handle
  591. /*
  592. collectionView.handleHeight = 40.0
  593. collectionView.handleWidth = 40.0
  594. collectionView.handleRadius = 20.0
  595. */
  596. collectionView.handleTimeToDisappear = 1
  597. collectionView.handleMarginRight = 3
  598. collectionView.handleColor = NCBrandColor.sharedInstance.brand
  599. collectionView.handle?.backgroundColor = NCBrandColor.sharedInstance.brand
  600. //scrollbar
  601. collectionView.scrollbarWidth = 0.0
  602. collectionView.scrollbarMarginTop = 43.0
  603. collectionView.scrollbarMarginBottom = 5.0
  604. collectionView.scrollbarMarginRight = 10.0
  605. //callback action to display bubble name
  606. /*
  607. collectionView.bubbleNameForIndexPath = { indexPath in
  608. let visibleSection: Section = self.data[indexPath.section]
  609. return visibleSection.sectionTitle
  610. }
  611. */
  612. }
  613. func hideHandle() {
  614. selectSearchSections()
  615. }
  616. }
  617. extension FastScrollCollectionView
  618. {
  619. /// Calls reloadsData() on self, and ensures that the given closure is
  620. /// called after reloadData() has been completed.
  621. ///
  622. /// Discussion: reloadData() appears to be asynchronous. i.e. the
  623. /// reloading actually happens during the next layout pass. So, doing
  624. /// things like scrolling the collectionView immediately after a
  625. /// call to reloadData() can cause trouble.
  626. ///
  627. /// This method uses CATransaction to schedule the closure.
  628. func reloadDataThenPerform(_ closure: @escaping (() -> Void))
  629. {
  630. CATransaction.begin()
  631. CATransaction.setCompletionBlock(closure)
  632. self.reloadData()
  633. CATransaction.commit()
  634. }
  635. }