NCMedia.swift 37 KB

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