geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import Foundation
import OSLog
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public struct MusicWebConfiguration: Equatable, Sendable {
public let apiKey: String
public let clientName: String
public let clientVersion: String
public let clientID: String
public let visitorData: String?
public let language: String
public let country: String
public let userAgent: String
public init(
apiKey: String = "",
clientName: String = "WEB_REMIX",
clientVersion: String = "1.20260315.01.00",
clientID: String = "67",
visitorData: String? = nil,
language: String = "en",
country: String = "US",
userAgent: String = InnerTubeClientProfile.webUserAgent
) {
self.apiKey = apiKey
self.clientName = clientName
self.clientVersion = clientVersion
self.clientID = clientID
self.visitorData = visitorData
self.language = language
self.country = country
self.userAgent = userAgent
}
/// AuraMusic's pinned WEB_REMIX defaults. InnerTube posts do not require a
/// web-page bootstrap or an API-key query for this client.
public static let auraWebRemix = MusicWebConfiguration()
public static func parse(from html: String) throws -> MusicWebConfiguration {
func value(for key: String) -> String? {
let escapedKey = NSRegularExpression.escapedPattern(for: key)
let pattern = "\"\(escapedKey)\"\\s*:\\s*\"([^\"]+)\""
guard let expression = try? NSRegularExpression(pattern: pattern) else {
return nil
}
let range = NSRange(html.startIndex..<html.endIndex, in: html)
return expression.firstMatch(in: html, range: range).flatMap {
guard let valueRange = Range($0.range(at: 1), in: html) else {
return nil
}
return String(html[valueRange])
}
}
func numericValue(for key: String) -> String? {
let escapedKey = NSRegularExpression.escapedPattern(for: key)
let pattern = "\"\(escapedKey)\"\\s*:\\s*(?:\"([0-9]+)\"|([0-9]+))"
guard let expression = try? NSRegularExpression(pattern: pattern) else {
return nil
}
let range = NSRange(html.startIndex..<html.endIndex, in: html)
guard let match = expression.firstMatch(in: html, range: range) else {
return nil
}
for index in 1...2 {
if let valueRange = Range(match.range(at: index), in: html) {
return String(html[valueRange])
}
}
return nil
}
guard let apiKey = value(for: "INNERTUBE_API_KEY"),
let clientVersion = value(for: "INNERTUBE_CLIENT_VERSION")
else {
throw InnerTubeError.invalidConfiguration(
"the web page did not contain an API key and client version")
}
return MusicWebConfiguration(
apiKey: apiKey,
clientName: value(for: "INNERTUBE_CLIENT_NAME") ?? "WEB_REMIX",
clientVersion: clientVersion,
clientID: numericValue(for: "INNERTUBE_CONTEXT_CLIENT_NAME") ?? "67",
visitorData: value(for: "VISITOR_DATA"),
language: value(for: "HL") ?? "en",
country: value(for: "GL") ?? "US",
userAgent: InnerTubeClientProfile.webUserAgent
)
}
}
public struct InnerTubeClientProfile: Sendable {
public static let webUserAgent =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0"
public let clientName: String
public let clientVersion: String
public let clientID: String
public let userAgent: String
public let loginSupported: Bool
public let useSignatureTimestamp: Bool
public let useWebPoTokens: Bool
public let osName: String?
public let osVersion: String?
public let deviceMake: String?
public let deviceModel: String?
public let androidSDKVersion: String?
public init(
clientName: String,
clientVersion: String,
clientID: String,
userAgent: String,
loginSupported: Bool = false,
useSignatureTimestamp: Bool = false,
useWebPoTokens: Bool = false,
osName: String? = nil,
osVersion: String? = nil,
deviceMake: String? = nil,
deviceModel: String? = nil,
androidSDKVersion: String? = nil
) {
self.clientName = clientName
self.clientVersion = clientVersion
self.clientID = clientID
self.userAgent = userAgent
self.loginSupported = loginSupported
self.useSignatureTimestamp = useSignatureTimestamp
self.useWebPoTokens = useWebPoTokens
self.osName = osName
self.osVersion = osVersion
self.deviceMake = deviceMake
self.deviceModel = deviceModel
self.androidSDKVersion = androidSDKVersion
}
public static let iosPlayback = InnerTubeClientProfile(
clientName: "IOS",
clientVersion: "21.03.1",
clientID: "5",
userAgent: "com.google.ios.youtube/21.03.1 (iPhone16,2; U; CPU iOS 18_2 like Mac OS X;)",
loginSupported: false,
osName: "iOS",
osVersion: "18.2.22C152",
deviceMake: "Apple",
deviceModel: "iPhone16,2"
)
public static func webRemix(from configuration: MusicWebConfiguration) -> InnerTubeClientProfile {
InnerTubeClientProfile(
clientName: configuration.clientName,
clientVersion: configuration.clientVersion,
clientID: configuration.clientID,
userAgent: configuration.userAgent,
loginSupported: true,
useSignatureTimestamp: true,
useWebPoTokens: true
)
}
}
public struct InnerTubeRequestBuilder: Sendable {
public let configuration: MusicWebConfiguration
public let origin: URL
public let now: @Sendable () -> Date
public init(
configuration: MusicWebConfiguration,
origin: URL? = nil,
now: @escaping @Sendable () -> Date = { Date() }
) {
self.configuration = configuration
self.origin = origin ?? Self.defaultOrigin
self.now = now
}
private static var defaultOrigin: URL {
guard let url = URL(string: "https://music.youtube.com") else {
preconditionFailure("The InnerTube origin must be a valid URL")
}
return url
}
public func makeRequest(
endpoint: String,
body: Data,
session: UserSession? = nil,
profile: InnerTubeClientProfile? = nil,
queryItems: [URLQueryItem] = []
) throws -> URLRequest {
guard
var components = URLComponents(
url: origin.appendingPathComponent("youtubei/v1/\(endpoint)"),
resolvingAgainstBaseURL: false
)
else {
throw InnerTubeError.invalidConfiguration("could not construct the InnerTube endpoint")
}
let allowedQueryNames: Set<String> = ["continuation", "ctoken"]
guard queryItems.allSatisfy({ allowedQueryNames.contains($0.name) }) else {
throw InnerTubeError.invalidConfiguration(
"the InnerTube endpoint received an unsupported query option")
}
var requestQueryItems = [
URLQueryItem(name: "prettyPrint", value: "false")
]
if !configuration.apiKey.isEmpty {
requestQueryItems.insert(URLQueryItem(name: "key", value: configuration.apiKey), at: 0)
}
components.queryItems = requestQueryItems + queryItems
guard let url = components.url else {
throw InnerTubeError.invalidConfiguration("could not encode the InnerTube endpoint")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = body
request.timeoutInterval = 60
request.httpShouldHandleCookies = false
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("1", forHTTPHeaderField: "X-Goog-Api-Format-Version")
let resolvedProfile = profile ?? .webRemix(from: configuration)
request.setValue(
resolvedProfile.clientID,
forHTTPHeaderField: "X-YouTube-Client-Name"
)
request.setValue(
resolvedProfile.clientVersion,
forHTTPHeaderField: "X-YouTube-Client-Version"
)
request.setValue(origin.absoluteString, forHTTPHeaderField: "X-Origin")
request.setValue("\(origin.absoluteString)/", forHTTPHeaderField: "Referer")
request.setValue(
resolvedProfile.userAgent,
forHTTPHeaderField: "User-Agent"
)
request.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language")
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
let credentialOriginAllowed = Self.isCredentialOrigin(origin)
let hasSAPISID = UserSessionCredentials.hasCompleteLogin(
in: session?.cookieHeader ?? ""
)
let requestVisitorData =
credentialOriginAllowed && resolvedProfile.loginSupported && hasSAPISID
? session?.visitorData ?? configuration.visitorData
: configuration.visitorData
if let requestVisitorData {
request.setValue(requestVisitorData, forHTTPHeaderField: "X-Goog-Visitor-Id")
}
if credentialOriginAllowed,
resolvedProfile.loginSupported,
let session,
session.isAuthenticated,
let sapisid = UserSessionCredentials.value(named: "SAPISID", in: session.cookieHeader)
{
request.setValue(session.cookieHeader, forHTTPHeaderField: "Cookie")
let timestamp = Int(now().timeIntervalSince1970)
let digest = SHA1.hexDigest("\(timestamp) \(sapisid) \(origin.absoluteString)")
request.setValue("SAPISIDHASH \(timestamp)_\(digest)", forHTTPHeaderField: "Authorization")
}
return request
}
private static func isCredentialOrigin(_ origin: URL) -> Bool {
InnerTubeMediaURLPolicy.isAllowedAPIOrigin(origin)
}
}
/// Builds the JSON envelope shared by the supported InnerTube operations.
///
/// This mirrors AuraMusic's `Context` model: nullable client fields are
/// omitted, while `request` and `user.lockedSafetyMode` remain present. The
/// session is included only when the selected client supports login and the
/// caller explicitly requested authenticated transport.
public struct InnerTubeRequestBodyBuilder: Sendable {
public let configuration: MusicWebConfiguration
public init(configuration: MusicWebConfiguration) {
self.configuration = configuration
}
public func makeBody(
values: [String: Any],
profile: InnerTubeClientProfile? = nil,
session: UserSession? = nil,
authenticated: Bool = false
) throws -> Data {
let resolvedProfile = profile ?? .webRemix(from: configuration)
var client: [String: Any] = [
"clientName": resolvedProfile.clientName,
"clientVersion": resolvedProfile.clientVersion,
"hl": configuration.language,
"gl": configuration.country,
]
if let osName = resolvedProfile.osName {
client["osName"] = osName
}
if let osVersion = resolvedProfile.osVersion {
client["osVersion"] = osVersion
}
if let deviceMake = resolvedProfile.deviceMake {
client["deviceMake"] = deviceMake
}
if let deviceModel = resolvedProfile.deviceModel {
client["deviceModel"] = deviceModel
}
if let androidSDKVersion = resolvedProfile.androidSDKVersion {
client["androidSdkVersion"] = androidSDKVersion
}
let contextVisitorData =
authenticated && resolvedProfile.loginSupported
? session?.visitorData ?? configuration.visitorData
: configuration.visitorData
if let contextVisitorData {
client["visitorData"] = contextVisitorData
}
var user: [String: Any] = ["lockedSafetyMode": false]
if authenticated,
resolvedProfile.loginSupported,
let delegatedSessionID = session?.delegatedSessionID
{
user["onBehalfOfUser"] = delegatedSessionID
}
let context: [String: Any] = [
"client": client,
"request": [
"internalExperimentFlags": [],
"useSsl": true,
],
"user": user,
]
var payload = values
payload["context"] = context
guard JSONSerialization.isValidJSONObject(payload) else {
throw InnerTubeError.invalidConfiguration("request body contains unsupported values")
}
do {
return try JSONSerialization.data(withJSONObject: payload)
} catch {
throw InnerTubeError.invalidConfiguration("request body could not be encoded")
}
}
}
public actor InnerTubeClient {
private let urlSession: URLSession
private let playerScriptHTTP: PlayerScriptHTTPCache?
private let redirectDelegate: InnerTubeRedirectDelegate?
private let origin: URL
private let logger = Logger(subsystem: "com.hydraulophone", category: "transport")
private var configuration: MusicWebConfiguration?
private var session: UserSession?
private var playbackVisitorData: String?
private var visitorBootstrapTask: (id: UUID, task: Task<String, Error>)?
private var visitorSessionGeneration = 0
private var playerScriptAsset: PreparedPlayerScript?
private var playerScriptTask: (id: UUID, task: Task<PreparedPlayerScript, Error>)?
private var playerPreparationGeneration = 0
private var forcePlayerScriptReload = false
struct PreparedPlayerScript: Sendable {
let url: URL
let source: String
let timestamp: Int
let profileKey: String
let createdAt: Date
let reusableUntil: Date
}
public init(
urlSession: URLSession? = nil,
origin: URL? = nil,
configuration: MusicWebConfiguration? = nil
) {
if let urlSession {
self.urlSession = urlSession
self.redirectDelegate = nil
self.playerScriptHTTP = nil
} else {
self.playerScriptHTTP = PlayerScriptHTTPCache()
let configuration = URLSessionConfiguration.ephemeral
configuration.httpCookieStorage = nil
configuration.httpShouldSetCookies = false
configuration.urlCache = nil
let redirectDelegate = InnerTubeRedirectDelegate()
self.redirectDelegate = redirectDelegate
self.urlSession = URLSession(
configuration: configuration,
delegate: redirectDelegate,
delegateQueue: nil
)
}
self.origin = origin ?? Self.defaultOrigin
self.configuration = configuration
}
private static var defaultOrigin: URL {
guard let url = URL(string: "https://music.youtube.com") else {
preconditionFailure("The InnerTube origin must be a valid URL")
}
return url
}
public func setSession(_ session: UserSession?) {
self.session = session
visitorSessionGeneration += 1
visitorBootstrapTask?.task.cancel()
visitorBootstrapTask = nil
playbackVisitorData = nil
invalidatePlayerPreparation()
}
func invalidatePlayerPreparation(includingHTTP: Bool = false) {
playerPreparationGeneration &+= 1
playerScriptAsset = nil
playerScriptTask?.task.cancel()
playerScriptTask = nil
if includingHTTP {
playerScriptHTTP?.invalidate()
forcePlayerScriptReload = true
}
}
func cancelPlaybackPreparation() {
// Offline Only must stop shared bootstrap work as well as script work.
// Keep an already established visitor, but reject late bootstrap results.
visitorSessionGeneration &+= 1
visitorBootstrapTask?.task.cancel()
visitorBootstrapTask = nil
invalidatePlayerPreparation()
}
func cachedPlayerScript(profile: InnerTubeClientProfile) -> PreparedPlayerScript? {
guard let asset = playerScriptAsset,
asset.profileKey == profile.clientName + "/" + profile.clientVersion + "/"
+ profile.userAgent,
(0..<1_800).contains(Date().timeIntervalSince(asset.createdAt)),
Date() < asset.reusableUntil
else { return nil }
return asset
}
/// Public script bytes have their own HTTP disk cache; the prepared version
/// is paired with its URL, timestamp, and response freshness in memory.
func preparePlayerScript(
from response: Data? = nil, videoID: String, profile: InnerTubeClientProfile
) async throws -> PreparedPlayerScript {
let generation = visitorSessionGeneration
let preparationGeneration = playerPreparationGeneration
let advertisedURL = response.flatMap { ResponseParser.playerJavaScriptURL(from: $0) }
if let cached = cachedPlayerScript(profile: profile),
advertisedURL == nil || advertisedURL == cached.url
{
return cached
}
if let pending = playerScriptTask {
let asset = try await pending.task.value
try Task.checkCancellation()
guard generation == visitorSessionGeneration,
preparationGeneration == playerPreparationGeneration
else { throw CancellationError() }
if asset.profileKey == profile.clientName + "/" + profile.clientVersion + "/"
+ profile.userAgent,
advertisedURL == nil || advertisedURL == asset.url
{
return asset
}
}
let id = UUID()
let forceReload = forcePlayerScriptReload
let task = Task { [self] in
let url: URL
let script: (source: String, reusableUntil: Date)
if let advertisedURL {
do {
script = try await fetchPlayerJavaScriptAsset(
at: advertisedURL, profile: profile, forceReload: forceReload)
url = advertisedURL
} catch is CancellationError {
throw CancellationError()
} catch {
url = try await discoverPlayerJavaScript(videoID: videoID, profile: profile)
script = try await fetchPlayerJavaScriptAsset(
at: url, profile: profile, forceReload: forceReload)
}
} else {
url = try await discoverPlayerJavaScript(videoID: videoID, profile: profile)
script = try await fetchPlayerJavaScriptAsset(
at: url, profile: profile, forceReload: forceReload)
}
try Task.checkCancellation()
guard let timestamp = ResponseParser.playerSignatureTimestamp(from: script.source) else {
throw PlayerStreamCipherError.invalidScript
}
return PreparedPlayerScript(
url: url, source: script.source, timestamp: timestamp,
profileKey: profile.clientName + "/" + profile.clientVersion + "/" + profile.userAgent,
createdAt: Date(), reusableUntil: script.reusableUntil)
}
playerScriptTask = (id, task)
do {
let asset = try await task.value
guard generation == visitorSessionGeneration,
preparationGeneration == playerPreparationGeneration, playerScriptTask?.id == id
else {
throw CancellationError()
}
playerScriptAsset = asset
forcePlayerScriptReload = false
playerScriptTask = nil
try Task.checkCancellation()
return asset
} catch {
if playerScriptTask?.id == id { playerScriptTask = nil }
throw error
}
}
public func hasSession() -> Bool {
session?.isAuthenticated == true
}
public func hasCompleteLogin() -> Bool {
Self.hasCompleteLogin(session)
}
public func credentialTransportAllowed() -> Bool {
Self.isCredentialOrigin(origin)
}
public func sessionSnapshot() -> UserSession? {
session
}
func logPlayerDiagnostic(data: Data, profile: InnerTubeClientProfile) {
let diagnostic = ResponseParser.playerDiagnostic(from: data)
let shape = ResponseParser.playerShapeDiagnostic(from: data)
logger.info(
"InnerTube player profile=\(profile.clientName, privacy: .public)/\(profile.clientVersion, privacy: .public) status=\(diagnostic.status, privacy: .public) category=\(diagnostic.category, privacy: .public) hls=\(shape.hasHLSManifest, privacy: .public) directAAC=\(shape.directAACCount, privacy: .public) cipheredAAC=\(shape.cipheredAACCount, privacy: .public) adaptive=\(shape.adaptiveCount, privacy: .public)"
)
}
func logStreamCandidate(
profile: InnerTubeClientProfile,
probePassed: Bool,
selected: Bool = false
) {
logger.info(
"InnerTube stream candidate profile=\(profile.clientName, privacy: .public)/\(profile.clientVersion, privacy: .public) probePassed=\(probePassed, privacy: .public) selected=\(selected, privacy: .public)"
)
}
func logStreamCipher(
profile: InnerTubeClientProfile,
stage: PlayerStreamCipherStage,
succeeded: Bool,
error: PlayerStreamCipherError? = nil
) {
let category = error?.rawValue ?? (succeeded ? "none" : "unavailable")
logger.info(
"""
InnerTube cipher profile=\(profile.clientName, privacy: .public) \
stage=\(stage.rawValue, privacy: .public) succeeded=\(succeeded) \
category=\(category, privacy: .public)
"""
)
}
public func configurationSnapshot() async throws -> MusicWebConfiguration {
let base = configuration ?? MusicWebConfiguration.auraWebRemix
configuration = base
let allowsSessionContext = Self.isCredentialOrigin(origin)
let visitor =
(allowsSessionContext ? Self.validVisitorData(session?.visitorData) : nil)
?? Self.validVisitorData(base.visitorData)
?? (allowsSessionContext ? playbackVisitorData : nil)
guard let visitor else {
return base
}
return Self.configurationWithVisitor(base, visitorData: visitor)
}
/// Prepares the anonymous visitor context required by playback profiles.
///
/// Unlike `configurationSnapshot()`, this method may perform the one
/// credential-free web bootstrap. Callers should invoke it before resolving a
/// player stream; ordinary search and library operations remain independent
/// of this network request.
public func preparePlaybackContext() async throws {
try Task.checkCancellation()
let base = configuration ?? MusicWebConfiguration.auraWebRemix
configuration = base
if Self.validVisitorData(session?.visitorData) != nil
|| Self.validVisitorData(base.visitorData) != nil
{
return
}
if Self.validVisitorData(playbackVisitorData) != nil {
return
}
guard Self.isCredentialOrigin(origin) else {
throw InnerTubeError.invalidConfiguration(
"anonymous visitor bootstrap requires the music.youtube.com origin")
}
let generation = visitorSessionGeneration
let pending: (id: UUID, task: Task<String, Error>)
if let visitorBootstrapTask {
pending = visitorBootstrapTask
} else {
let newTask = Task { [weak self] () throws -> String in
guard let self else {
throw InnerTubeError.invalidConfiguration(
"anonymous visitor bootstrap is no longer available")
}
return try await self.fetchAnonymousVisitor()
}
pending = (UUID(), newTask)
visitorBootstrapTask = pending
}
let visitor: String
do {
visitor = try await pending.task.value
} catch {
if visitorBootstrapTask?.id == pending.id {
visitorBootstrapTask = nil
}
throw error
}
try Task.checkCancellation()
guard generation == visitorSessionGeneration else {
throw CancellationError()
}
guard let visitor = Self.validVisitorData(visitor) else {
throw InnerTubeError.invalidResponse(
"anonymous visitor bootstrap returned no visitor data")
}
playbackVisitorData = visitor
if visitorBootstrapTask?.id == pending.id {
visitorBootstrapTask = nil
}
}
public func post(
endpoint: String,
body: Data,
authenticated: Bool = false,
profile: InnerTubeClientProfile? = nil,
sessionOverride: UserSession? = nil,
queryItems: [URLQueryItem] = []
) async throws -> Data {
let configuration = try await configurationSnapshot()
let resolvedProfile = profile ?? .webRemix(from: configuration)
let builder = InnerTubeRequestBuilder(
configuration: configuration,
origin: origin
)
let requestSession = sessionOverride ?? session
let useLogin =
authenticated
&& resolvedProfile.loginSupported
&& Self.isCredentialOrigin(origin)
&& Self.hasCompleteLogin(requestSession)
let request = try builder.makeRequest(
endpoint: endpoint,
body: body,
session: useLogin ? requestSession : nil,
profile: resolvedProfile,
queryItems: queryItems
)
#if DEBUG
if endpoint == "player",
ProcessInfo.processInfo.arguments.contains("-HydraulophoneGuestVisitorProbe")
{
logger.notice(
"""
visitor_probe profile=\(resolvedProfile.clientName, privacy: .public) \
visitor_header=\(request.value(forHTTPHeaderField: "X-Goog-Visitor-Id") != nil) \
cookie_header=\(request.value(forHTTPHeaderField: "Cookie") != nil) \
authorization_header=\(request.value(forHTTPHeaderField: "Authorization") != nil)
"""
)
}
#endif
let (data, response) = try await data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw InnerTubeError.invalidResponse("InnerTube response was not HTTP")
}
guard (200..<300).contains(httpResponse.statusCode) else {
let diagnostic = InnerTubeFailureDiagnosticParser.parse(
data: data,
statusCode: httpResponse.statusCode
)
logger.error(
"InnerTube endpoint \(endpoint, privacy: .public) returned HTTP \(httpResponse.statusCode, privacy: .public) client=\(resolvedProfile.clientName, privacy: .public) category=\(diagnostic.category.rawValue, privacy: .public) reason=\(diagnostic.reason ?? "none", privacy: .public)"
)
throw InnerTubeError.httpStatus(httpResponse.statusCode)
}
return data
}
/// Performs AuraMusic's bounded ranged liveness check for a resolved media
/// URL. Direct media URLs are expiring credentials, so this method never
/// persists or logs them. A failed probe means the caller should request a
/// fresh player response rather than retry the same URL indefinitely.
public func probeStreamURL(
_ url: URL,
profile: InnerTubeClientProfile,
timeout: TimeInterval = 10
) async throws -> Bool {
guard
let statusCode = try await probeStreamURLStatus(
url,
profile: profile,
timeout: timeout
)
else {
return false
}
return (200..<300).contains(statusCode)
}
/// Returns the bounded range probe's HTTP status without exposing the URL
/// or response body. High-quality resolution uses 403 to decide whether one
/// fresh proof/player attempt is justified.
public func probeStreamURLStatus(
_ url: URL,
profile: InnerTubeClientProfile,
timeout: TimeInterval = 10
) async throws -> Int? {
guard InnerTubeMediaURLPolicy.isAllowedMediaURL(url) else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.timeoutInterval = timeout
request.httpShouldHandleCookies = false
request.setValue("bytes=0-0", forHTTPHeaderField: "Range")
for (name, value) in profile.mediaHeaders {
request.setValue(value, forHTTPHeaderField: name)
}
let (_, response) = try await data(for: request, maximumBytes: 16 * 1024)
guard let httpResponse = response as? HTTPURLResponse else {
return nil
}
guard
let finalURL = httpResponse.url,
InnerTubeMediaURLPolicy.isAllowedMediaURL(finalURL)
else {
return nil
}
logger.info(
"""
InnerTube media probe profile=\(profile.clientName, privacy: .public) \
status=\(httpResponse.statusCode)
"""
)
return httpResponse.statusCode
}
func fetchMediaPlaylist(
at url: URL, profile: InnerTubeClientProfile
) async throws -> (text: String, url: URL) {
guard InnerTubeMediaURLPolicy.isAllowedMediaURL(url) else {
throw InnerTubeError.playbackUnavailable("the playlist URL was not allowed")
}
var request = URLRequest(url: url)
request.httpShouldHandleCookies = false
request.timeoutInterval = 10
for (name, value) in profile.mediaHeaders {
request.setValue(value, forHTTPHeaderField: name)
}
let (data, response) = try await self.data(for: request, maximumBytes: 512 * 1024)
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
let finalURL = http.url, InnerTubeMediaURLPolicy.isAllowedMediaURL(finalURL),
let text = String(data: data, encoding: .utf8), text.hasPrefix("#EXTM3U")
else {
throw InnerTubeError.playbackUnavailable("the media playlist could not be loaded")
}
return (text, finalURL)
}
func logHLSSelection(
audioCount: Int, variantCount: Int, audioOnlyVariantCount: Int, audioGroupCount: Int,
bitrate: Int
) {
logger.notice(
"hls_manifest audio=\(audioCount) variants=\(variantCount) audio_only_variants=\(audioOnlyVariantCount) audio_groups=\(audioGroupCount) selected_bitrate=\(bitrate)"
)
}
func logHLSRendition(formatID: Int, bitrate: Int, selected: Bool) {
logger.notice("hls_audio itag=\(formatID) bitrate=\(bitrate) selected=\(selected)")
}
func logHLSPlaylistShape(
segmentCount: Int, transportStreamSegments: Int, fragmentedMP4Segments: Int,
otherSegments: Int, aes128KeyCount: Int, sampleEncryptionKeyCount: Int, mapCount: Int,
byteRangeCount: Int
) {
logger.notice(
"hls_playlist segments=\(segmentCount) ts=\(transportStreamSegments) fmp4=\(fragmentedMP4Segments) other=\(otherSegments) aes128_keys=\(aes128KeyCount) sample_keys=\(sampleEncryptionKeyCount) maps=\(mapCount) byte_ranges=\(byteRangeCount)"
)
}
/// Fetches the player JavaScript needed by a local stream decipherer.
///
/// The player response is searched first for its advertised script URL. If
/// that metadata is absent, a credential-free YouTube watch-page discovery
/// request is used. Both requests are bounded by the client's existing
/// cancellation-aware retry policy and validate their final hosts before
/// returning script source. Script source and response data are ephemeral.
public func fetchPlayerJavaScript(
from playerResponse: Data,
videoID: String,
profile: InnerTubeClientProfile
) async throws -> String {
try Task.checkCancellation()
if let responseURL = ResponseParser.playerJavaScriptURL(from: playerResponse) {
do {
return try await fetchPlayerJavaScript(at: responseURL, profile: profile)
} catch is CancellationError {
throw CancellationError()
} catch {
// A stale player response can advertise an unavailable asset. A
// bounded, anonymous page discovery remains a safe alternative.
}
}
let discoveredURL = try await discoverPlayerJavaScript(videoID: videoID, profile: profile)
return try await fetchPlayerJavaScript(at: discoveredURL, profile: profile)
}
private func fetchAnonymousVisitor() async throws -> String {
guard let url = URL(string: "https://music.youtube.com/sw.js_data"),
Self.isCredentialOrigin(url)
else {
throw InnerTubeError.invalidConfiguration(
"anonymous visitor bootstrap URL was not allowed")
}
var request = URLRequest(url: url)
request.httpShouldHandleCookies = false
request.timeoutInterval = 10
request.setValue(InnerTubeClientProfile.webUserAgent, forHTTPHeaderField: "User-Agent")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let data: Data
let response: URLResponse
do {
(data, response) = try await self.data(for: request, maximumBytes: 512 * 1024)
} catch is CancellationError {
throw CancellationError()
} catch let error as InnerTubeError {
throw error
} catch {
throw InnerTubeError.invalidResponse(
"anonymous visitor bootstrap could not be fetched")
}
guard let http = response as? HTTPURLResponse else {
throw InnerTubeError.invalidResponse(
"anonymous visitor bootstrap returned a non-HTTP response")
}
guard http.statusCode == 200 else {
throw InnerTubeError.httpStatus(http.statusCode)
}
guard let finalURL = http.url, Self.isCredentialOrigin(finalURL) else {
throw InnerTubeError.invalidResponse(
"anonymous visitor bootstrap redirected outside music.youtube.com")
}
let json = data.starts(with: [0x29, 0x5D, 0x7D, 0x27]) ? Data(data.dropFirst(5)) : data
guard let root = try? JSONSerialization.jsonObject(with: json) as? [Any],
let first = root.first as? [Any], first.count > 2,
let values = first[2] as? [Any],
let visitor = values.compactMap({ $0 as? String }).first(where: {
($0.hasPrefix("Cgt") || $0.hasPrefix("Cgs"))
&& $0.utf8.count < 4096 && !$0.contains("\r") && !$0.contains("\n")
})
else {
throw InnerTubeError.invalidResponse(
"anonymous visitor bootstrap response was malformed")
}
return visitor
}
#if DEBUG
func logAlternativePlayerShape(data: Data, profile: InnerTubeClientProfile) {
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let streaming = root["streamingData"] as? [String: Any]
else {
logger.notice("audio_shape profile=\(profile.clientName, privacy: .public) streaming=false")
return
}
let formats = streaming["adaptiveFormats"] as? [[String: Any]] ?? []
let sabr = streaming["serverAbrStreamingUrl"] != nil
logger.notice(
"audio_shape profile=\(profile.clientName, privacy: .public) adaptive=\(formats.count) sabr=\(sabr)"
)
for format in formats.filter({
($0["mimeType"] as? String)?.hasPrefix("audio/") == true
}).prefix(8) {
let mime = format["mimeType"] as? String ?? ""
let family = mime.contains("opus") ? "opus" : (mime.contains("mp4a") ? "aac" : "other")
let itag = format["itag"] as? Int ?? -1
let bitrate = format["bitrate"] as? Int ?? -1
let direct = format["url"] != nil
let cipher = format["signatureCipher"] != nil || format["cipher"] != nil
let drm = format["drmFamilies"] != nil
logger.notice(
"""
audio_shape itag=\(itag) family=\(family, privacy: .public) \
bitrate=\(bitrate) direct=\(direct) cipher=\(cipher) drm=\(drm)
"""
)
}
}
func logOpusCandidates(profile: InnerTubeClientProfile, count: Int) {
logger.notice(
"""
opus_probe profile=\(profile.clientName, privacy: .public) \
guest=\(!profile.loginSupported) candidates=\(count)
"""
)
}
func logOpusCandidate(
profile: InnerTubeClientProfile,
bitrate: Int,
direct: Bool,
ciphered: Bool
) {
logger.notice(
"opus_candidate profile=\(profile.clientName, privacy: .public) bitrate=\(bitrate) direct=\(direct) ciphered=\(ciphered)"
)
}
/// Simulator experiment only. Reports byte-range viability, not decoding
/// support, and never returns a URL or response body to the diagnostic UI.
func probeAlternativeRange(
url: URL, profile: InnerTubeClientProfile, offset: Int64, percent: Int
) async throws -> (length: Int64?, valid: Bool) {
guard InnerTubeMediaURLPolicy.isAllowedMediaURL(url), offset >= 0,
offset < Int64.max - 1
else { throw PlayerStreamCipherError.invalidResult }
var request = URLRequest(url: url)
request.httpShouldHandleCookies = false
request.timeoutInterval = 10
for (name, value) in profile.mediaHeaders {
request.setValue(value, forHTTPHeaderField: name)
}
request.setValue("bytes=\(offset)-\(offset + 1)", forHTTPHeaderField: "Range")
let (body, response) = try await data(for: request, maximumBytes: 16 * 1024)
guard let http = response as? HTTPURLResponse,
let finalURL = http.url, InnerTubeMediaURLPolicy.isAllowedMediaURL(finalURL)
else { throw PlayerStreamCipherError.invalidResult }
let rawRange = http.value(forHTTPHeaderField: "Content-Range") ?? ""
let parts = rawRange.split(separator: "/")
let length = parts.count == 2 ? Int64(parts[1]) : nil
let valid =
http.statusCode == 206 && body.count == 2
&& parts.first == "bytes \(offset)-\(offset + 1)"
&& length.map { $0 > offset + 1 } ?? false
logger.notice(
"""
opus_probe profile=\(profile.clientName, privacy: .public) percent=\(percent) \
offset=\(offset) status=\(http.statusCode) bytes=\(body.count) \
total=\(length ?? -1) range_valid=\(valid)
"""
)
return (length, valid)
}
#endif
private func data(
for request: URLRequest,
maximumBytes: Int? = nil
) async throws -> (Data, URLResponse) {
let maxAttempts = 3
var attempt = 0
while true {
try Task.checkCancellation()
do {
let result: (Data, URLResponse)
if let maximumBytes {
result = try await boundedData(for: request, maximumBytes: maximumBytes)
} else {
result = try await urlSession.data(for: request)
}
try Task.checkCancellation()
return result
} catch is CancellationError {
throw CancellationError()
} catch let error as URLError where error.code == .cancelled {
throw CancellationError()
} catch let error as URLError where Self.isTransient(error) && attempt < maxAttempts - 1 {
attempt += 1
try await Task.sleep(for: .milliseconds(500 * Int64(1 << (attempt - 1))))
} catch {
throw error
}
}
}
/// Enforce the cap while receiving, not after URLSession has already
/// buffered an arbitrarily large page/script. The redirect delegate and
/// credential-free session policy still apply to this byte stream.
private func boundedData(
for request: URLRequest,
maximumBytes: Int
) async throws -> (Data, URLResponse) {
let (bytes, response) = try await urlSession.bytes(for: request)
defer { bytes.task.cancel() }
guard response.expectedContentLength <= Int64(maximumBytes) else {
throw InnerTubeError.invalidResponse("response exceeded the configured byte limit")
}
var data = Data()
data.reserveCapacity(Int(max(0, min(response.expectedContentLength, Int64(maximumBytes)))))
for try await byte in bytes {
guard data.count < maximumBytes else {
throw InnerTubeError.invalidResponse("response exceeded the configured byte limit")
}
if data.count.isMultiple(of: 16_384) {
try Task.checkCancellation()
}
data.append(byte)
}
return (data, response)
}
private func discoverPlayerJavaScript(
videoID: String,
profile: InnerTubeClientProfile
) async throws -> URL {
#if DEBUG
var timing = PlaybackStartupTiming()
#endif
guard
!videoID.isEmpty,
videoID.count <= 100,
videoID.unicodeScalars.allSatisfy({
CharacterSet.alphanumerics.contains($0) || $0 == "_" || $0 == "-"
}),
var components = URLComponents(string: "https://www.youtube.com/watch")
else {
throw InnerTubeError.playbackUnavailable("player script discovery was unavailable")
}
components.queryItems = [
URLQueryItem(name: "v", value: videoID),
URLQueryItem(name: "hl", value: "en"),
]
guard let url = components.url else {
throw InnerTubeError.playbackUnavailable("player script discovery was unavailable")
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.timeoutInterval = 15
request.httpShouldHandleCookies = false
request.setValue("text/html", forHTTPHeaderField: "Accept")
request.setValue(profile.userAgent, forHTTPHeaderField: "User-Agent")
let (data, response) = try await data(for: request, maximumBytes: Self.maxPlayerDiscoveryBytes)
guard
let httpResponse = response as? HTTPURLResponse,
(200..<300).contains(httpResponse.statusCode),
let finalURL = httpResponse.url,
InnerTubeMediaURLPolicy.isAllowedYouTubePageURL(finalURL),
data.count <= Self.maxPlayerDiscoveryBytes,
let html = String(data: data, encoding: .utf8),
let scriptURL = ResponseParser.playerJavaScriptURL(fromHTML: html)
else {
throw InnerTubeError.playbackUnavailable("player script discovery was unavailable")
}
#if DEBUG
timing.mark(.scriptDiscovery, bytes: data.count)
#endif
return scriptURL
}
private func fetchPlayerJavaScript(
at url: URL,
profile: InnerTubeClientProfile
) async throws -> String {
try await fetchPlayerJavaScriptAsset(at: url, profile: profile).source
}
private func fetchPlayerJavaScriptAsset(
at url: URL, profile: InnerTubeClientProfile, forceReload: Bool = false
) async throws -> (source: String, reusableUntil: Date) {
#if DEBUG
var timing = PlaybackStartupTiming()
#endif
guard InnerTubeMediaURLPolicy.isAllowedPlayerJavaScriptURL(url) else {
throw InnerTubeError.playbackUnavailable("player script URL was not allowed")
}
var request = URLRequest(url: url)
request.cachePolicy = forceReload ? .reloadIgnoringLocalCacheData : .useProtocolCachePolicy
request.httpMethod = "GET"
request.timeoutInterval = 15
request.httpShouldHandleCookies = false
request.setValue("text/javascript,*/*;q=0.1", forHTTPHeaderField: "Accept")
request.setValue(profile.userAgent, forHTTPHeaderField: "User-Agent")
let data: Data
let response: URLResponse
if let playerScriptHTTP {
(data, response) = try await playerScriptHTTP.data(
for: request, maximumBytes: Self.maxPlayerScriptBytes)
} else {
// Injected transports remain deterministic and never touch a real cache.
(data, response) = try await self.data(for: request, maximumBytes: Self.maxPlayerScriptBytes)
}
guard
let httpResponse = response as? HTTPURLResponse,
(200..<300).contains(httpResponse.statusCode),
let finalURL = httpResponse.url,
InnerTubeMediaURLPolicy.isAllowedPlayerJavaScriptURL(finalURL),
data.count <= Self.maxPlayerScriptBytes,
let source = String(data: data, encoding: .utf8),
!source.isEmpty
else {
throw InnerTubeError.playbackUnavailable("player script could not be fetched")
}
#if DEBUG
timing.mark(.scriptDownload, bytes: data.count)
#endif
return (source, PlayerScriptHTTPCache.preparedReuseDeadline(response: httpResponse))
}
private static let maxPlayerDiscoveryBytes = 2 * 1024 * 1024
private static let maxPlayerScriptBytes = 4 * 1024 * 1024
private static func validVisitorData(_ value: String?) -> String? {
guard let value, !value.isEmpty, value.caseInsensitiveCompare("null") != .orderedSame else {
return nil
}
return value
}
private static func configurationWithVisitor(
_ base: MusicWebConfiguration,
visitorData: String
) -> MusicWebConfiguration {
MusicWebConfiguration(
apiKey: base.apiKey,
clientName: base.clientName,
clientVersion: base.clientVersion,
clientID: base.clientID,
visitorData: visitorData,
language: base.language,
country: base.country,
userAgent: base.userAgent
)
}
private static func isTransient(_ error: URLError) -> Bool {
switch error.code {
case .timedOut, .cannotConnectToHost, .networkConnectionLost, .notConnectedToInternet,
.dnsLookupFailed, .cannotFindHost:
return true
default:
return false
}
}
private static func hasCompleteLogin(_ session: UserSession?) -> Bool {
guard let cookieHeader = session?.cookieHeader else {
return false
}
return UserSessionCredentials.hasCompleteLogin(in: cookieHeader)
}
private static func isCredentialOrigin(_ origin: URL) -> Bool {
InnerTubeMediaURLPolicy.isAllowedAPIOrigin(origin)
}
}
private enum SHA1 {
static func hexDigest(_ string: String) -> String {
let bytes = Array(string.utf8)
var message = bytes
let bitLength = UInt64(message.count) * 8
message.append(0x80)
while message.count % 64 != 56 {
message.append(0)
}
message.append(contentsOf: withUnsafeBytes(of: bitLength.bigEndian, Array.init))
var hash: [UInt32] = [
0x6745_2301,
0xEFCD_AB89,
0x98BA_DCFE,
0x1032_5476,
0xC3D2_E1F0,
]
for chunkStart in stride(from: 0, to: message.count, by: 64) {
var words = Array(repeating: UInt32(0), count: 80)
for index in 0..<16 {
let offset = chunkStart + index * 4
words[index] =
UInt32(message[offset]) << 24
| UInt32(message[offset + 1]) << 16
| UInt32(message[offset + 2]) << 8
| UInt32(message[offset + 3])
}
for index in 16..<80 {
words[index] = (words[index - 3] ^ words[index - 8] ^ words[index - 14] ^ words[index - 16])
.rotateLeft(1)
}
var (a, b, c, d, e) = (hash[0], hash[1], hash[2], hash[3], hash[4])
for index in 0..<80 {
let (function, constant): (UInt32, UInt32)
switch index {
case 0..<20:
function = (b & c) | ((~b) & d)
constant = 0x5A82_7999
case 20..<40:
function = b ^ c ^ d
constant = 0x6ED9_EBA1
case 40..<60:
function = (b & c) | (b & d) | (c & d)
constant = 0x8F1B_BCDC
default:
function = b ^ c ^ d
constant = 0xCA62_C1D6
}
let temp =
a.rotateLeft(5)
&+ function
&+ e
&+ constant
&+ words[index]
e = d
d = c
c = b.rotateLeft(30)
b = a
a = temp
}
hash[0] &+= a
hash[1] &+= b
hash[2] &+= c
hash[3] &+= d
hash[4] &+= e
}
return hash.map { String(format: "%08x", $0) }.joined()
}
}
extension UInt32 {
fileprivate func rotateLeft(_ amount: UInt32) -> UInt32 {
(self << amount) | (self >> (32 - amount))
}
}