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) } }