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

geesawra.industries/hydraulophone

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

0
0
main
249 lines · 9.0 KB Raw History
import Foundation
import Testing

@testable import HydraulophoneCore

struct BetterLyricsProviderTests {
  @Test
  func parsesWordRunsWithoutLosingSpacingOrTranslations() throws {
    let ttml = """
      <tt xmlns="http://www.w3.org/ns/ttml" xmlns:ttm="http://www.w3.org/ns/ttml#metadata">
        <body><div><p begin="00:10.000" end="00:12.000"><span begin="10s" end="10.5s">Hello </span><span begin="10.6s" end="11s">world</span><span ttm:role="x-translation">Bonjour monde</span></p></div></body>
      </tt>
      """
    let lines = try #require(TTMLLyricsParser.parse(ttml))

    #expect(lines.count == 1)
    #expect(lines[0].text == "Hello world")
    #expect(lines[0].startTime == 10)
    #expect(lines[0].endTime == 12)
    #expect(lines[0].words.map(\.text) == ["Hello ", "world"])
    #expect(lines[0].words.map(\.text).joined() == lines[0].text)
    #expect(lines[0].words.map(\.startTime) == [10, 10.6])
    #expect(lines[0].words.map(\.endTime) == [10.5, 11])
  }

  @Test
  func supportsNamespacedTimingUnitsOffsetsAndInferredLineBegin() throws {
    let ttml = """
      <tt xmlns="http://www.w3.org/ns/ttml" xmlns:ttp="http://www.w3.org/ns/ttml#parameter">
        <head><metadata><audio lyricOffset="1.5"/></metadata></head>
        <body><div>
          <p ttp:begin="2000ms" ttp:end="4s">Line only</p>
          <p><span ttp:begin="00:00:05.250" ttp:end="00:00:05.750">Next</span></p>
          <p begin="0.1m" end="0.2m">Minutes</p>
        </div></body>
      </tt>
      """
    let lines = try #require(TTMLLyricsParser.parse(ttml))

    #expect(lines.map(\.text) == ["Line only", "Next", "Minutes"])
    #expect(lines.map(\.startTime) == [3.5, 6.75, 7.5])
    #expect(lines.map(\.endTime) == [5.5, nil, 13.5])
    #expect(lines[0].words.isEmpty)
    #expect(lines[1].words.map(\.text) == ["Next"])
  }

  @Test
  func incompleteWordTimingFallsBackToTimedLine() throws {
    let ttml = """
      <tt xmlns="http://www.w3.org/ns/ttml"><body><div>
        <p begin="1s" end="3s"><span begin="1s" end="1.5s">First </span><span begin="bad" end="2s">second</span></p>
      </div></body></tt>
      """
    let lines = try #require(TTMLLyricsParser.parse(ttml))

    #expect(lines.count == 1)
    #expect(lines[0].text == "First second")
    #expect(lines[0].startTime == 1)
    #expect(lines[0].words.isEmpty)
  }

  @Test
  func rejectsDTDAndMalformedXML() {
    #expect(
      TTMLLyricsParser.parse(
        """
        <!DOCTYPE tt [<!ENTITY secret SYSTEM "file:///etc/passwd">]>
        <tt><body><p begin="1s">&secret;</p></body></tt>
        """) == nil)
    #expect(TTMLLyricsParser.parse("<tt><body><p begin=\"1s\">Unclosed") == nil)
    #expect(
      TTMLLyricsParser.parse(
        "<other><tt><body><p begin=\"1s\">Wrong root</p></body></tt></other>") == nil)
  }

  @Test
  func providerUsesExactParametersAndNoCredentials() async throws {
    let title = "Song & Rain"
    let ttml = "<tt><body><p begin=\"1s\" end=\"2s\">Line</p></body></tt>"
    BetterProtocol.register(title: title, status: 200, body: payload(ttml))
    let provider = makeProvider()
    let song = Song(
      id: "video-id-not-sent", title: title, artist: "One Artist", album: "The Album",
      durationText: "3:07")

    let result = try await provider.lyrics(for: song)
    let request = try #require(BetterProtocol.lastRequest(for: title))
    let url = try #require(request.url)
    let items = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems)
    let query = Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") })

    #expect(url.scheme == "https")
    #expect(url.host == "api.betterlyrics.org")
    #expect(url.path == "/getLyrics")
    #expect(query == ["s": title, "a": "One Artist", "d": "187", "al": "The Album"])
    #expect(!url.absoluteString.contains(song.id))
    #expect(request.httpMethod == "GET")
    #expect(request.timeoutInterval == 8)
    #expect(request.httpShouldHandleCookies == false)
    #expect(request.value(forHTTPHeaderField: "Authorization") == nil)
    #expect(request.value(forHTTPHeaderField: "Cookie") == nil)
    #expect(request.value(forHTTPHeaderField: "X-API-Key") == nil)
    #expect(result?.isSynchronized == true)
    #expect(result?.source == "BetterLyrics")
    #expect(result?.lines.first?.text == "Line")
  }

  @Test
  func missingAndUncachedLyricsAreAbsenceWhileServerFailuresStayTyped() async throws {
    let absent = "Absent Better fixture"
    let gated = "Gated Better fixture"
    let failed = "Failed Better fixture"
    BetterProtocol.register(title: absent, status: 404, body: Data())
    BetterProtocol.register(title: gated, status: 401, body: Data())
    BetterProtocol.register(title: failed, status: 503, body: Data())
    let provider = makeProvider()

    #expect(try await provider.lyrics(for: song(absent)) == nil)
    #expect(try await provider.lyrics(for: song(gated)) == nil)
    await #expect(throws: BetterLyricsError.httpStatus(503)) {
      try await provider.lyrics(for: song(failed))
    }
  }

  @Test
  func malformedResponseIsTypedAndPrecancelledRequestSendsNothing() async throws {
    let malformed = "Malformed Better fixture"
    BetterProtocol.register(title: malformed, status: 200, body: Data("{}".utf8))
    let provider = makeProvider()
    await #expect(throws: BetterLyricsError.invalidResponse) {
      try await provider.lyrics(for: song(malformed))
    }

    let cancelled = "Cancelled Better fixture"
    BetterProtocol.register(title: cancelled, status: 404, body: Data())
    let task = Task {
      withUnsafeCurrentTask { $0?.cancel() }
      return try await provider.lyrics(for: song(cancelled))
    }
    await #expect(throws: CancellationError.self) { try await task.value }
    #expect(BetterProtocol.lastRequest(for: cancelled) == nil)
  }

  @Test
  func retryAfterBlocksFurtherRequestsWithoutPolling() async {
    let limited = "Limited Better fixture"
    let next = "Blocked Better fixture"
    BetterProtocol.register(
      title: limited, status: 429, body: Data(), headers: ["Retry-After": "60"])
    BetterProtocol.register(title: next, status: 404, body: Data())
    let provider = makeProvider()

    await #expect(throws: BetterLyricsError.rateLimited) {
      try await provider.lyrics(for: song(limited))
    }
    await #expect(throws: BetterLyricsError.rateLimited) {
      try await provider.lyrics(for: song(next))
    }
    #expect(BetterProtocol.lastRequest(for: next) == nil)
  }

  private func makeProvider() -> BetterLyricsProvider {
    let configuration = URLSessionConfiguration.ephemeral
    configuration.protocolClasses = [BetterProtocol.self]
    return BetterLyricsProvider(
      session: URLSession(configuration: configuration),
      throttle: BetterLyricsRequestThrottle())
  }

  private func song(_ title: String) -> Song {
    Song(id: "id", title: title, artist: "Artist")
  }

  private func payload(_ ttml: String) -> Data {
    (try? JSONSerialization.data(withJSONObject: ["ttml": ttml])) ?? Data()
  }
}

private final class BetterProtocol: URLProtocol {
  private struct Fixture: Sendable {
    let status: Int
    let body: Data
    let headers: [String: String]
  }

  private static let registry = Registry()

  static func register(
    title: String, status: Int, body: Data, headers: [String: String] = [:]
  ) {
    registry.register(
      title: title, fixture: Fixture(status: status, body: body, headers: headers))
  }

  static func lastRequest(for title: String) -> URLRequest? {
    registry.lastRequest(for: title)
  }

  override class func canInit(with request: URLRequest) -> Bool {
    request.url?.host == "api.betterlyrics.org"
  }

  override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }

  override func startLoading() {
    guard let url = request.url,
      let title = URLComponents(url: url, resolvingAgainstBaseURL: false)?
        .queryItems?.first(where: { $0.name == "s" })?.value,
      let fixture = Self.registry.fixture(for: title, request: request),
      let response = HTTPURLResponse(
        url: url, statusCode: fixture.status, httpVersion: "HTTP/1.1",
        headerFields: fixture.headers)
    else {
      client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse))
      return
    }
    client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
    client?.urlProtocol(self, didLoad: fixture.body)
    client?.urlProtocolDidFinishLoading(self)
  }

  override func stopLoading() {}

  private final class Registry: @unchecked Sendable {
    private let lock = NSLock()
    private var fixtures: [String: Fixture] = [:]
    private var requests: [String: URLRequest] = [:]

    func register(title: String, fixture: Fixture) {
      lock.lock()
      defer { lock.unlock() }
      fixtures[title] = fixture
      requests.removeValue(forKey: title)
    }

    func fixture(for title: String, request: URLRequest) -> Fixture? {
      lock.lock()
      defer { lock.unlock() }
      requests[title] = request
      return fixtures[title]
    }

    func lastRequest(for title: String) -> URLRequest? {
      lock.lock()
      defer { lock.unlock() }
      return requests[title]
    }
  }
}