NCMedia.swift 38 KB

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