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

geesawra.industries/hydraulophone

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

0
0
main
443 lines · 12.9 KB Raw History
import HydraulophoneCore
import SwiftUI

enum HydraulophoneAccessibilityID {
  static let searchField = "search.field"
  static let searchSubmit = "search.submit"
  static let playlistCollection = "library.playlist.collection"
  static let miniPlayer = "mini.player"
  static let playbackPlayPause = "playback.playPause"
  static let playbackNext = "playback.next"
  static let playbackPrevious = "playback.previous"
  static let playbackSeek = "playback.seek"

  static func playlist(_ id: String) -> String {
    "library.playlist.\(id)"
  }

  static func track(_ id: String) -> String {
    "playlist.track.\(id)"
  }

  static func searchSong(_ id: String) -> String {
    "search.song.\(id)"
  }

  static func searchPlaylist(_ id: String) -> String {
    "search.playlist.\(id)"
  }
}

enum ArtworkURL {
  private static let maximumRequestedPixelSize = 2_048

  /// Lock Screen and external Now Playing surfaces can render larger art than
  /// list cells. Keep this on the same validated, host-specific resize path.
  static func forNowPlaying(_ url: URL) -> URL {
    guard !url.isFileURL else { return url }
    return resized(url, forPoints: 1_024, scale: 2)
  }

  static func nowPlayingCandidates(from url: URL) -> [URL] {
    let preferred = forNowPlaying(url)
    return preferred == url ? [url] : [preferred, url]
  }

  static func resized(_ url: URL, forPoints points: CGFloat, scale: CGFloat) -> URL {
    guard points.isFinite, scale.isFinite, points > 0, scale > 0 else {
      return url
    }
    let pixelSize = Int(
      min(CGFloat(maximumRequestedPixelSize), max(1, ceil(points * scale)))
    )
    guard
      let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
      components.scheme?.lowercased() == "https",
      components.port == nil,
      let host = components.host?.lowercased()
    else {
      return url
    }

    if isGoogleArtworkHost(host) {
      return resizedGoogleArtwork(
        url: url,
        components: components,
        pixelSize: pixelSize
      )
    }
    guard host == "i.ytimg.com" else {
      return url
    }
    return resizedYTImgArtwork(url: url, components: components, pixelSize: pixelSize)
  }

  private static func isGoogleArtworkHost(_ host: String) -> Bool {
    host == "googleusercontent.com"
      || host.hasSuffix(".googleusercontent.com")
      || host == "ggpht.com"
      || host.hasSuffix(".ggpht.com")
  }

  private static func resizedGoogleArtwork(
    url: URL,
    components: URLComponents,
    pixelSize: Int
  ) -> URL {
    var components = components
    var path = components.percentEncodedPath

    // This is the size-segment behavior used by AuraMusic's pinned
    // YouTubeUtils.String.resize helper, restricted to a validated host and
    // path. Preserve any quality suffix already supplied by the CDN.
    let dimensions = #"w\d+-h\d+"#
    if let range = path.range(of: dimensions, options: .regularExpression) {
      path.replaceSubrange(range, with: "w\(pixelSize)-h\(pixelSize)")
      components.percentEncodedPath = path
      return components.url ?? url
    }

    if let range = path.range(
      of: #"=[wsh]\d+"#,
      options: .regularExpression
    ) {
      path = String(path[..<range.lowerBound])
    }
    components.percentEncodedPath = path + "=w\(pixelSize)-h\(pixelSize)-p-l90-rj"
    return components.url ?? url
  }

  private static func resizedYTImgArtwork(
    url: URL,
    components: URLComponents,
    pixelSize: Int
  ) -> URL {
    let path = components.percentEncodedPath
    let replacements: [String: String]
    if pixelSize > 480 {
      replacements = [
        "hqdefault.jpg": "maxresdefault.jpg",
        "mqdefault.jpg": "maxresdefault.jpg",
        "sddefault.jpg": "maxresdefault.jpg",
        "default.jpg": "maxresdefault.jpg",
      ]
    } else if pixelSize > 320 {
      replacements = [
        "mqdefault.jpg": "hqdefault.jpg",
        "default.jpg": "hqdefault.jpg",
      ]
    } else {
      return url
    }

    guard let filename = path.split(separator: "/").last,
      let replacement = replacements[String(filename)]
    else {
      return url
    }
    var components = components
    components.percentEncodedPath =
      String(path.dropLast(filename.count)) + replacement
    return components.url ?? url
  }
}

struct ArtworkView: View, Equatable {
  let url: URL?
  var size: CGFloat = 56
  var cornerRadius: CGFloat = 10
  /// Keep the loaded image stable while its displayed frame animates.
  var imageRequestSize: CGFloat?
  @Environment(\.displayScale) private var displayScale
  @Environment(\.offlineOnly) private var offlineOnly
  @State private var localArtwork: UIImage?

  static func == (lhs: Self, rhs: Self) -> Bool {
    lhs.url == rhs.url && lhs.size == rhs.size && lhs.cornerRadius == rhs.cornerRadius
      && lhs.imageRequestSize == rhs.imageRequestSize
  }

  var body: some View {
    Group {
      if url?.isFileURL == true {
        if let localArtwork {
          Image(uiImage: localArtwork).resizable().scaledToFill()
        } else {
          placeholder
        }
      } else {
        remoteArtwork
      }
    }
    .task(id: url) {
      localArtwork = nil
      if let url, url.isFileURL {
        let image = await LocalArtworkImageCache.image(at: url)
        if !Task.isCancelled { localArtwork = image }
      }
    }
    .frame(width: size, height: size)
    .clipShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
    .accessibilityHidden(true)
  }

  private var remoteArtwork: some View {
    AsyncImage(url: resolvedURL) { phase in
      switch phase {
      case .success(let image):
        image
          .resizable()
          .scaledToFill()
      case .empty:
        if resolvedURL != nil {
          placeholder
            .overlay {
              ProgressView()
                .tint(.secondary)
            }
        } else {
          placeholder
        }
      case .failure:
        if resolvedURL != url {
          originalArtwork
        } else {
          placeholder
        }
      @unknown default:
        placeholder
      }
    }
    .frame(width: size, height: size)
    .clipShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
    .accessibilityHidden(true)
  }

  private var resolvedURL: URL? {
    guard let url = safeOriginalURL else { return nil }
    return ArtworkURL.resized(url, forPoints: imageRequestSize ?? size, scale: displayScale)
  }

  private var safeOriginalURL: URL? {
    guard !offlineOnly, let url, url.scheme?.lowercased() == "https",
      url.host != nil, url.user == nil, url.password == nil
    else {
      return nil
    }
    return url
  }

  private var originalArtwork: some View {
    AsyncImage(url: safeOriginalURL) { phase in
      if case .success(let image) = phase {
        image.resizable().scaledToFill()
      } else {
        placeholder
      }
    }
  }

  private var placeholder: some View {
    RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
      .fill(
        LinearGradient(
          colors: [
            HydraulophoneTheme.accent.opacity(0.22),
            Color.secondary.opacity(0.12),
          ],
          startPoint: .topLeading,
          endPoint: .bottomTrailing
        )
      )
      .overlay {
        Image(systemName: "music.note")
          .font(.title3)
          .foregroundStyle(HydraulophoneTheme.accent)
      }
  }
}

struct SongRow: View {
  @State private var playbackFeedback = 0
  @EnvironmentObject private var model: AppModel
  let song: Song
  let accessibilityIdentifier: String
  let trackNumber: Int?
  let showsDetails: Bool
  let showsArtwork: Bool
  let play: () -> Void
  let playNext: (() -> Void)?
  let addToQueue: (() -> Void)?

  init(
    song: Song,
    accessibilityIdentifier: String? = nil,
    trackNumber: Int? = nil,
    showsDetails: Bool = true,
    showsArtwork: Bool = true,
    playNext: (() -> Void)? = nil,
    addToQueue: (() -> Void)? = nil,
    play: @escaping () -> Void
  ) {
    self.song = song
    self.accessibilityIdentifier =
      accessibilityIdentifier ?? HydraulophoneAccessibilityID.track(song.id)
    self.trackNumber = trackNumber
    self.showsDetails = showsDetails
    self.showsArtwork = showsArtwork
    self.playNext = playNext
    self.addToQueue = addToQueue
    self.play = play
  }

  var body: some View {
    HStack(spacing: 12) {
      if let trackNumber {
        Text("\(trackNumber)").font(.caption.monospacedDigit()).foregroundStyle(.secondary)
          .frame(width: 24, alignment: .trailing).accessibilityHidden(true)
      }
      if showsArtwork {
        Button(action: playWithFeedback) { ArtworkView(url: song.thumbnailURL) }
          .buttonStyle(.plain).accessibilityLabel("Play \(song.title)")
          .songActions(song, playNext: playNext, addToQueue: addToQueue)
      }
      VStack(alignment: .leading, spacing: 0) {
        Button(action: playWithFeedback) {
          HStack(spacing: 8) {
            Text(song.title).font(.body.weight(.medium)).foregroundStyle(.primary).lineLimit(2)
            Spacer(minLength: 8)
            if let duration = song.durationText {
              Text(duration).font(.caption).foregroundStyle(.secondary)
            }
            Image(systemName: "play.circle.fill").font(.title2)
              .foregroundStyle(HydraulophoneTheme.accent).accessibilityHidden(true)
          }
          .frame(minHeight: 44)
          .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
        .accessibilityIdentifier(accessibilityIdentifier)
        .accessibilityLabel(playbackAccessibilityLabel)
        .accessibilityHint("Starts playback")
        .songActions(song, playNext: playNext, addToQueue: addToQueue)
        if showsDetails {
          VStack(alignment: .leading, spacing: 2) {
            ArtistNameLinks(
              artists: song.artistReferences ?? [], fallback: song.artist, compact: true)
            if let album = song.album, !album.isEmpty {
              AlbumNameLink(album: song.navigationAlbum, fallback: album, compact: true)
            }
          }
          .font(.subheadline)
          .lineLimit(1)
        }
      }
    }
    .padding(.vertical, 7)
    .padding(.horizontal, 4)
    .contentShape(Rectangle())
    .sensoryFeedback(.impact(weight: .light), trigger: playbackFeedback)
  }

  private func playWithFeedback() {
    playbackFeedback += 1
    play()
  }

  private var playbackAccessibilityLabel: String {
    let trackPrefix = trackNumber.map { "Track \($0). " } ?? ""
    let artistSuffix = showsDetails ? " by \(song.artist)" : ""
    return "\(trackPrefix)Play \(song.title)\(artistSuffix)"
  }
}

struct PlaylistRow: View {
  let playlist: Playlist

  init(playlist: Playlist) {
    self.playlist = playlist
  }

  var body: some View {
    HStack(spacing: 12) {
      ArtworkView(url: playlist.thumbnailURL)
      VStack(alignment: .leading, spacing: 3) {
        Text(playlist.title)
          .font(.body.weight(.medium))
          .foregroundStyle(.primary)
          .lineLimit(2)
        if let subtitle = playlist.subtitle, !subtitle.isEmpty {
          Text(subtitle)
            .font(.subheadline)
            .foregroundStyle(.secondary)
            .lineLimit(1)
        }
      }
      Spacer(minLength: 8)
      Image(systemName: "chevron.right")
        .font(.subheadline.weight(.semibold))
        .foregroundStyle(.secondary)
        .accessibilityHidden(true)
    }
    .contentShape(Rectangle())
    .padding(.vertical, 7)
    .padding(.horizontal, 4)
    .accessibilityIdentifier(HydraulophoneAccessibilityID.playlist(playlist.id))
    .accessibilityLabel("Open playlist \(playlist.title)")
    .accessibilityHint("Shows the songs in this playlist")
  }
}

struct PlaylistTile: View {
  let playlist: Playlist

  var body: some View {
    VStack(alignment: .leading, spacing: 8) {
      ArtworkView(
        url: playlist.thumbnailURL,
        size: 180,
        cornerRadius: 12
      )
      .frame(maxWidth: .infinity)
      .aspectRatio(1, contentMode: .fit)
      Text(playlist.title)
        .font(.body.weight(.semibold))
        .foregroundStyle(.primary)
        .lineLimit(2)
        .multilineTextAlignment(.leading)
      if let subtitle = playlist.subtitle, !subtitle.isEmpty {
        Text(subtitle)
          .font(.caption)
          .foregroundStyle(.secondary)
          .lineLimit(1)
      }
    }
    .frame(maxWidth: .infinity, alignment: .leading)
    .contentShape(Rectangle())
    .accessibilityIdentifier(HydraulophoneAccessibilityID.playlist(playlist.id))
    .accessibilityLabel("Open playlist \(playlist.title)")
    .accessibilityHint("Shows the songs in this playlist")
  }
}

struct HydraulophoneErrorState: View {
  let title: String
  let message: String
  let retry: (() -> Void)?

  var body: some View {
    ContentUnavailableView {
      Label(title, systemImage: "wifi.exclamationmark")
    } description: {
      Text(message)
    } actions: {
      if let retry {
        Button("Try Again", action: retry)
          .buttonStyle(.borderedProminent)
          .tint(HydraulophoneTheme.accent)
      }
    }
    .multilineTextAlignment(.center)
    .padding()
  }
}