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:
2026-09-17 20:38:19 +03:00
commit acd50280bc
70 changed files with 4588 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
import Foundation
/// Yandex OAuth Device Flow — the only sane way to sign in on a TV: the code is
/// shown on screen, the user confirms it on a phone at https://ya.ru/device.
enum DeviceAuth {
/// Public OAuth credentials of the official Yandex Music Android client.
private static let clientID = "23cabbbdc6cd418abb4b39c32c41195d"
private static let clientSecret = "53bc75238f0c4d08a118e51fe9203300"
private static let oauthBase = URL(string: "https://oauth.yandex.ru")!
enum PollResult {
case pending
case token(String)
}
private static func post(_ path: String, fields: [String: String]) async throws -> (Int, Data) {
var request = URLRequest(url: oauthBase.appendingPathComponent(path))
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = fields
.map { key, value in
let escape: (String) -> String = {
$0.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? $0
}
return "\(escape(key))=\(escape(value))"
}
.joined(separator: "&")
.data(using: .utf8)
do {
let (data, response) = try await URLSession.shared.data(for: request)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
return (status, data)
} catch {
throw YMError.transport(error)
}
}
static func requestCode(deviceName: String = "Apple TV") async throws -> DeviceCode {
let deviceID = String(UUID().uuidString.replacingOccurrences(of: "-", with: "").prefix(16))
let (status, data) = try await post("device/code", fields: [
"client_id": clientID,
"device_id": deviceID,
"device_name": deviceName,
])
guard status == 200 else {
throw YMError.http(status: status, body: String(data: data, encoding: .utf8) ?? "")
}
do {
return try JSONDecoder().decode(DeviceCode.self, from: data)
} catch {
throw YMError.decoding("device/code: \(error)")
}
}
static func poll(deviceCode: String) async throws -> PollResult {
let (status, data) = try await post("token", fields: [
"grant_type": "device_code",
"code": deviceCode,
"client_id": clientID,
"client_secret": clientSecret,
])
if status == 200 {
do {
return .token(try JSONDecoder().decode(OAuthToken.self, from: data).accessToken)
} catch {
throw YMError.decoding("token: \(error)")
}
}
let body = String(data: data, encoding: .utf8) ?? ""
if body.contains("authorization_pending") { return .pending }
if body.contains("expired_token") {
throw YMError.message("Код истёк — запросите новый.")
}
if body.contains("access_denied") {
throw YMError.message("Вход отклонён.")
}
throw YMError.http(status: status, body: body)
}
}
+132
View File
@@ -0,0 +1,132 @@
import Foundation
struct LyricsLine: Identifiable, Hashable {
let id: Int
/// Start time in seconds, or nil when the track only has plain text.
let time: Double?
let text: String
var isBlank: Bool { text.trimmingCharacters(in: .whitespaces).isEmpty }
}
struct Lyrics: Equatable {
let lines: [LyricsLine]
let synced: Bool
let writers: [String]
static func == (lhs: Lyrics, rhs: Lyrics) -> Bool {
lhs.synced == rhs.synced && lhs.lines == rhs.lines
}
/// Index of the line that should be highlighted at `time`.
func activeIndex(at time: Double) -> Int? {
guard synced else { return nil }
var result: Int?
for line in lines {
guard let start = line.time else { continue }
if start <= time + 0.15 { result = line.id } else { break }
}
return result
}
}
enum LyricsService {
/// Signing key taken from the Android client; unrelated to the web player key.
private static let signKey = "p93jhgh689SBReK6ghtw62"
/// Timed LRC only. A track whose lyrics carry no timestamps is treated as
/// having none.
static func load(trackID: String) async throws -> Lyrics {
let lyrics = try await fetch(trackID: trackID, format: "LRC")
guard lyrics.synced else { throw YMError.message("lyrics are not timed") }
return lyrics
}
private static func fetch(trackID: String, format: String) async throws -> Lyrics {
// The signature uses the bare numeric id, without any ":album" suffix.
let numericID = trackID.split(separator: ":").first.map(String.init) ?? trackID
let timestamp = String(Int(Date().timeIntervalSince1970))
let sign = Crypto.hmacSHA256Base64(
message: numericID + timestamp,
key: signKey,
stripPadding: false
)
let meta = try await YMClient.shared.lyrics(
trackID: numericID,
query: ["format": format, "timeStamp": timestamp, "sign": sign]
)
guard let urlString = meta.downloadUrl, let url = URL(string: urlString) else {
throw YMError.message("У трека нет текста")
}
let data = try await YMClient.shared.fetchPlain(url)
guard let text = String(data: data, encoding: .utf8), !text.isEmpty else {
throw YMError.message("Пустой текст")
}
return parse(text, writers: meta.writers ?? [])
}
static func parse(_ raw: String, writers: [String]) -> Lyrics {
var timed: [(Double, String)] = []
var plain: [String] = []
for rawLine in raw.components(separatedBy: .newlines) {
let line = rawLine.trimmingCharacters(in: .whitespaces)
if line.isEmpty {
plain.append("")
continue
}
let stamps = timestamps(in: line)
if stamps.isEmpty {
// Skip LRC metadata tags like [ar:...] but keep real lyric lines.
if line.hasPrefix("["), line.hasSuffix("]"), line.contains(":") { continue }
plain.append(line)
} else {
let text = line.replacingOccurrences(
of: "\\[\\d+:\\d+(?:[.:]\\d+)?\\]",
with: "",
options: .regularExpression
).trimmingCharacters(in: .whitespaces)
for stamp in stamps { timed.append((stamp, text)) }
}
}
if !timed.isEmpty {
let sorted = timed.sorted { $0.0 < $1.0 }
return Lyrics(
lines: sorted.enumerated().map { LyricsLine(id: $0.offset, time: $0.element.0, text: $0.element.1) },
synced: true,
writers: writers
)
}
// Collapse runs of blank lines so plain text does not sprawl.
var compact: [String] = []
for line in plain where !(line.isEmpty && compact.last?.isEmpty == true) {
compact.append(line)
}
return Lyrics(
lines: compact.enumerated().map { LyricsLine(id: $0.offset, time: nil, text: $0.element) },
synced: false,
writers: writers
)
}
private static func timestamps(in line: String) -> [Double] {
let pattern = try! NSRegularExpression(pattern: "\\[(\\d+):(\\d+)(?:[.:](\\d+))?\\]")
let range = NSRange(line.startIndex ..< line.endIndex, in: line)
return pattern.matches(in: line, range: range).compactMap { match in
func group(_ index: Int) -> Double? {
guard let r = Range(match.range(at: index), in: line) else { return nil }
return Double(line[r])
}
guard let minutes = group(1), let seconds = group(2) else { return nil }
var total = minutes * 60 + seconds
if let fraction = group(3) {
let digits = String(Int(fraction)).count
total += fraction / pow(10, Double(max(digits, 1)))
}
return total
}
}
}
+179
View File
@@ -0,0 +1,179 @@
import Foundation
enum StreamMethod: String {
/// `GET /get-file-info` signed with HMAC-SHA256 — the scheme the current web
/// player uses. Returns unencrypted `strm.yandex.net` URLs (FLAC / MP3 320).
case fileInfo
/// `GET /tracks/{id}/download-info` + XML + MD5 sign — the older scheme the
/// mobile clients use. Returns MP3 URLs.
case downloadInfo
}
struct ResolvedStream {
let url: URL
let method: StreamMethod
let codec: String?
}
/// Turns a track id into a playable URL.
///
/// Two independent signing schemes exist and Yandex rotates which one works, so
/// both are implemented and we fail over between them.
enum StreamResolver {
/// App-level secret from the music-web frontend (`player.secretKey.web`).
/// Stable across users; when Yandex ships a new one, get-file-info answers
/// "not-allowed" and playback falls through to the MP3 scheme. Refresh with
/// tools/check-api.sh.
static let webSecret = "7tvSmFbyf5hJnIHhCimDDD"
private static let legacySalt = "XGRlBW9FXlekgbPrRHuSiA"
static func resolve(trackID: String, preferring method: StreamMethod) async throws -> ResolvedStream {
let order: [StreamMethod] = method == .fileInfo ? [.fileInfo, .downloadInfo] : [.downloadInfo, .fileInfo]
var lastError: Error = YMError.message("Не удалось получить ссылку на трек")
for candidate in order {
do {
switch candidate {
case .fileInfo:
return try await resolveFileInfo(trackID: trackID)
case .downloadInfo:
return try await resolveDownloadInfo(trackID: trackID)
}
} catch {
log.error("stream \(candidate.rawValue) failed for \(trackID): \(String(describing: error))")
lastError = error
}
}
throw lastError
}
// MARK: - get-file-info
private struct FileInfoResponse: Decodable {
struct Info: Decodable {
let trackId: FlexID?
let quality: String?
let codec: String?
let url: String?
let urls: [String]?
}
struct Wrapped: Decodable {
let downloadInfo: Info?
}
let downloadInfo: Info?
let result: Wrapped?
let name: String?
let message: String?
var info: Info? { downloadInfo ?? result?.downloadInfo }
}
private static func resolveFileInfo(trackID: String) async throws -> ResolvedStream {
let ts = String(Int(Date().timeIntervalSince1970))
let quality = "lossless"
let codecs = "flac,aac,he-aac,mp3"
let transport = "raw"
// The signature joins the codec list WITHOUT separators, while the URL
// keeps the commas. Getting this wrong yields 403 "not-allowed".
let message = ts + trackID + quality + codecs.replacingOccurrences(of: ",", with: "") + transport
let sign = Crypto.hmacSHA256Base64(message: message, key: webSecret)
let data = try await YMClient.shared.getFileInfoJSON(query: [
"ts": ts,
"trackId": trackID,
"quality": quality,
"codecs": codecs,
"transports": transport,
"sign": sign,
])
let decoded: FileInfoResponse
do {
decoded = try JSONDecoder().decode(FileInfoResponse.self, from: data)
} catch {
let raw = String(data: data, encoding: .utf8)?.prefix(200) ?? ""
throw YMError.decoding("get-file-info: \(error)\n\(raw)")
}
if decoded.name == "track-download-info-error" {
throw YMError.message("get-file-info отклонён: \(decoded.message ?? "неизвестно"). Вероятно, сменился секретный ключ веб-плеера.")
}
guard let info = decoded.info,
let raw = info.url ?? info.urls?.first,
let url = URL(string: raw.hasPrefix("//") ? "https:" + raw : raw)
else {
throw YMError.message("get-file-info не вернул ссылку")
}
return ResolvedStream(url: url, method: .fileInfo, codec: info.codec)
}
// MARK: - download-info
private static func resolveDownloadInfo(trackID: String) async throws -> ResolvedStream {
let infos = try await YMClient.shared.downloadInfos(trackID: trackID)
let best = infos
.filter { ($0.preview ?? false) == false }
.max(by: { ($0.bitrateInKbps ?? 0) < ($1.bitrateInKbps ?? 0) }) ?? infos.first
guard let best, let infoURLString = best.downloadInfoUrl,
let infoURL = URL(string: infoURLString)
else {
throw YMError.message("download-info пуст (трек недоступен в вашем регионе или нет Плюса)")
}
let xml = try await YMClient.shared.fetchRaw(infoURL)
let fields = DownloadInfoXML.parse(xml)
guard let host = fields["host"], let path = fields["path"],
let ts = fields["ts"], let s = fields["s"]
else {
throw YMError.message("Не удалось разобрать XML download-info")
}
let sign = Crypto.md5Hex(legacySalt + String(path.dropFirst()) + s)
guard let url = URL(string: "https://\(host)/get-mp3/\(sign)/\(ts)\(path)") else {
throw YMError.message("Некорректная прямая ссылка")
}
return ResolvedStream(url: url, method: .downloadInfo, codec: best.codec)
}
}
/// Minimal reader for `<download-info><host/><path/><ts/><s/></download-info>`.
private final class DownloadInfoXML: NSObject, XMLParserDelegate {
private var fields: [String: String] = [:]
private var buffer = ""
static func parse(_ data: Data) -> [String: String] {
let handler = DownloadInfoXML()
let parser = XMLParser(data: data)
parser.delegate = handler
parser.parse()
return handler.fields
}
func parser(
_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String] = [:]
) {
buffer = ""
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
buffer += string
}
func parser(
_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?
) {
let value = buffer.trimmingCharacters(in: .whitespacesAndNewlines)
if !value.isEmpty { fields[elementName] = value }
buffer = ""
}
}
+344
View File
@@ -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)
}
}
+363
View File
@@ -0,0 +1,363 @@
import Foundation
/// The API is inconsistent about whether ids come back as JSON strings or numbers,
/// so every id goes through this.
struct FlexID: Codable, Hashable, CustomStringConvertible {
let value: String
init(_ value: String) { self.value = value }
init(from decoder: Decoder) throws {
let c = try decoder.singleValueContainer()
if let s = try? c.decode(String.self) {
value = s
} else if let i = try? c.decode(Int64.self) {
value = String(i)
} else if let d = try? c.decode(Double.self) {
value = String(Int64(d))
} else {
value = ""
}
}
func encode(to encoder: Encoder) throws {
var c = encoder.singleValueContainer()
try c.encode(value)
}
var description: String { value }
var isEmpty: Bool { value.isEmpty }
}
// MARK: - Envelope
struct YMEnvelope<T: Decodable>: Decodable {
let result: T
}
// MARK: - Account
struct AccountStatus: Decodable {
struct Account: Decodable {
let uid: Int64?
let login: String?
let displayName: String?
let fullName: String?
}
struct Plus: Decodable {
let hasPlus: Bool?
}
let account: Account
let plus: Plus?
}
// MARK: - Track
struct Artist: Decodable, Hashable, Identifiable {
struct Counts: Decodable, Hashable {
let tracks: Int?
let directAlbums: Int?
}
struct Description: Decodable, Hashable {
let text: String?
}
let id: FlexID
let name: String
let cover: Cover?
let ogImage: String?
let genres: [String]?
let counts: Counts?
let description: Description?
func coverURL(size: Int) -> URL? {
YMImage.url(cover?.uri ?? ogImage, size: size)
}
/// "12 альбомов · 148 треков", skipping whichever half is missing.
var countsLine: String? {
var parts: [String] = []
if let albums = counts?.directAlbums, albums > 0 { parts.append("\(albums) альбомов") }
if let tracks = counts?.tracks, tracks > 0 { parts.append("\(tracks) треков") }
return parts.isEmpty ? nil : parts.joined(separator: " · ")
}
}
struct Album: Decodable, Hashable, Identifiable {
let id: FlexID
let title: String?
let version: String?
let coverUri: String?
let ogImage: String?
let year: Int?
let genre: String?
let type: String?
let shortDescription: String?
let artists: [Artist]?
let trackCount: Int?
let volumes: [[Track]]?
var displayTitle: String {
let base = title ?? "Альбом"
guard let version, !version.isEmpty else { return base }
return "\(base) (\(version))"
}
var artistNames: String {
let names = (artists ?? []).map(\.name).filter { !$0.isEmpty }
return names.isEmpty ? "Разные исполнители" : names.joined(separator: ", ")
}
/// "Сингл · 2021 · 3 трека"
var subtitleLine: String {
var parts: [String] = []
switch type {
case "single": parts.append("Сингл")
case "compilation": parts.append("Сборник")
case "ep": parts.append("EP")
default: break
}
if let year { parts.append(String(year)) }
if let trackCount, trackCount > 0 { parts.append("\(trackCount) треков") }
return parts.joined(separator: " · ")
}
func coverURL(size: Int) -> URL? { YMImage.url(coverUri ?? ogImage, size: size) }
}
struct Cover: Decodable, Hashable {
let uri: String?
let itemsUri: [String]?
let type: String?
}
struct Track: Decodable, Hashable, Identifiable {
let id: FlexID
let realId: FlexID?
let title: String?
let version: String?
let available: Bool?
let durationMs: Int?
let coverUri: String?
let artists: [Artist]?
let albums: [Album]?
let lyricsInfo: LyricsInfo?
var trackID: String { (realId?.isEmpty == false ? realId!.value : id.value) }
var displayTitle: String {
guard let title, !title.isEmpty else { return "Без названия" }
guard let version, !version.isEmpty else { return title }
return "\(title) (\(version))"
}
var artistNames: String {
let names = (artists ?? []).map(\.name).filter { !$0.isEmpty }
return names.isEmpty ? "Неизвестный исполнитель" : names.joined(separator: ", ")
}
var albumID: String? { albums?.first?.id.value }
var duration: TimeInterval { Double(durationMs ?? 0) / 1000 }
func coverURL(size: Int) -> URL? { YMImage.url(coverUri, size: size) }
/// `trackId:albumId` is what the API wants when a track belongs to an album.
var trackAlbumKey: String {
if let albumID, !albumID.isEmpty { return "\(trackID):\(albumID)" }
return trackID
}
}
/// Track covers are templated paths ending in `%%`; the size is substituted in.
enum YMImage {
static func url(_ uri: String?, size: Int) -> URL? {
guard var uri, !uri.isEmpty else { return nil }
uri = uri.replacingOccurrences(of: "%%", with: "\(size)x\(size)")
if !uri.hasPrefix("http") { uri = "https://" + uri }
return URL(string: uri)
}
}
// MARK: - Lyrics
struct LyricsInfo: Decodable, Hashable {
let hasAvailableSyncLyrics: Bool?
let hasAvailableTextLyrics: Bool?
/// Only timed lyrics are of use; plain text is treated as none.
var hasSynced: Bool { hasAvailableSyncLyrics ?? false }
}
struct LyricsMeta: Decodable {
let downloadUrl: String?
let writers: [String]?
}
// MARK: - Likes
struct LibraryTracks: Decodable {
struct Item: Decodable {
let id: FlexID
let albumId: FlexID?
}
struct Library: Decodable {
let tracks: [Item]
}
let library: Library
}
// MARK: - Playlists
struct Playlist: Decodable, Hashable, Identifiable {
struct Owner: Decodable, Hashable {
let uid: Int64?
let login: String?
let name: String?
}
struct TrackItem: Decodable, Hashable {
let id: FlexID?
let track: Track?
}
let kind: FlexID
let title: String?
let trackCount: Int?
let cover: Cover?
let ogImage: String?
let owner: Owner?
let description: String?
let tracks: [TrackItem]?
let uid: Int64?
let playlistUuid: String?
var id: String { "\(owner?.uid ?? uid ?? 0):\(kind.value)" }
var coverURI: String? {
if let uri = cover?.uri, !uri.isEmpty { return uri }
if let first = cover?.itemsUri?.first, !first.isEmpty { return first }
if let ogImage, !ogImage.isEmpty { return ogImage }
return nil
}
func coverURL(size: Int) -> URL? { YMImage.url(coverURI, size: size) }
}
// MARK: - Rotor
struct StationID: Decodable, Hashable {
let type: String
let tag: String
var stringValue: String { "\(type):\(tag)" }
}
struct Station: Decodable, Hashable {
let id: StationID
let name: String?
let icon: StationIcon?
let fullImageUrl: String?
let mtsFullImageUrl: String?
}
struct StationIcon: Decodable, Hashable {
let backgroundColor: String?
let imageUrl: String?
}
struct DashboardStation: Decodable {
let station: Station
}
struct RotorDashboard: Decodable {
let stations: [DashboardStation]
}
struct StationSequenceItem: Decodable {
let track: Track?
let liked: Bool?
}
struct StationTracksResult: Decodable {
let id: StationID?
let sequence: [StationSequenceItem]
let batchId: String?
}
struct ArtistBriefInfo: Decodable {
let artist: Artist?
let albums: [Album]?
let alsoAlbums: [Album]?
let lastReleases: [Album]?
let popularTracks: [Track]?
let similarArtists: [Artist]?
}
struct ArtistTracks: Decodable {
let tracks: [Track]?
}
// MARK: - Search
struct SearchResult: Decodable {
struct Page<T: Decodable>: Decodable {
let results: [T]?
let total: Int?
}
let tracks: Page<Track>?
let albums: Page<Album>?
let artists: Page<Artist>?
let playlists: Page<Playlist>?
let best: Best?
struct Best: Decodable {
let type: String?
}
}
// MARK: - Download info (legacy scheme)
struct DownloadInfo: Decodable {
let codec: String?
let bitrateInKbps: Int?
let downloadInfoUrl: String?
let direct: Bool?
let preview: Bool?
}
// MARK: - Device auth
struct DeviceCode: Decodable {
let deviceCode: String
let userCode: String
let verificationUrl: String
let expiresIn: Int
let interval: Int?
enum CodingKeys: String, CodingKey {
case deviceCode = "device_code"
case userCode = "user_code"
case verificationUrl = "verification_url"
case expiresIn = "expires_in"
case interval
}
}
struct OAuthToken: Decodable {
let accessToken: String
let expiresIn: Int?
let tokenType: String?
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case expiresIn = "expires_in"
case tokenType = "token_type"
}
}