DiscoveryNewsViewModel.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // DiscoveryNewsViewModel.swift
  3. // Mastodon
  4. //
  5. // Created by MainasuK on 2022-4-13.
  6. //
  7. import os.log
  8. import UIKit
  9. import Combine
  10. import GameplayKit
  11. import CoreData
  12. import CoreDataStack
  13. import MastodonSDK
  14. import MastodonCore
  15. final class DiscoveryNewsViewModel {
  16. var disposeBag = Set<AnyCancellable>()
  17. // input
  18. let context: AppContext
  19. let authContext: AuthContext
  20. let listBatchFetchViewModel = ListBatchFetchViewModel()
  21. // output
  22. @Published var links: [Mastodon.Entity.Link] = []
  23. var diffableDataSource: UITableViewDiffableDataSource<DiscoverySection, DiscoveryItem>?
  24. private(set) lazy var stateMachine: GKStateMachine = {
  25. let stateMachine = GKStateMachine(states: [
  26. State.Initial(viewModel: self),
  27. State.Reloading(viewModel: self),
  28. State.Fail(viewModel: self),
  29. State.Idle(viewModel: self),
  30. State.Loading(viewModel: self),
  31. State.NoMore(viewModel: self),
  32. ])
  33. stateMachine.enter(State.Initial.self)
  34. return stateMachine
  35. }()
  36. let didLoadLatest = PassthroughSubject<Void, Never>()
  37. @Published var isServerSupportEndpoint = true
  38. init(context: AppContext, authContext: AuthContext) {
  39. self.context = context
  40. self.authContext = authContext
  41. // end init
  42. Task {
  43. await checkServerEndpoint()
  44. } // end Task
  45. }
  46. deinit {
  47. os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s", ((#file as NSString).lastPathComponent), #line, #function)
  48. }
  49. }
  50. extension DiscoveryNewsViewModel {
  51. func checkServerEndpoint() async {
  52. do {
  53. _ = try await context.apiService.trendLinks(
  54. domain: authContext.mastodonAuthenticationBox.domain,
  55. query: .init(offset: nil, limit: nil)
  56. )
  57. } catch let error as Mastodon.API.Error where error.httpResponseStatus.code == 404 {
  58. isServerSupportEndpoint = false
  59. } catch {
  60. // do nothing
  61. }
  62. }
  63. }