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

geesawra.industries/hydraulophone

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

0
0
main
519 lines · 14.7 KB Raw History
import Foundation
import Testing

@testable import HydraulophoneCore

struct ResponseParserTests {
  @Test
  func decodesSongsAndPlaylistsFromDifferentRenderers() throws {
    let data = Data(
      """
      {
        "contents": {
          "musicResponsiveListItemRenderer": {
            "playlistItemData": {"videoId": "song-1"},
            "flexColumns": [
              {"musicResponsiveListItemFlexColumnRenderer": {"text": {"runs": [{"text": "First song"}]}}},
              {"musicResponsiveListItemFlexColumnRenderer": {"text": {"runs": [{"text": "Artist"}]}}},
              {"musicResponsiveListItemFlexColumnRenderer": {"text": {"simpleText": "Album"}}}
            ],
            "fixedColumns": [
              {"musicResponsiveListItemFixedColumnRenderer": {"text": {"simpleText": "3:21"}}}
            ]
          },
          "musicTwoRowItemRenderer": {
            "title": {"runs": [{"text": "A playlist"}]},
            "subtitle": {"simpleText": "5 songs"},
            "navigationEndpoint": {"browseEndpoint": {"browseId": "VLPL123"}}
          }
        }
      }
      """.utf8
    )

    let results = try ResponseParser.searchResults(from: data)

    #expect(
      results.contains(
        .song(
          Song(
            id: "song-1", title: "First song", artist: "Artist", album: "Album",
            durationText: "3:21"))))
    #expect(
      results.contains(
        .playlist(
          Playlist(id: "PL123", title: "A playlist", subtitle: "5 songs", browseID: "VLPL123")))
    )
  }

  @Test
  func decodesLibraryPlaylistsWithoutTreatingAlbumsAsPlaylists() throws {
    let data = Data(
      """
      {
        "contents": {
          "gridRenderer": {
            "items": [
              {
                "musicTwoRowItemRenderer": {
                  "title": {"simpleText": "Owned playlist"},
                  "navigationEndpoint": {
                    "browseEndpoint": {"browseId": "VLPLowned123"}
                  }
                }
              },
              {
                "musicTwoRowItemRenderer": {
                  "title": {"simpleText": "An album"},
                  "navigationEndpoint": {
                    "browseEndpoint": {"browseId": "MPREb00b"}
                  }
                }
              }
            ]
          }
        }
      }
      """.utf8
    )

    #expect(
      try ResponseParser.playlists(from: data)
        == [Playlist(id: "PLowned123", title: "Owned playlist", browseID: "VLPLowned123")]
    )
  }

  @Test
  func choosesTheHighestBitrateMP4AudioWithADirectURL() throws {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "adaptiveFormats": [
            {"mimeType": "audio/webm; codecs=\\"opus\\"", "bitrate": 160000, "url": "https://rr1---sn-example.googlevideo.com/opus"},
            {"mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"", "bitrate": 128000, "url": "https://rr1---sn-example.googlevideo.com/aac"},
            {"mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"", "bitrate": 96000, "url": "https://rr1---sn-example.googlevideo.com/aac-low"}
          ]
        }
      }
      """.utf8
    )

    // ResponseParser is intentionally exercised through the fixture-facing internal parser.
    // The direct URL returned here is never persisted by the app.
    // swift-testing reports a useful failure if a future parser changes this policy.
    #expect(
      try ResponseParser.streamURL(from: data)
        == URL(string: "https://rr1---sn-example.googlevideo.com/aac")
    )
  }

  @Test
  func usesSelectedFormatApproximateDurationBeforeVideoDetailsFallback() throws {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "videoDetails": {"lengthSeconds": "99"},
        "streamingData": {
          "adaptiveFormats": [
            {
              "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
              "bitrate": 128000,
              "approxDurationMs": "321000",
              "url": "https://rr1---sn-example.googlevideo.com/aac"
            }
          ]
        }
      }
      """.utf8
    )

    let stream = try ResponseParser.audioStream(from: data)

    #expect(stream.authoritativeDuration == 321)
  }

  @Test
  func fallsBackToVideoDetailsWhenApproximateDurationIsInvalid() throws {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "videoDetails": {"lengthSeconds": "17"},
        "streamingData": {
          "adaptiveFormats": [
            {
              "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
              "bitrate": 128000,
              "approxDurationMs": "not-a-duration",
              "url": "https://rr1---sn-example.googlevideo.com/aac"
            }
          ]
        }
      }
      """.utf8
    )

    let stream = try ResponseParser.audioStream(from: data)

    #expect(stream.authoritativeDuration == 17)
  }

  @Test
  func fallsBackToVideoDetailsWhenApproximateDurationIsMissing() throws {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "videoDetails": {"lengthSeconds": "42"},
        "streamingData": {
          "adaptiveFormats": [
            {
              "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
              "bitrate": 128000,
              "url": "https://rr1---sn-example.googlevideo.com/aac"
            }
          ]
        }
      }
      """.utf8
    )

    let stream = try ResponseParser.audioStream(from: data)

    #expect(stream.authoritativeDuration == 42)
  }

  @Test
  func leavesAuthoritativeDurationMissingWhenBothDurationFieldsAreUnavailable() throws {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "adaptiveFormats": [
            {
              "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
              "bitrate": 128000,
              "url": "https://rr1---sn-example.googlevideo.com/aac"
            }
          ]
        }
      }
      """.utf8
    )

    let stream = try ResponseParser.audioStream(from: data)

    #expect(stream.authoritativeDuration == nil)
  }

  @Test
  func durationNumbersRejectBooleansWithoutRejectingNumericOne() throws {
    let cases: [(String, TimeInterval?)] = [
      ("1", 1), ("1.5", 1.5), ("\"2000\"", 2_000),
      ("true", nil), ("false", nil), ("0", nil), ("-1", nil),
      ("\"NaN\"", nil), ("\"Infinity\"", nil), ("null", nil),
    ]
    for (rawValue, expected) in cases {
      for field in ["approxDurationMs", "lengthSeconds"] {
        let object = """
          {
            "playabilityStatus": {"status": "OK"},
            "videoDetails": \(field == "lengthSeconds" ? "{\"lengthSeconds\": \(rawValue)}" : "{}"),
            "streamingData": {
              "adaptiveFormats": [{
                "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
                "url": "https://rr1---sn-example.googlevideo.com/aac",
                "approxDurationMs": \(field == "approxDurationMs" ? rawValue : "null")
              }]
            }
          }
          """
        let stream = try ResponseParser.audioStream(from: Data(object.utf8))
        let divisor = field == "approxDurationMs" ? 1_000.0 : 1.0
        #expect(stream.authoritativeDuration == expected.map { $0 / divisor })
      }
    }
  }

  @Test
  func reportsUnavailablePlaybackWhenOnlyCipheredFormatsExist() {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "adaptiveFormats": [
            {"mimeType": "audio/mp4", "signatureCipher": "s=opaque"}
          ]
        }
      }
      """.utf8
    )

    #expect(
      throws: InnerTubeError.playbackUnavailable("the response contained no direct audio URL")
    ) {
      try ResponseParser.streamURL(from: data)
    }
  }

  @Test
  func parsesSignatureCipherURLSignatureParameterAndN() throws {
    let baseURL = try #require(
      URL(string: "https://rr1---sn-example.googlevideo.com/videoplayback?expire=123&n=raw-n")
    )
    var cipherComponents = URLComponents()
    cipherComponents.queryItems = [
      URLQueryItem(name: "url", value: baseURL.absoluteString),
      URLQueryItem(name: "sp", value: "signature"),
      URLQueryItem(name: "s", value: "opaque-signature"),
    ]
    let cipher = try #require(cipherComponents.percentEncodedQuery)
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "videoDetails": {"lengthSeconds": "37"},
        "streamingData": {
          "adaptiveFormats": [{
            "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
            "bitrate": 128000,
            "signatureCipher": "\(cipher)"
          }]
        }
      }
      """.utf8
    )

    let candidate = try #require(try ResponseParser.audioCandidates(from: data).first)
    let parsedCipher = try #require(candidate.cipher)
    #expect(candidate.directURL == nil)
    #expect(parsedCipher.url == baseURL)
    #expect(parsedCipher.signature == "opaque-signature")
    #expect(parsedCipher.signatureParameter == "signature")
    #expect(parsedCipher.n == "raw-n")
    #expect(candidate.authoritativeDuration == 37)
  }

  @Test
  func rejectsCipheredURLsOutsideTheMediaPolicy() throws {
    var cipherComponents = URLComponents()
    cipherComponents.queryItems = [
      URLQueryItem(name: "url", value: "https://user:password@evil.example/videoplayback"),
      URLQueryItem(name: "sp", value: "sig"),
      URLQueryItem(name: "s", value: "opaque-signature"),
    ]
    let cipher = try #require(cipherComponents.percentEncodedQuery)
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "adaptiveFormats": [{
            "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
            "signatureCipher": "\(cipher)"
          }]
        }
      }
      """.utf8
    )

    #expect(try ResponseParser.audioCandidates(from: data).isEmpty)
  }

  @Test
  func extractsOnlyAllowlistedPlayerJavaScriptURLs() throws {
    let data = Data(
      """
      {
        "assets": {
          "js": "/s/player/fixture/base.js"
        },
        "untrusted": {
          "js": "https://evil.example/player.js"
        }
      }
      """.utf8
    )

    #expect(
      ResponseParser.playerJavaScriptURL(from: data)
        == URL(string: "https://www.youtube.com/s/player/fixture/base.js")
    )
    #expect(
      ResponseParser.playerJavaScriptURL(
        fromHTML: #""PLAYER_JS_URL":"\/s\/player\/fixture\/base.js""#
      )
        == URL(string: "https://www.youtube.com/s/player/fixture/base.js")
    )
  }

  @Test
  func preservesNForDirectAACCandidates() throws {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "adaptiveFormats": [{
            "mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"",
            "bitrate": 128000,
            "url": "https://rr1---sn-example.googlevideo.com/videoplayback?n=raw-n"
          }]
        }
      }
      """.utf8
    )

    let candidate = try #require(try ResponseParser.audioCandidates(from: data).first)
    #expect(candidate.directURL != nil)
    #expect(candidate.cipher == nil)
    #expect(candidate.n == "raw-n")
  }

  @Test
  func choosesAudioFromRegularFormatsWhenAdaptiveFormatsAreAbsent() throws {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "formats": [
            {"mimeType": "video/mp4", "bitrate": 900000, "url": "https://rr1---sn-example.googlevideo.com/video"},
            {"mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"", "bitrate": 96000, "url": "https://rr1---sn-example.googlevideo.com/audio"}
          ]
        }
      }
      """.utf8
    )

    #expect(
      try ResponseParser.streamURL(from: data)
        == URL(string: "https://rr1---sn-example.googlevideo.com/audio")
    )
  }

  @Test
  func rejectsOpusOnlyFormatsForNativePlayback() {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "adaptiveFormats": [
            {
              "mimeType": "audio/webm; codecs=\\"opus\\"",
              "bitrate": 160000,
              "url": "https://rr1---sn-example.googlevideo.com/opus"
            }
          ]
        }
      }
      """.utf8
    )

    #expect(
      throws: InnerTubeError.playbackUnavailable("the response contained no direct audio URL")
    ) {
      try ResponseParser.streamURL(from: data)
    }
  }

  @Test
  func reportsPlayerPlayabilityReasonWithoutInventingAStream() {
    let data = Data(
      """
      {
        "playabilityStatus": {
          "status": "LOGIN_REQUIRED",
          "reason": "Sign in to confirm your age"
        }
      }
      """.utf8
    )

    #expect(
      throws: InnerTubeError.playbackRestricted(
        status: "LOGIN_REQUIRED",
        reason: "Sign in to confirm your age"
      )
    ) {
      try ResponseParser.streamURL(from: data)
    }
  }

  @Test
  func classifiesPlayerStatusWithoutLoggingServerReason() {
    let data = Data(
      """
      {
        "playabilityStatus": {
          "status": "ERROR",
          "reason": "private account detail that must not be logged"
        }
      }
      """.utf8
    )

    #expect(
      ResponseParser.playerDiagnostic(from: data)
        == InnerTubePlayerDiagnostic(status: "ERROR", category: "profileUnsupported")
    )
  }

  @Test
  func redactsUnknownPlayerStatusToUnknownDiagnostic() {
    let data = Data(
      #"{"playabilityStatus":{"status":"SERVER_INTERNAL_SECRET","reason":"private"}}"#
        .utf8
    )

    #expect(
      ResponseParser.playerDiagnostic(from: data)
        == InnerTubePlayerDiagnostic(status: "UNKNOWN", category: "unknown")
    )
  }

  @Test
  func reportsAllowlistedPlayerShapeCountsWithoutReturningURLs() {
    let data = Data(
      """
      {
        "playabilityStatus": {"status": "OK"},
        "streamingData": {
          "hlsManifestUrl": "opaque-hls-value",
          "adaptiveFormats": [
            {"mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"", "url": "opaque-aac"},
            {"mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"", "signatureCipher": "opaque-cipher"},
            {"mimeType": "audio/webm; codecs=\\"opus\\"", "url": "opaque-opus"}
          ],
          "formats": [
            {"mimeType": "audio/mp4; codecs=\\"mp4a.40.2\\"", "url": "opaque-aac-muxed"}
          ]
        }
      }
      """.utf8
    )

    #expect(
      ResponseParser.playerShapeDiagnostic(from: data)
        == InnerTubePlayerShapeDiagnostic(
          hasHLSManifest: true,
          directAACCount: 2,
          cipheredAACCount: 1,
          adaptiveCount: 3
        )
    )
  }

  @Test
  func rejectsMalformedPlayerJSONWithTypedError() {
    #expect(throws: InnerTubeError.invalidResponse("JSON could not be decoded")) {
      try ResponseParser.streamURL(from: Data("{".utf8))
    }
  }
}