~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
276 lines · 8.2 KB Raw History
import HydraulophoneCore
import SwiftUI

/// Main-actor state for the Home feature.
///
/// Home pages are intentionally kept as domain values here. The view model
/// owns the opaque continuation and the rules for replacing or appending
/// content, so a view refresh or a session transition cannot accidentally
/// expose private content from the previous audience.
@MainActor
final class HomeViewModel: ObservableObject {
  private struct LoadedContext: Equatable {
    let audience: HomeAudience
    let sessionID: Int
    let filter: HomeFilter?
  }

  private var service: (any PaginatedCatalogMusicService)?
  private var requestToken = UUID()
  private var loadedContext: LoadedContext?
  private var hasLoadedPage = false
  private var continuation: PaginationToken?
  private var requestedContinuations = Set<PaginationToken>()

  @Published private(set) var filters: [HomeFilter] = []
  @Published private(set) var sections: [HomeSection] = []
  @Published private(set) var isLoading = false
  @Published private(set) var isRefreshing = false
  @Published private(set) var isLoadingMore = false
  @Published private(set) var errorMessage: String?
  @Published private(set) var loadMoreErrorMessage: String?
  @Published private(set) var selectedFilter: HomeFilter?

  var hasMore: Bool {
    continuation != nil
  }

  init(service: (any PaginatedCatalogMusicService)? = nil) {
    self.service = service
  }

  func setService(_ service: (any PaginatedCatalogMusicService)?) {
    self.service = service
  }

  /// Drops all private Home state and invalidates any response currently in
  /// flight. This is deliberately synchronous so sign-out cannot briefly
  /// display the previous account's shelves.
  func clear() {
    requestToken = UUID()
    loadedContext = nil
    hasLoadedPage = false
    continuation = nil
    requestedContinuations.removeAll()
    filters = []
    sections = []
    isLoading = false
    isRefreshing = false
    isLoadingMore = false
    errorMessage = nil
    loadMoreErrorMessage = nil
    selectedFilter = nil
  }

  /// Loads the first Home page for an explicit audience. `reload` does not
  /// clear existing content: a failed refresh remains non-destructive.
  func load(
    audience: HomeAudience,
    sessionID: Int = 0,
    isSessionTransitioning: Bool = false,
    filter: HomeFilter? = nil,
    policy: CatalogLoadPolicy = .cacheFirst
  ) async {
    guard !isSessionTransitioning else {
      clear()
      return
    }

    let context = LoadedContext(audience: audience, sessionID: sessionID, filter: filter)
    if let loadedContext,
      loadedContext.audience != context.audience
        || loadedContext.sessionID != context.sessionID
    {
      clear()
    }

    if policy == .cacheFirst, hasLoadedPage, loadedContext == context {
      guard !isLoading, !isRefreshing, !isLoadingMore,
        continuation != nil,
        let service
      else {
        return
      }
      let request = UUID()
      requestToken = request
      loadMoreErrorMessage = nil
      await loadRemainingPages(request: request, context: context, service: service)
      return
    }
    guard !isLoading, !isRefreshing, !isLoadingMore else {
      return
    }

    guard let service else {
      errorMessage = "Home is unavailable until catalog support is connected."
      hasLoadedPage = false
      return
    }

    let request = UUID()
    requestToken = request
    errorMessage = nil
    loadMoreErrorMessage = nil
    isLoading = !hasLoadedPage
    isRefreshing = policy == .reload

    defer {
      if requestToken == request {
        isLoading = false
        isRefreshing = false
      }
    }

    do {
      let page = try await service.homePage(
        audience: audience,
        filter: filter,
        continuation: nil,
        policy: policy
      )
      guard requestToken == request, !Task.isCancelled else { return }

      // A first page and a successful reload replace the page atomically.
      // Existing content is therefore retained only while a reload is in
      // flight or when it fails.
      selectedFilter = filter
      sections = page.sections.filter { !$0.items.isEmpty }
      filters = deduplicatedFilters(page.filters)
      loadedContext = context
      hasLoadedPage = true
      requestedContinuations.removeAll()
      continuation =
        page.sections.contains(where: { !$0.items.isEmpty })
        ? usableContinuation(page.next, after: nil)
        : nil
      if let continuation {
        requestedContinuations.insert(continuation)
      }
      await loadRemainingPages(request: request, context: context, service: service)
    } catch is CancellationError {
      return
    } catch {
      guard requestToken == request else { return }
      errorMessage = message(for: error)
    }
  }

  /// Fetches every remaining Home page. Empty pages and repeated or empty
  /// tokens exhaust pagination rather than causing a polling loop.
  func loadMore() async {
    guard !isLoading, !isRefreshing, !isLoadingMore,
      continuation != nil,
      let loadedContext,
      let service
    else {
      return
    }

    loadMoreErrorMessage = nil
    let request = UUID()
    requestToken = request
    await loadRemainingPages(request: request, context: loadedContext, service: service)
  }

  func retryLoadMore() async {
    await loadMore()
  }

  private func loadRemainingPages(
    request: UUID,
    context: LoadedContext,
    service: any PaginatedCatalogMusicService
  ) async {
    guard continuation != nil else { return }
    isLoadingMore = true
    defer {
      if requestToken == request {
        isLoadingMore = false
      }
    }

    while let currentContinuation = continuation {
      guard requestToken == request, !Task.isCancelled else { return }
      requestedContinuations.insert(currentContinuation)

      do {
        let page = try await service.homePage(
          audience: context.audience,
          filter: context.filter,
          continuation: currentContinuation,
          policy: .cacheFirst
        )
        guard requestToken == request, !Task.isCancelled else { return }

        guard page.sections.contains(where: { !$0.items.isEmpty }) else {
          continuation = nil
          return
        }
        sections = mergedSections(existing: sections, incoming: page.sections)
        continuation = usableContinuation(page.next, after: currentContinuation)
        if let continuation {
          requestedContinuations.insert(continuation)
        }
      } catch is CancellationError {
        return
      } catch {
        guard requestToken == request else { return }
        loadMoreErrorMessage = message(for: error)
        return
      }
    }
  }

  private func deduplicatedFilters(_ values: [HomeFilter]) -> [HomeFilter] {
    var seen = Set<String>()
    return values.filter { seen.insert($0.id).inserted }
  }

  private func usableContinuation(
    _ candidate: PaginationToken?,
    after previous: PaginationToken?
  ) -> PaginationToken? {
    guard let candidate, !candidate.rawValue.isEmpty,
      candidate != previous,
      !requestedContinuations.contains(candidate)
    else {
      return nil
    }
    return candidate
  }

  private func mergedSections(
    existing: [HomeSection],
    incoming: [HomeSection]
  ) -> [HomeSection] {
    var result = existing
    var indexes: [String: Int] = [:]
    for (index, section) in result.enumerated() where indexes[section.id] == nil {
      indexes[section.id] = index
    }

    for section in incoming {
      guard !section.items.isEmpty else { continue }
      if let index = indexes[section.id] {
        let existingItems = result[index].items
        let existingIDs = Set(existingItems.map(\.id))
        let appended = section.items.filter { !existingIDs.contains($0.id) }
        guard !appended.isEmpty else { continue }
        result[index] = HomeSection(
          id: result[index].id,
          title: result[index].title,
          subtitle: result[index].subtitle ?? section.subtitle,
          items: existingItems + appended
        )
      } else {
        indexes[section.id] = result.count
        result.append(section)
      }
    }
    return result
  }

  private func message(for error: Error) -> String {
    (error as? LocalizedError)?.errorDescription ?? "Could not load Home right now."
  }
}