Yandex Music client for Apple TV
tvOS 17+ SwiftUI client for the unofficial Yandex Music API: rotor stations with feedback, library, search, artist and album pages, synced lyrics, and system Now Playing integration.
This commit is contained in:
@@ -0,0 +1,344 @@
|
||||
import Foundation
|
||||
|
||||
enum YMError: LocalizedError {
|
||||
case notAuthorized
|
||||
case http(status: Int, body: String)
|
||||
case decoding(String)
|
||||
case transport(Error)
|
||||
case message(String)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .notAuthorized:
|
||||
return "Нужно войти в аккаунт Яндекс.Музыки"
|
||||
case let .http(status, body):
|
||||
let snippet = body.prefix(300)
|
||||
if status == 401 || status == 403 {
|
||||
return "Ошибка \(status): доступ запрещён. Токен просрочен или нет подписки Плюс.\n\(snippet)"
|
||||
}
|
||||
return "HTTP \(status)\n\(snippet)"
|
||||
case let .decoding(detail):
|
||||
return "Не удалось разобрать ответ API: \(detail)"
|
||||
case let .transport(error):
|
||||
return "Сеть: \(error.localizedDescription)"
|
||||
case let .message(text):
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Client for the unofficial Yandex Music API (`api.music.yandex.net`).
|
||||
///
|
||||
/// Reverse-engineered from the official clients; Yandex can change it without
|
||||
/// notice. Errors carry the response body to make that diagnosable.
|
||||
actor YMClient {
|
||||
static let shared = YMClient()
|
||||
|
||||
private let base = URL(string: "https://api.music.yandex.net")!
|
||||
private let session: URLSession
|
||||
|
||||
private var token: String?
|
||||
private(set) var uid: Int64?
|
||||
|
||||
init() {
|
||||
let config = URLSessionConfiguration.default
|
||||
config.timeoutIntervalForRequest = 20
|
||||
config.waitsForConnectivity = true
|
||||
config.requestCachePolicy = .reloadIgnoringLocalCacheData
|
||||
session = URLSession(configuration: config)
|
||||
}
|
||||
|
||||
func setToken(_ token: String?) {
|
||||
self.token = token
|
||||
if token == nil { uid = nil }
|
||||
}
|
||||
|
||||
// MARK: - Request plumbing
|
||||
|
||||
private func headers(for request: inout URLRequest) {
|
||||
request.setValue("YandexMusicAndroid/24023621", forHTTPHeaderField: "X-Yandex-Music-Client")
|
||||
request.setValue("Yandex-Music-API", forHTTPHeaderField: "User-Agent")
|
||||
request.setValue("ru", forHTTPHeaderField: "Accept-Language")
|
||||
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||
if let token {
|
||||
request.setValue("OAuth \(token)", forHTTPHeaderField: "Authorization")
|
||||
}
|
||||
}
|
||||
|
||||
private func makeURL(_ path: String, query: [String: String] = [:]) -> URL {
|
||||
var components = URLComponents(
|
||||
url: base.appendingPathComponent(path),
|
||||
resolvingAgainstBaseURL: false
|
||||
)!
|
||||
if !query.isEmpty {
|
||||
// URLComponents lets "+" and "/" through untouched, and servers read
|
||||
// a raw "+" as a space — which silently corrupts every base64 `sign`
|
||||
// we send. Encode the pairs ourselves and hand them over as-is.
|
||||
components.percentEncodedQueryItems = query.map {
|
||||
URLQueryItem(name: Self.escape($0.key), value: Self.escape($0.value))
|
||||
}
|
||||
}
|
||||
return components.url!
|
||||
}
|
||||
|
||||
private func perform(_ request: URLRequest) async throws -> Data {
|
||||
do {
|
||||
let (data, response) = try await session.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse else { return data }
|
||||
guard (200 ..< 300).contains(http.statusCode) else {
|
||||
throw YMError.http(
|
||||
status: http.statusCode,
|
||||
body: String(data: data, encoding: .utf8) ?? "<binary>"
|
||||
)
|
||||
}
|
||||
return data
|
||||
} catch let error as YMError {
|
||||
throw error
|
||||
} catch {
|
||||
throw YMError.transport(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
|
||||
do {
|
||||
return try JSONDecoder().decode(YMEnvelope<T>.self, from: data).result
|
||||
} catch {
|
||||
let raw = String(data: data, encoding: .utf8)?.prefix(300) ?? ""
|
||||
throw YMError.decoding("\(error)\n\(raw)")
|
||||
}
|
||||
}
|
||||
|
||||
private func get<T: Decodable>(
|
||||
_ path: String,
|
||||
query: [String: String] = [:],
|
||||
as type: T.Type
|
||||
) async throws -> T {
|
||||
guard token != nil else { throw YMError.notAuthorized }
|
||||
var request = URLRequest(url: makeURL(path, query: query))
|
||||
headers(for: &request)
|
||||
return try decode(type, from: try await perform(request))
|
||||
}
|
||||
|
||||
/// Percent-encodes everything outside the unreserved set, so "+", "/" and
|
||||
/// "=" from base64 signatures survive the trip.
|
||||
private static func escape(_ value: String) -> String {
|
||||
let unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
+ "abcdefghijklmnopqrstuvwxyz0123456789-._~")
|
||||
return value.addingPercentEncoding(withAllowedCharacters: unreserved) ?? value
|
||||
}
|
||||
|
||||
private func formBody(_ fields: [String: String]) -> Data {
|
||||
fields
|
||||
.map { "\(Self.escape($0.key))=\(Self.escape($0.value))" }
|
||||
.joined(separator: "&")
|
||||
.data(using: .utf8) ?? Data()
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func post<T: Decodable>(
|
||||
_ path: String,
|
||||
query: [String: String] = [:],
|
||||
form: [String: String],
|
||||
as type: T.Type
|
||||
) async throws -> T {
|
||||
guard token != nil else { throw YMError.notAuthorized }
|
||||
var request = URLRequest(url: makeURL(path, query: query))
|
||||
request.httpMethod = "POST"
|
||||
headers(for: &request)
|
||||
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
request.httpBody = formBody(form)
|
||||
return try decode(type, from: try await perform(request))
|
||||
}
|
||||
|
||||
private func postIgnoringResult(
|
||||
_ path: String,
|
||||
query: [String: String] = [:],
|
||||
form: [String: String]
|
||||
) async throws {
|
||||
guard token != nil else { throw YMError.notAuthorized }
|
||||
var request = URLRequest(url: makeURL(path, query: query))
|
||||
request.httpMethod = "POST"
|
||||
headers(for: &request)
|
||||
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||
request.httpBody = formBody(form)
|
||||
_ = try await perform(request)
|
||||
}
|
||||
|
||||
// MARK: - Account
|
||||
|
||||
@discardableResult
|
||||
func accountStatus() async throws -> AccountStatus {
|
||||
let status = try await get("account/status", as: AccountStatus.self)
|
||||
uid = status.account.uid
|
||||
return status
|
||||
}
|
||||
|
||||
private func requireUID() async throws -> Int64 {
|
||||
if let uid { return uid }
|
||||
_ = try await accountStatus()
|
||||
guard let uid else { throw YMError.notAuthorized }
|
||||
return uid
|
||||
}
|
||||
|
||||
// MARK: - Library
|
||||
|
||||
/// Keys for the whole library, newest first. Hydrating them is the caller's
|
||||
/// job so a large collection can appear a batch at a time.
|
||||
func likedTrackKeys() async throws -> [String] {
|
||||
let uid = try await requireUID()
|
||||
let library = try await get("users/\(uid)/likes/tracks", as: LibraryTracks.self)
|
||||
return library.library.tracks.map { item in
|
||||
if let album = item.albumId, !album.isEmpty { return "\(item.id.value):\(album.value)" }
|
||||
return item.id.value
|
||||
}
|
||||
}
|
||||
|
||||
/// Just the ids, for telling at a glance whether a track is liked.
|
||||
func likedTrackIDs() async throws -> Set<String> {
|
||||
let uid = try await requireUID()
|
||||
let library = try await get("users/\(uid)/likes/tracks", as: LibraryTracks.self)
|
||||
return Set(library.library.tracks.map(\.id.value))
|
||||
}
|
||||
|
||||
func tracks(keys: [String]) async throws -> [Track] {
|
||||
guard !keys.isEmpty else { return [] }
|
||||
var result: [Track] = []
|
||||
for chunk in stride(from: 0, to: keys.count, by: 100).map({
|
||||
Array(keys[$0 ..< min($0 + 100, keys.count)])
|
||||
}) {
|
||||
let batch = try await post(
|
||||
"tracks",
|
||||
form: ["track-ids": chunk.joined(separator: ","), "with-positions": "True"],
|
||||
as: [Track].self
|
||||
)
|
||||
result.append(contentsOf: batch)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func playlists() async throws -> [Playlist] {
|
||||
let uid = try await requireUID()
|
||||
return try await get("users/\(uid)/playlists/list", as: [Playlist].self)
|
||||
}
|
||||
|
||||
func playlist(ownerUID: Int64, kind: String) async throws -> Playlist {
|
||||
try await get("users/\(ownerUID)/playlists/\(kind)", as: Playlist.self)
|
||||
}
|
||||
|
||||
func setLiked(_ liked: Bool, trackID: String) async throws {
|
||||
let uid = try await requireUID()
|
||||
let action = liked ? "add-multiple" : "remove"
|
||||
try await postIgnoringResult(
|
||||
"users/\(uid)/likes/tracks/\(action)",
|
||||
form: ["track-ids": trackID]
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Rotor
|
||||
|
||||
func rotorDashboard() async throws -> RotorDashboard {
|
||||
try await get("rotor/stations/dashboard", as: RotorDashboard.self)
|
||||
}
|
||||
|
||||
func rotorStations() async throws -> [DashboardStation] {
|
||||
try await get("rotor/stations/list", query: ["language": "ru"], as: [DashboardStation].self)
|
||||
}
|
||||
|
||||
func rotorTracks(station: String, queue: String? = nil) async throws -> StationTracksResult {
|
||||
var query = ["settings2": "True"]
|
||||
if let queue { query = ["queue": queue] }
|
||||
return try await get("rotor/station/\(station)/tracks", query: query, as: StationTracksResult.self)
|
||||
}
|
||||
|
||||
func rotorFeedback(
|
||||
station: String,
|
||||
type: String,
|
||||
trackID: String? = nil,
|
||||
batchID: String? = nil,
|
||||
totalPlayedSeconds: Double? = nil,
|
||||
from: String? = nil
|
||||
) async {
|
||||
var form = ["type": type, "timestamp": String(Date().timeIntervalSince1970)]
|
||||
if let trackID { form["trackId"] = trackID }
|
||||
if let from { form["from"] = from }
|
||||
if let totalPlayedSeconds { form["totalPlayedSeconds"] = String(format: "%.1f", totalPlayedSeconds) }
|
||||
let query = batchID.map { ["batch-id": $0] } ?? [:]
|
||||
// Feedback is fire-and-forget: a failure must never interrupt playback.
|
||||
try? await postIgnoringResult("rotor/station/\(station)/feedback", query: query, form: form)
|
||||
}
|
||||
|
||||
// MARK: - Search
|
||||
|
||||
func search(_ text: String, type: String = "all", page: Int = 0) async throws -> SearchResult {
|
||||
try await get(
|
||||
"search",
|
||||
query: [
|
||||
"text": text,
|
||||
"type": type,
|
||||
"page": String(page),
|
||||
"nocorrect": "False",
|
||||
"playlist-in-best": "True",
|
||||
],
|
||||
as: SearchResult.self
|
||||
)
|
||||
}
|
||||
|
||||
func album(albumID: String) async throws -> Album {
|
||||
try await get("albums/\(albumID)/with-tracks", as: Album.self)
|
||||
}
|
||||
|
||||
func albumTracks(albumID: String) async throws -> [Track] {
|
||||
(try await album(albumID: albumID).volumes ?? []).flatMap { $0 }
|
||||
}
|
||||
|
||||
/// One request covers the whole artist page: header, top tracks, albums,
|
||||
/// compilations and lookalikes.
|
||||
func artistBriefInfo(artistID: String) async throws -> ArtistBriefInfo {
|
||||
try await get("artists/\(artistID)/brief-info", as: ArtistBriefInfo.self)
|
||||
}
|
||||
|
||||
func artistTracks(artistID: String, limit: Int = 60) async throws -> [Track] {
|
||||
let result = try await get(
|
||||
"artists/\(artistID)/tracks",
|
||||
query: ["page": "0", "page-size": String(limit)],
|
||||
as: ArtistTracks.self
|
||||
)
|
||||
return result.tracks ?? []
|
||||
}
|
||||
|
||||
// MARK: - Lyrics
|
||||
|
||||
func lyrics(trackID: String, query: [String: String]) async throws -> LyricsMeta {
|
||||
try await get("tracks/\(trackID)/lyrics", query: query, as: LyricsMeta.self)
|
||||
}
|
||||
|
||||
/// Plain GET with no auth headers — lyrics live behind a presigned S3 URL
|
||||
/// that rejects an extra Authorization header.
|
||||
func fetchPlain(_ url: URL) async throws -> Data {
|
||||
try await perform(URLRequest(url: url))
|
||||
}
|
||||
|
||||
// MARK: - Stream resolution
|
||||
|
||||
func downloadInfos(trackID: String) async throws -> [DownloadInfo] {
|
||||
try await get("tracks/\(trackID)/download-info", as: [DownloadInfo].self)
|
||||
}
|
||||
|
||||
/// Fetches the little XML document the legacy scheme points at.
|
||||
func fetchRaw(_ url: URL) async throws -> Data {
|
||||
var request = URLRequest(url: url)
|
||||
headers(for: &request)
|
||||
return try await perform(request)
|
||||
}
|
||||
|
||||
func getFileInfoJSON(query: [String: String]) async throws -> Data {
|
||||
guard token != nil else { throw YMError.notAuthorized }
|
||||
var request = URLRequest(url: makeURL("get-file-info", query: query))
|
||||
headers(for: &request)
|
||||
request.setValue("YandexMusicWebNext/1.0.0", forHTTPHeaderField: "X-Yandex-Music-Client")
|
||||
request.setValue("1", forHTTPHeaderField: "X-Yandex-Music-Without-Invocation-Info")
|
||||
request.setValue("https://music.yandex.ru", forHTTPHeaderField: "Origin")
|
||||
request.setValue("https://music.yandex.ru/", forHTTPHeaderField: "Referer")
|
||||
return try await perform(request)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user