NCMedia.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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: "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. }
  256. }
  257. }
  258. }
  259. // MARK: - 3D Touch peek and pop
  260. extension NCMedia: UIViewControllerPreviewingDelegate {
  261. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  262. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  263. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  264. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else { return nil }
  265. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  266. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  267. previewingContext.sourceRect = cell.frame
  268. viewController.metadata = metadata
  269. viewController.imageFile = cell.imageItem.image
  270. viewController.showOpenIn = true
  271. viewController.showShare = false
  272. viewController.showOpenInternalViewer = false
  273. return viewController
  274. }
  275. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  276. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  277. collectionView(collectionView, didSelectItemAt: indexPath)
  278. }
  279. }
  280. // MARK: - Collection View
  281. extension NCMedia: UICollectionViewDelegate {
  282. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  283. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  284. return
  285. }
  286. metadataPush = metadata
  287. if isEditMode {
  288. if let index = selectocId.firstIndex(of: metadata.ocId) {
  289. selectocId.remove(at: index)
  290. } else {
  291. selectocId.append(metadata.ocId)
  292. }
  293. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  294. collectionView.reloadItems(at: [indexPath])
  295. }
  296. return
  297. }
  298. performSegue(withIdentifier: "segueDetail", sender: self)
  299. }
  300. }
  301. extension NCMedia: UICollectionViewDataSource {
  302. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  303. if kind == UICollectionView.elementKindSectionHeader {
  304. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  305. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  306. header.labelSection.textColor = .white
  307. header.labelHeightConstraint.constant = 20
  308. header.labelSection.layer.cornerRadius = 10
  309. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  310. let width = header.labelSection.intrinsicContentSize.width + 30
  311. let leading = collectionView.bounds.width / 2 - width / 2
  312. header.labelWidthConstraint.constant = width
  313. header.labelLeadingConstraint.constant = leading
  314. return header
  315. } else {
  316. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  317. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  318. return footer
  319. }
  320. }
  321. func numberOfSections(in collectionView: UICollectionView) -> Int {
  322. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  323. return sections
  324. }
  325. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  326. var numberOfItemsInSection: Int = 0
  327. if section < sectionDatasource.sections.count {
  328. let key = sectionDatasource.sections.object(at: section)
  329. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  330. numberOfItemsInSection = datasource.count
  331. }
  332. return numberOfItemsInSection
  333. }
  334. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  335. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  336. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  337. }
  338. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  339. 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)
  340. return cell
  341. }
  342. }
  343. extension NCMedia: UICollectionViewDelegateFlowLayout {
  344. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  345. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  346. }
  347. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  348. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  349. if (section == sections - 1) {
  350. return CGSize(width: collectionView.frame.width, height: footerHeight)
  351. } else {
  352. return CGSize(width: collectionView.frame.width, height: 0)
  353. }
  354. }
  355. }
  356. // MARK: - NC API & Algorithm
  357. extension NCMedia {
  358. public func reloadDataSource(loadNetworkDatasource: Bool) {
  359. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  360. return
  361. }
  362. DispatchQueue.global().async {
  363. let metadatas = NCManageDatabase.sharedInstance.getTablesMedia(account: self.appDelegate.activeAccount)
  364. 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)
  365. DispatchQueue.main.async {
  366. self.collectionView?.reloadData()
  367. if loadNetworkDatasource {
  368. self.loadNetworkDatasource()
  369. }
  370. self.collectionView?.reloadDataThenPerform {
  371. self.downloadThumbnail()
  372. }
  373. }
  374. }
  375. }
  376. func deleteItems() {
  377. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  378. return
  379. }
  380. var metadatas = [tableMetadata]()
  381. for ocId in selectocId {
  382. if let metadata = NCManageDatabase.sharedInstance.getTableMedia(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  383. metadatas.append(metadata)
  384. }
  385. }
  386. if metadatas.count > 0 {
  387. NCMainCommon.sharedInstance.deleteFile(metadatas: metadatas as NSArray, e2ee: false, serverUrl: "", folderocId: "") { (errorCode, message) in
  388. self.isEditMode = false
  389. self.selectocId.removeAll()
  390. self.selectSearchSections()
  391. }
  392. }
  393. }
  394. func search(lteDate: Date, gteDate: Date, addPast: Bool, insertPrevius: Int,setDistantPast: Bool, debug: String) {
  395. // ----- DEBUG -----
  396. #if DEBUG
  397. let dateFormatter = DateFormatter()
  398. dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
  399. print("[LOG] Search: addPast \(addPast), distantPass: \(setDistantPast), Lte: " + dateFormatter.string(from: lteDate) + " - Gte: " + dateFormatter.string(from: gteDate) + " DEBUG: " + debug)
  400. #endif
  401. // -----------------
  402. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  403. return
  404. }
  405. if addPast && loadingSearch {
  406. return
  407. }
  408. if setDistantPast {
  409. isDistantPast = true
  410. }
  411. if addPast {
  412. //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)
  413. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  414. }
  415. loadingSearch = true
  416. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  417. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  418. self.refreshControl.endRefreshing()
  419. NCUtility.sharedInstance.stopActivityIndicator()
  420. //self.navigationItem.titleView = nil
  421. //self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  422. if errorCode == 0 && account == self.appDelegate.activeAccount {
  423. var isDifferent: Bool = false
  424. var newInsert: Int = 0
  425. let totalDistance = Calendar.current.dateComponents([Calendar.Component.day], from: gteDate, to: lteDate).value(for: .day) ?? 0
  426. let difference = NCManageDatabase.sharedInstance.createTableMedia(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  427. isDifferent = difference.isDifferent
  428. newInsert = difference.newInsert
  429. self.loadingSearch = false
  430. print("[LOG] Search: Totale Distance \(totalDistance) - It's Different \(isDifferent) - New insert \(newInsert)")
  431. if isDifferent {
  432. self.reloadDataSource(loadNetworkDatasource: false)
  433. }
  434. if (isDifferent == false || newInsert+insertPrevius < 100) && addPast && setDistantPast == false {
  435. switch totalDistance {
  436. case 0...89:
  437. if var gteDate90 = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  438. gteDate90 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate90) ?? Date()
  439. self.search(lteDate: lteDate, gteDate: gteDate90, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -90 gg")
  440. }
  441. case 90...179:
  442. if var gteDate180 = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  443. gteDate180 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate180) ?? Date()
  444. self.search(lteDate: lteDate, gteDate: gteDate180, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -180 gg")
  445. }
  446. case 180...364:
  447. if var gteDate365 = Calendar.current.date(byAdding: .day, value: -365, to: gteDate) {
  448. gteDate365 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate365) ?? Date()
  449. self.search(lteDate: lteDate, gteDate: gteDate365, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -365 gg")
  450. }
  451. default:
  452. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: true, debug: "search recursive distant pass")
  453. }
  454. }
  455. self.collectionView?.reloadDataThenPerform {
  456. self.downloadThumbnail()
  457. }
  458. } else {
  459. self.loadingSearch = false
  460. self.reloadDataSource(loadNetworkDatasource: false)
  461. }
  462. })
  463. }
  464. @objc private func loadNetworkDatasource() {
  465. isDistantPast = false
  466. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  467. return
  468. }
  469. if sectionDatasource.allRecordsDataSource.count == 0 {
  470. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  471. search(lteDate: Date(), gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) today, -30 gg")
  472. } else {
  473. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  474. search(lteDate: Date(), gteDate: gteDate, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search today, first date record")
  475. }
  476. collectionView?.reloadDataThenPerform {
  477. self.downloadThumbnail()
  478. }
  479. }
  480. private func selectSearchSections() {
  481. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  482. return
  483. }
  484. let sections = NSMutableSet()
  485. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  486. var gteDate: Date?
  487. for item in collectionView.indexPathsForVisibleItems {
  488. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  489. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  490. sections.add(date)
  491. }
  492. }
  493. }
  494. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  495. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  496. }
  497. if sortedSections.count >= 1 {
  498. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  499. if lastDate == sortedSections.last as! Date {
  500. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  501. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) last record, -30 gg")
  502. } else {
  503. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  504. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search [refresh window]")
  505. }
  506. }
  507. }
  508. private func downloadThumbnail() {
  509. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  510. for item in self.collectionView.indexPathsForVisibleItems {
  511. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  512. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: self.collectionView as Any, indexPath: item)
  513. }
  514. }
  515. }
  516. }
  517. }
  518. // MARK: - FastScroll - ScrollView
  519. extension NCMedia: UIScrollViewDelegate {
  520. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  521. collectionView.scrollViewDidScroll(scrollView)
  522. }
  523. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  524. collectionView.scrollViewWillBeginDragging(scrollView)
  525. }
  526. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  527. collectionView.scrollViewDidEndDecelerating(scrollView)
  528. }
  529. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  530. collectionView.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
  531. }
  532. func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
  533. selectSearchSections()
  534. }
  535. }
  536. extension NCMedia: FastScrollCollectionViewDelegate {
  537. fileprivate func configFastScroll() {
  538. collectionView.fastScrollDelegate = self
  539. //bubble
  540. collectionView.deactivateBubble = true
  541. collectionView.bubbleFocus = .dynamic
  542. collectionView.bubbleTextSize = 14.0
  543. collectionView.bubbleMarginRight = 50.0
  544. collectionView.bubbleColor = UIColor(red: 38.0 / 255.0, green: 48.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
  545. //handle
  546. /*
  547. collectionView.handleHeight = 40.0
  548. collectionView.handleWidth = 40.0
  549. collectionView.handleRadius = 20.0
  550. */
  551. collectionView.handleTimeToDisappear = 1
  552. collectionView.handleMarginRight = 3
  553. collectionView.handleColor = NCBrandColor.sharedInstance.brand
  554. collectionView.handle?.backgroundColor = NCBrandColor.sharedInstance.brand
  555. //scrollbar
  556. collectionView.scrollbarWidth = 0.0
  557. collectionView.scrollbarMarginTop = 43.0
  558. collectionView.scrollbarMarginBottom = 5.0
  559. collectionView.scrollbarMarginRight = 10.0
  560. //callback action to display bubble name
  561. /*
  562. collectionView.bubbleNameForIndexPath = { indexPath in
  563. let visibleSection: Section = self.data[indexPath.section]
  564. return visibleSection.sectionTitle
  565. }
  566. */
  567. }
  568. func hideHandle() {
  569. selectSearchSections()
  570. }
  571. }
  572. extension FastScrollCollectionView
  573. {
  574. /// Calls reloadsData() on self, and ensures that the given closure is
  575. /// called after reloadData() has been completed.
  576. ///
  577. /// Discussion: reloadData() appears to be asynchronous. i.e. the
  578. /// reloading actually happens during the next layout pass. So, doing
  579. /// things like scrolling the collectionView immediately after a
  580. /// call to reloadData() can cause trouble.
  581. ///
  582. /// This method uses CATransaction to schedule the closure.
  583. func reloadDataThenPerform(_ closure: @escaping (() -> Void))
  584. {
  585. CATransaction.begin()
  586. CATransaction.setCompletionBlock(closure)
  587. self.reloadData()
  588. CATransaction.commit()
  589. }
  590. }