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

geesawra.industries/hydraulophone

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

0
0
main
330 lines · 11.6 KB Raw History
import HydraulophoneCore
import SwiftUI

struct DownloadsView: View {
  @EnvironmentObject private var model: AppModel
  @ObservedObject var downloads: TrackDownloadManager
  var offlineOnly = false
  var title = "Downloads"
  @State private var query = ""

  private var visibleTracks: [TrackDownload] {
    downloads.tracks.filter { item in
      (!offlineOnly || item.isAvailable)
        && (query.isEmpty
          || "\(item.song.title) \(item.song.artist) \(item.song.album ?? "")"
            .localizedStandardContains(query))
    }
  }

  var body: some View {
    List {
      if downloads.isRestoring {
        ProgressView("Loading downloads…")
      } else if downloads.tracks.isEmpty {
        ContentUnavailableView(
          "No downloads yet", systemImage: "arrow.down.circle",
          description: Text(
            offlineOnly
              ? "Turn off Offline Only in Settings to download songs or albums."
              : "Download a song from its menu, or an album from its page.")
        )
        .listRowBackground(Color.clear)
      } else {
        if offlineOnly {
          Label("Offline Only", systemImage: "wifi.slash")
            .foregroundStyle(.secondary)
        }
        if query.isEmpty, !downloads.albums.isEmpty {
          Section("Albums") {
            ForEach(
              downloads.albums.filter { album in
                !offlineOnly
                  || album.trackIDs.contains { id in
                    downloads.tracks.contains { $0.id == id && $0.isAvailable }
                  }
              }
            ) { album in
              NavigationLink {
                DownloadedAlbumView(album: album, downloads: downloads)
              } label: {
                let items = downloads.tracks.filter { album.trackIDs.contains($0.id) }
                HStack(spacing: 12) {
                  ArtworkView(url: items.first.map(downloads.localSong)?.thumbnailURL)
                  VStack(alignment: .leading, spacing: 4) {
                    Text(album.album.title).font(.headline)
                    Text(
                      "\(items.filter { $0.isAvailable }.count) of \(album.trackIDs.count) downloaded"
                    )
                    .font(.subheadline).foregroundStyle(.secondary)
                  }
                }
              }
            }
          }
        }
        Section("Songs") {
          ForEach(visibleTracks) { item in
            DownloadTrackRow(item: item, downloads: downloads) {
              let songs = visibleTracks.filter { $0.isAvailable }.map(downloads.localSong)
              guard let index = songs.firstIndex(where: { $0.id == item.id }) else { return }
              model.playback.setQueue(songs, startAt: index)
            }
          }
          if visibleTracks.isEmpty {
            if query.isEmpty {
              ContentUnavailableView(
                "No completed downloads", systemImage: "arrow.down.circle",
                description: Text("Turn off Offline Only to finish your queued downloads."))
            } else {
              ContentUnavailableView.search(text: query)
            }
          }
        }
        Section {
          LabeledContent(
            "Downloaded audio",
            value: ByteCountFormatter.string(
              fromByteCount: downloads.storedBytes, countStyle: .file))
          if !offlineOnly {
            Text("Downloads are kept separately from the track cache.")
              .font(.footnote).foregroundStyle(.secondary)
          }
        }
      }
    }
    .navigationTitle(title)
    .searchable(text: $query, prompt: "Songs, artists, or albums")
    .task { await downloads.refreshStorageUsage() }
    .toolbar {
      if !offlineOnly, !downloads.tracks.isEmpty {
        ToolbarItem(placement: .topBarTrailing) {
          Menu {
            Button("Resume Downloads", systemImage: "play") { downloads.resumeAll() }
              .disabled(!downloads.networkAllowed)
            Button("Pause Downloads", systemImage: "pause") { downloads.pauseAll() }
          } label: {
            Label("Download actions", systemImage: "ellipsis.circle")
          }
        }
      }
    }
    .alert(
      "Downloads",
      isPresented: Binding(
        get: { downloads.message != nil },
        set: { if !$0 { downloads.message = nil } })
    ) {
      Button("OK") { downloads.message = nil }
    } message: {
      Text(downloads.message ?? "")
    }
  }
}

private struct DownloadTrackRow: View {
  let item: TrackDownload
  @ObservedObject var downloads: TrackDownloadManager
  var trackNumber: Int?
  var showsArtist = true
  var showsArtwork = true
  let play: () -> Void
  @State private var confirmingRemoval = false

  var body: some View {
    HStack(spacing: 12) {
      if let trackNumber {
        Text("\(trackNumber)").font(.caption).monospacedDigit()
          .foregroundStyle(.secondary).frame(minWidth: 18)
          .accessibilityHidden(true)
      }
      Button(action: play) {
        HStack(spacing: 12) {
          if showsArtwork {
            ArtworkView(url: downloads.localSong(item).thumbnailURL)
          }
          VStack(alignment: .leading, spacing: 4) {
            Text(item.song.title).font(.body.weight(.medium)).foregroundStyle(.primary)
              .lineLimit(2)
            if showsArtist {
              Text(item.song.artist).font(.subheadline).foregroundStyle(.secondary).lineLimit(1)
            }
            if item.state == .downloading {
              ProgressView(value: item.progress)
                .accessibilityLabel("Download progress")
                .accessibilityValue("\(Int(item.progress * 100)) percent")
            }
            if item.state != .complete {
              Text(status).font(.caption).foregroundStyle(.secondary)
            }
          }
          Spacer(minLength: 0)
        }
        .frame(minHeight: 44)
        .contentShape(Rectangle())
      }
      .buttonStyle(.plain)
      .disabled(!item.isAvailable)
      .accessibilityLabel("Play \(item.song.title) by \(item.song.artist)")
      Menu {
        if item.isAvailable {
          Button("Play", systemImage: "play", action: play)
        }
        if item.state == .downloading || item.state == .queued {
          Button("Pause Download", systemImage: "pause") { downloads.pause(item.id) }
        } else if item.state != .complete {
          Button(
            item.state == .failed ? "Retry Download" : "Resume Download",
            systemImage: "arrow.down.circle"
          ) { downloads.resume(item.id) }
          .disabled(!downloads.networkAllowed)
        }
        Button("Remove Download", systemImage: "trash", role: .destructive) {
          confirmingRemoval = true
        }
      } label: {
        Image(systemName: item.state == .complete ? "checkmark.circle.fill" : "ellipsis.circle")
          .frame(minWidth: 44, minHeight: 44)
      }
      .accessibilityLabel("Download options for \(item.song.title)")
    }
    .padding(.vertical, 4)
    .songActions(downloads.localSong(item))
    .confirmationDialog(
      "Remove \(item.song.title) from this device?",
      isPresented: $confirmingRemoval, titleVisibility: .visible
    ) {
      Button("Remove Download", role: .destructive) { Task { await downloads.remove(item.id) } }
    }
  }

  private var status: String {
    switch item.state {
    case .complete: "Downloaded"
    case .downloading: "\(Int(item.progress * 100))% downloaded"
    case .queued: downloads.networkAllowed ? "Queued" : "Waiting to go online"
    case .paused: "Paused"
    case .failed: item.message ?? "Download interrupted"
    }
  }
}

struct DownloadedAlbumView: View {
  let album: DownloadedAlbum
  @ObservedObject var downloads: TrackDownloadManager
  @EnvironmentObject private var model: AppModel
  @State private var confirmingRemoval = false

  private var items: [TrackDownload] {
    album.trackIDs.compactMap { id in downloads.tracks.first { $0.id == id } }
  }
  private var songs: [Song] { items.filter { $0.isAvailable }.map(downloads.localSong) }

  private var headerAlbum: Album {
    let source = album.album
    return Album(
      browseID: source.browseID, playlistID: source.playlistID,
      title: source.title, subtitle: source.subtitle,
      thumbnailURL: songs.first?.thumbnailURL ?? source.thumbnailURL,
      artistReferences: source.artistReferences, params: source.params)
  }

  var body: some View {
    List {
      Section {
        AlbumDetailHeader(album: headerAlbum)
        MusicPlaybackActions(
          isEnabled: !songs.isEmpty,
          play: { model.playback.setQueue(songs, startAt: 0, shuffle: false) },
          shuffle: { model.playback.setQueue(songs, startAt: 0, shuffle: true) })
        Text("\(songs.count) of \(album.trackIDs.count) songs downloaded")
          .font(.subheadline).foregroundStyle(.secondary)
      }
      Section {
        ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
          DownloadTrackRow(
            item: item, downloads: downloads, trackNumber: index + 1,
            showsArtist: false, showsArtwork: false
          ) {
            if let index = songs.firstIndex(where: { $0.id == item.id }) {
              model.playback.setQueue(songs, startAt: index)
            }
          }
        }
      }
    }
    .navigationTitle(album.album.title)
    .navigationBarTitleDisplayMode(.inline)
    .toolbar {
      Button("Remove Album", systemImage: "trash") { confirmingRemoval = true }
    }
    .confirmationDialog(
      "Remove this album’s downloads?", isPresented: $confirmingRemoval,
      titleVisibility: .visible
    ) {
      Button("Remove Downloads", role: .destructive) {
        Task { await downloads.remove(album: album) }
      }
    }
  }
}

struct DownloadSongAction: View {
  let song: Song
  @ObservedObject var downloads: TrackDownloadManager
  let quality: AudioQualityPreference
  var body: some View {
    if let item = downloads.item(for: song), item.state == .complete {
      if item.quality == .standard, quality == .high {
        Button("Download in High Quality", systemImage: "arrow.down.circle") {
          downloads.enqueue(song, quality: quality)
        }.disabled(!downloads.networkAllowed)
      } else {
        Label("Downloaded", systemImage: "checkmark.circle.fill")
      }
    } else if let item = downloads.item(for: song),
      item.state == .queued || item.state == .downloading
    {
      Button("Pause Download", systemImage: "pause") { downloads.pause(item.id) }
    } else {
      Button("Download", systemImage: "arrow.down.circle") {
        downloads.enqueue(song, quality: quality)
      }
      .disabled(!downloads.networkAllowed || downloads.isRestoring)
    }
  }
}

struct AlbumDownloadButton: View {
  let album: Album
  @ObservedObject var downloads: TrackDownloadManager
  let quality: AudioQualityPreference

  private var isComplete: Bool {
    guard let saved = downloads.albums.first(where: { $0.id == album.id }), !saved.trackIDs.isEmpty
    else { return false }
    return saved.trackIDs.allSatisfy { id in
      downloads.tracks.contains { item in
        item.id == id && item.isAvailable
          && (item.availableQuality == .high || quality == .standard)
      }
    }
  }

  var body: some View {
    Button {
      downloads.enqueue(album: album, quality: quality)
    } label: {
      if downloads.isLoadingAlbum {
        ProgressView().accessibilityLabel("Preparing album download")
      } else {
        Label(
          isComplete ? "Album downloaded" : "Download Album",
          systemImage: isComplete ? "checkmark.circle.fill" : "arrow.down.circle")
      }
    }
    .frame(minWidth: 44, minHeight: 44)
    .disabled(
      isComplete || !downloads.networkAllowed || downloads.isRestoring || downloads.isLoadingAlbum)
  }
}