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

geesawra.industries/hydraulophone

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

0
0
main
235 lines · 8.4 KB Raw History
import CryptoKit
import Foundation
import HydraulophoneCore

enum TrackDownloadState: String, Codable, Sendable {
  case queued, downloading, paused, complete, failed
}

struct TrackDownload: Codable, Identifiable, Sendable {
  var id: String { song.id }
  var song: Song
  var quality: AudioQualityPreference
  var completedQuality: AudioQualityPreference?
  var state: TrackDownloadState = .queued
  var progress: Double = 0
  var message: String?
  var artworkFile: String?
  var addedAt = Date()
  var availableQuality: AudioQualityPreference? {
    completedQuality ?? (state == .complete ? quality : nil)
  }
  var isAvailable: Bool { availableQuality != nil }
}

struct DownloadedAlbum: Codable, Identifiable, Sendable {
  var id: String { album.id }
  let album: Album
  let trackIDs: [String]
}

struct DownloadCatalog: Codable, Sendable {
  var schema = 1
  var tracks: [TrackDownload] = []
  var albums: [DownloadedAlbum] = []
}

/// Durable user-requested downloads have a separate lifetime from the LRU.
/// Disk operations and image transfers never run on the UI actor.
actor DownloadCatalogStore {
  nonisolated let directory: URL
  nonisolated let artworkCacheDirectory: URL
  private var revision: UInt64 = 0
  private var clearGeneration: UInt64 = 0
  private let session: URLSession
  private let imageDelegate = DownloadArtworkDelegate()

  init(directory: URL, artworkCacheDirectory: URL? = nil) {
    self.directory = directory
    self.artworkCacheDirectory =
      artworkCacheDirectory
      ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
      .appendingPathComponent("HydraulophoneArtwork/v1", isDirectory: true)
    let configuration = URLSessionConfiguration.ephemeral
    configuration.httpCookieStorage = nil
    configuration.httpShouldSetCookies = false
    configuration.urlCredentialStorage = nil
    configuration.urlCache = nil
    configuration.timeoutIntervalForRequest = 15
    configuration.timeoutIntervalForResource = 30
    session = URLSession(configuration: configuration, delegate: imageDelegate, delegateQueue: nil)
  }

  deinit { session.invalidateAndCancel() }

  func load() -> DownloadCatalog {
    let url = directory.appendingPathComponent("catalog.json")
    guard (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? Int.max <= 8 * 1024 * 1024,
      let data = try? Data(contentsOf: url),
      data.count <= 8 * 1024 * 1024,
      let catalog = try? JSONDecoder().decode(DownloadCatalog.self, from: data), catalog.schema == 1
    else { return DownloadCatalog() }
    return catalog
  }

  func save(_ catalog: DownloadCatalog, revision: UInt64) throws {
    guard revision >= self.revision else { return }
    self.revision = revision
    try prepareDirectory()
    try JSONEncoder().encode(catalog).write(
      to: directory.appendingPathComponent("catalog.json"),
      options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
  }

  func clear(revision: UInt64) throws {
    clearGeneration &+= 1
    self.revision = revision
    session.getAllTasks { tasks in for task in tasks { task.cancel() } }
    if FileManager.default.fileExists(atPath: directory.path) {
      try FileManager.default.removeItem(at: directory)
    }
  }

  func cancelArtworkTransfers() {
    session.getAllTasks { tasks in
      for task in tasks { task.cancel() }
    }
  }

  func saveArtwork(from url: URL?, trackID: String) async -> String? {
    await saveArtwork(
      from: url, trackID: trackID,
      in: directory.appendingPathComponent("Artwork", isDirectory: true))
  }

  func saveCachedArtwork(from url: URL?, trackID: String) async -> URL? {
    guard let destination = artworkCacheFileURL(trackID: trackID) else { return nil }
    if FileManager.default.fileExists(atPath: destination.path) { return destination }
    guard
      await saveArtwork(
        from: url, trackID: trackID, in: artworkCacheDirectory
      ) != nil
    else { return nil }
    return destination
  }

  func preserveArtworkInCache(named name: String?, trackID: String) {
    guard let name, let source = artworkURL(name),
      let destination = artworkCacheFileURL(trackID: trackID),
      !FileManager.default.fileExists(atPath: destination.path),
      let data = try? Data(contentsOf: source), !data.isEmpty,
      data.count < 2 * 1024 * 1024
    else { return }
    do {
      try FileManager.default.createDirectory(
        at: artworkCacheDirectory, withIntermediateDirectories: true)
      try data.write(
        to: destination,
        options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
    } catch {
      // Artwork is an optional cache and must not affect a completed download.
    }
  }

  nonisolated func cachedArtworkURL(trackID: String) -> URL? {
    guard let url = artworkCacheFileURL(trackID: trackID),
      FileManager.default.fileExists(atPath: url.path)
    else { return nil }
    return url
  }

  private nonisolated func artworkCacheFileURL(trackID: String) -> URL? {
    guard !trackID.isEmpty else { return nil }
    let name = Self.artworkName(trackID: trackID)
    return artworkCacheDirectory.appendingPathComponent(name)
  }

  private nonisolated static func artworkName(trackID: String) -> String {
    SHA256.hash(data: Data(trackID.utf8)).map { String(format: "%02x", $0) }.joined() + ".image"
  }

  private func saveArtwork(from url: URL?, trackID: String, in artworkDirectory: URL) async
    -> String?
  {
    guard let url else { return nil }
    let expectedGeneration = clearGeneration
    let name = Self.artworkName(trackID: trackID)
    let destination = artworkDirectory.appendingPathComponent(name)
    if FileManager.default.fileExists(atPath: destination.path) { return name }
    for artworkURL in ArtworkURL.nowPlayingCandidates(from: url) {
      guard DownloadArtworkDelegate.allowed(artworkURL) else { continue }
      do {
        let (bytes, response) = try await session.bytes(from: artworkURL)
        defer { bytes.task.cancel() }
        guard let response = response as? HTTPURLResponse,
          response.statusCode == 200,
          response.url.map(DownloadArtworkDelegate.allowed) == true,
          response.mimeType?.hasPrefix("image/") == true,
          response.expectedContentLength <= 2 * 1024 * 1024
        else { continue }
        var data = Data()
        for try await byte in bytes {
          guard data.count < 2 * 1024 * 1024 else { break }
          if data.count.isMultiple(of: 16_384) { try Task.checkCancellation() }
          data.append(byte)
        }
        try Task.checkCancellation()
        guard expectedGeneration == clearGeneration, !data.isEmpty,
          data.count < 2 * 1024 * 1024
        else { continue }
        try prepareDirectory()
        try FileManager.default.createDirectory(
          at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
        try data.write(
          to: destination,
          options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
        return name
      } catch is CancellationError {
        return nil
      } catch {
        continue
      }
    }
    return nil
  }

  nonisolated func artworkURL(_ name: String?) -> URL? {
    guard let name, name.count == 70, name.hasSuffix(".image"),
      name.dropLast(6).allSatisfy({ $0.isHexDigit })
    else { return nil }
    return directory.appendingPathComponent("Artwork", isDirectory: true).appendingPathComponent(
      name)
  }

  func removeArtwork(_ name: String?) {
    guard let url = artworkURL(name) else { return }
    try? FileManager.default.removeItem(at: url)
  }

  private func prepareDirectory() throws {
    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
    var root = directory
    var values = URLResourceValues()
    values.isExcludedFromBackup = true
    try root.setResourceValues(values)
  }
}

private final class DownloadArtworkDelegate: NSObject, URLSessionTaskDelegate {
  static func allowed(_ url: URL) -> Bool {
    guard url.scheme == "https", url.user == nil, url.password == nil, url.port == nil,
      let host = url.host?.lowercased()
    else { return false }
    return ["ytimg.com", "googleusercontent.com", "ggpht.com"].contains {
      host == $0 || host.hasSuffix("." + $0)
    }
  }

  func urlSession(
    _ session: URLSession, task: URLSessionTask,
    willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest,
    completionHandler: @escaping (URLRequest?) -> Void
  ) {
    completionHandler(request.url.map(Self.allowed) == true ? request : nil)
  }
}