NCMedia.swift 34 KB

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