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.
@@ -0,0 +1,6 @@
|
|||||||
|
YaMusek.xcodeproj/
|
||||||
|
build/
|
||||||
|
DerivedData/
|
||||||
|
.DS_Store
|
||||||
|
*.xcuserstate
|
||||||
|
tools/.autorefresh.env
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# YaMusek
|
||||||
|
|
||||||
|
Неофициальный клиент Яндекс.Музыки для Apple TV (tvOS 17+). SwiftUI, AVPlayer,
|
||||||
|
вход через Yandex OAuth Device Flow.
|
||||||
|
|
||||||
|
Официального API у Яндекс.Музыки нет. Приложение работает с тем же закрытым
|
||||||
|
API (`api.music.yandex.net`), что и веб-плеер с мобильными клиентами, поэтому
|
||||||
|
Яндекс может сломать его без предупреждения.
|
||||||
|
|
||||||
|
## Возможности
|
||||||
|
|
||||||
|
- **Волна** — «Моя волна» и станции ротора с полной обратной связью
|
||||||
|
(`radioStarted` / `trackStarted` / `trackFinished` / `skip`), бесконечной
|
||||||
|
подгрузкой и продолжением с места, где остановились.
|
||||||
|
- **Мне нравится** — вся коллекция, порциями по 100 треков.
|
||||||
|
- **Поиск** — системная сцена поиска tvOS: исполнители, треки, альбомы.
|
||||||
|
- **Страницы исполнителей и альбомов** — популярное, дискография, сборники,
|
||||||
|
похожие исполнители, волна по артисту.
|
||||||
|
- **Плеер** — синхронный текст с отсчётом перед первой строкой, полоса
|
||||||
|
перемотки с ускорением, лайк, фон из цветов обложки.
|
||||||
|
- **Системный Now Playing** — трек в Пункте управления и поверх заставки,
|
||||||
|
управление с пульта, фоновое воспроизведение.
|
||||||
|
|
||||||
|
## Требования
|
||||||
|
|
||||||
|
- macOS с Xcode 26, `brew install xcodegen`.
|
||||||
|
- Apple TV с tvOS 17+, спаренный с Xcode.
|
||||||
|
- Активная подписка **Яндекс Плюс** — без неё API отдаёт только превью.
|
||||||
|
|
||||||
|
## Сборка и установка
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./tools/install.sh <TEAM_ID> # собрать и поставить на Apple TV
|
||||||
|
./tools/install-autorefresh.sh <TEAM_ID> # ежедневная переподписка (free-профиль живёт 7 дней)
|
||||||
|
./tools/check-api.sh <OAUTH_TOKEN> # диагностика API с Mac
|
||||||
|
./tools/make-assets.swift # перерисовать иконки
|
||||||
|
```
|
||||||
|
|
||||||
|
`TEAM_ID` — из `security find-identity -v -p codesigning`.
|
||||||
|
Проект генерируется XcodeGen из `project.yml`, сам `.xcodeproj` не коммитится.
|
||||||
|
|
||||||
|
## Вход
|
||||||
|
|
||||||
|
При первом запуске на экране код и QR. Открыть `ya.ru/device` на телефоне,
|
||||||
|
ввести код — Apple TV подхватит токен и сохранит его в Keychain.
|
||||||
|
|
||||||
|
## Структура
|
||||||
|
|
||||||
|
```
|
||||||
|
Sources/App/ точка входа, состояние аккаунта
|
||||||
|
Sources/Core/ Keychain, MD5/HMAC, логирование
|
||||||
|
Sources/Network/ клиент API, модели, device flow, резолвер потоков, тексты
|
||||||
|
Sources/Player/ очередь, ротор, системный Now Playing
|
||||||
|
Sources/Views/ экраны, палитра фона
|
||||||
|
Sources/Views/Player/ экран плеера, полоса перемотки, текст
|
||||||
|
Resources/ иконка и Top Shelf
|
||||||
|
tools/ сборка, установка, диагностика
|
||||||
|
```
|
||||||
|
|
||||||
|
## Потоки
|
||||||
|
|
||||||
|
Ссылки на аудио подписываются двумя схемами, приложение использует первую и
|
||||||
|
падает на вторую при отказе:
|
||||||
|
|
||||||
|
| Схема | Эндпоинт | Подпись |
|
||||||
|
|---|---|---|
|
||||||
|
| Lossless | `GET /get-file-info` | HMAC-SHA256 ключом веб-плеера |
|
||||||
|
| MP3 320 | `GET /tracks/{id}/download-info` + XML | MD5 с солью |
|
||||||
|
|
||||||
|
Когда Яндекс выкатывает новый фронтенд, ключ веб-плеера меняется и первая схема
|
||||||
|
отвечает `not-allowed`. Новый ключ лежит в JS-бандле `music.yandex.ru`
|
||||||
|
(`secretKey:{web:"..."}`), подставляется в `StreamResolver.webSecret`.
|
||||||
|
|
||||||
|
## Оговорки
|
||||||
|
|
||||||
|
Личный проект для собственного аккаунта. Использует незадокументированный API,
|
||||||
|
в App Store такое не пройдёт. Публичные OAuth-креды Android-клиента и ключ
|
||||||
|
подписи веб-плеера взяты из открытых проектов
|
||||||
|
[MarshalX/yandex-music-api](https://github.com/MarshalX/yandex-music-api) и
|
||||||
|
[yt-dlp-yandex-music-plugin](https://github.com/fgsfds1/yt-dlp-yandex-music-plugin).
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "back@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 817 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"layers" : [
|
||||||
|
{ "filename" : "Front.imagestacklayer" },
|
||||||
|
{ "filename" : "Middle.imagestacklayer" },
|
||||||
|
{ "filename" : "Back.imagestacklayer" }
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "front@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "middle@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 42 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "back@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "back@2x.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 330 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"layers" : [
|
||||||
|
{ "filename" : "Front.imagestacklayer" },
|
||||||
|
{ "filename" : "Middle.imagestacklayer" },
|
||||||
|
{ "filename" : "Back.imagestacklayer" }
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "front@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "front@2x.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "middle@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "middle@2x.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 8.9 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"assets" : [
|
||||||
|
{ "filename" : "App Icon - App Store.imagestack", "idiom" : "tv", "role" : "primary-app-icon", "size" : "1280x768" },
|
||||||
|
{ "filename" : "App Icon.imagestack", "idiom" : "tv", "role" : "primary-app-icon", "size" : "400x240" },
|
||||||
|
{ "filename" : "Top Shelf Image Wide.imageset", "idiom" : "tv", "role" : "top-shelf-image-wide", "size" : "2320x720" },
|
||||||
|
{ "filename" : "Top Shelf Image.imageset", "idiom" : "tv", "role" : "top-shelf-image", "size" : "1920x720" }
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "top-shelf-image-wide@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "top-shelf-image-wide@2x.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 4.8 MiB |
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "top-shelf-image@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "top-shelf-image@2x.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 4.0 MiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "launch@1x.png",
|
||||||
|
"scale" : "1x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "launch@2x.png",
|
||||||
|
"scale" : "2x"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 1.6 MiB |
|
After Width: | Height: | Size: 6.0 MiB |
@@ -0,0 +1,35 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleDevelopmentRegion</key>
|
||||||
|
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||||
|
<key>CFBundleDisplayName</key>
|
||||||
|
<string>YaMusek</string>
|
||||||
|
<key>CFBundleExecutable</key>
|
||||||
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
|
<key>CFBundleIdentifier</key>
|
||||||
|
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||||
|
<key>CFBundleInfoDictionaryVersion</key>
|
||||||
|
<string>6.0</string>
|
||||||
|
<key>CFBundleName</key>
|
||||||
|
<string>$(PRODUCT_NAME)</string>
|
||||||
|
<key>CFBundlePackageType</key>
|
||||||
|
<string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key>
|
||||||
|
<string>1.0</string>
|
||||||
|
<key>CFBundleVersion</key>
|
||||||
|
<string>1</string>
|
||||||
|
<key>NSAppTransportSecurity</key>
|
||||||
|
<dict>
|
||||||
|
<key>NSAllowsArbitraryLoads</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
<key>UIBackgroundModes</key>
|
||||||
|
<array>
|
||||||
|
<string>audio</string>
|
||||||
|
</array>
|
||||||
|
<key>UIUserInterfaceStyle</key>
|
||||||
|
<string>Dark</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import Foundation
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
final class AppState: ObservableObject {
|
||||||
|
@Published var token: String?
|
||||||
|
@Published var accountName: String = ""
|
||||||
|
@Published var isBooting = true
|
||||||
|
|
||||||
|
var isAuthorized: Bool { token != nil }
|
||||||
|
|
||||||
|
init() {
|
||||||
|
token = Keychain.get("token")
|
||||||
|
}
|
||||||
|
|
||||||
|
func boot() async {
|
||||||
|
isBooting = true
|
||||||
|
defer { isBooting = false }
|
||||||
|
guard let token else { return }
|
||||||
|
await YMClient.shared.setToken(token)
|
||||||
|
do {
|
||||||
|
let status = try await YMClient.shared.accountStatus()
|
||||||
|
accountName = status.account.displayName
|
||||||
|
?? status.account.fullName
|
||||||
|
?? status.account.login
|
||||||
|
?? "Аккаунт"
|
||||||
|
await PlayerController.shared.refreshLikes()
|
||||||
|
} catch {
|
||||||
|
log.error("boot: \(error.localizedDescription)")
|
||||||
|
// A dead token should not trap the user on a broken screen.
|
||||||
|
if case let YMError.http(status, _) = error, status == 401 || status == 403 {
|
||||||
|
signOut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func signIn(with token: String) async {
|
||||||
|
let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty else { return }
|
||||||
|
Keychain.set(trimmed, for: "token")
|
||||||
|
self.token = trimmed
|
||||||
|
await boot()
|
||||||
|
}
|
||||||
|
|
||||||
|
func signOut() {
|
||||||
|
Keychain.set(nil, for: "token")
|
||||||
|
token = nil
|
||||||
|
accountName = ""
|
||||||
|
Task { await YMClient.shared.setToken(nil) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
@main
|
||||||
|
struct YaMusekApp: App {
|
||||||
|
@StateObject private var state = AppState()
|
||||||
|
@StateObject private var player = PlayerController.shared
|
||||||
|
|
||||||
|
var body: some Scene {
|
||||||
|
WindowGroup {
|
||||||
|
Group {
|
||||||
|
// The API client only learns the token inside boot(), so nothing
|
||||||
|
// that makes requests may appear before it finishes.
|
||||||
|
if state.isBooting {
|
||||||
|
SplashView()
|
||||||
|
} else if state.isAuthorized {
|
||||||
|
RootView()
|
||||||
|
} else {
|
||||||
|
LoginView()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.environmentObject(state)
|
||||||
|
.environmentObject(player)
|
||||||
|
.preferredColorScheme(.dark)
|
||||||
|
.task { await state.boot() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SplashView: View {
|
||||||
|
var body: some View {
|
||||||
|
ZStack {
|
||||||
|
Color.black.ignoresSafeArea()
|
||||||
|
VStack(spacing: 24) {
|
||||||
|
Text("YaMusek")
|
||||||
|
.font(.system(size: 72, weight: .heavy, design: .rounded))
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
ProgressView()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import CryptoKit
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
enum Crypto {
|
||||||
|
/// md5 hex digest, used by the legacy `download-info` signing scheme.
|
||||||
|
static func md5Hex(_ string: String) -> String {
|
||||||
|
let digest = Insecure.MD5.hash(data: Data(string.utf8))
|
||||||
|
return digest.map { String(format: "%02x", $0) }.joined()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// base64(hmac-sha256(key, message)).
|
||||||
|
///
|
||||||
|
/// `get-file-info` wants the trailing "=" padding stripped; the lyrics
|
||||||
|
/// endpoint wants it kept.
|
||||||
|
static func hmacSHA256Base64(message: String, key: String, stripPadding: Bool = true) -> String {
|
||||||
|
let mac = HMAC<SHA256>.authenticationCode(
|
||||||
|
for: Data(message.utf8),
|
||||||
|
using: SymmetricKey(data: Data(key.utf8))
|
||||||
|
)
|
||||||
|
let encoded = Data(mac).base64EncodedString()
|
||||||
|
return stripPadding ? encoded.replacingOccurrences(of: "=", with: "") : encoded
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import Foundation
|
||||||
|
import Security
|
||||||
|
|
||||||
|
/// Tiny keychain wrapper for the single secret we keep: the OAuth token.
|
||||||
|
enum Keychain {
|
||||||
|
private static let service = "com.yamusek.tv.oauth"
|
||||||
|
|
||||||
|
static func set(_ value: String?, for account: String) {
|
||||||
|
let query: [String: Any] = [
|
||||||
|
kSecClass as String: kSecClassGenericPassword,
|
||||||
|
kSecAttrService as String: service,
|
||||||
|
kSecAttrAccount as String: account,
|
||||||
|
]
|
||||||
|
SecItemDelete(query as CFDictionary)
|
||||||
|
guard let value, !value.isEmpty else { return }
|
||||||
|
var add = query
|
||||||
|
add[kSecValueData as String] = Data(value.utf8)
|
||||||
|
add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
|
||||||
|
SecItemAdd(add as CFDictionary, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func get(_ account: String) -> String? {
|
||||||
|
let query: [String: Any] = [
|
||||||
|
kSecClass as String: kSecClassGenericPassword,
|
||||||
|
kSecAttrService as String: service,
|
||||||
|
kSecAttrAccount as String: account,
|
||||||
|
kSecReturnData as String: true,
|
||||||
|
kSecMatchLimit as String: kSecMatchLimitOne,
|
||||||
|
]
|
||||||
|
var item: CFTypeRef?
|
||||||
|
guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,
|
||||||
|
let data = item as? Data else { return nil }
|
||||||
|
return String(data: data, encoding: .utf8)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import Foundation
|
||||||
|
import os
|
||||||
|
|
||||||
|
let log = Logger(subsystem: "com.yamusek.tv", category: "app")
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Playback position, published separately from `PlayerController`.
|
||||||
|
///
|
||||||
|
/// It ticks five times a second. Anything observing it re-renders that often,
|
||||||
|
/// so only the transport bar and the lyrics watch it.
|
||||||
|
@MainActor
|
||||||
|
final class PlaybackClock: ObservableObject {
|
||||||
|
@Published var currentTime: Double = 0
|
||||||
|
@Published var duration: Double = 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import MediaPlayer
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// Feeds the tvOS Now Playing card and the Siri Remote.
|
||||||
|
///
|
||||||
|
/// `MPNowPlayingInfoCenter.playbackState` is entitlement-gated and rejected for
|
||||||
|
/// third-party apps, so playback state travels through `playbackRate` instead.
|
||||||
|
extension PlayerController {
|
||||||
|
func configureRemoteCommands() {
|
||||||
|
let center = MPRemoteCommandCenter.shared()
|
||||||
|
|
||||||
|
// Declaring which commands exist is what makes the Control Center card
|
||||||
|
// and the screensaver overlay draw the right buttons.
|
||||||
|
for command in [
|
||||||
|
center.seekForwardCommand, center.seekBackwardCommand,
|
||||||
|
center.skipForwardCommand, center.skipBackwardCommand,
|
||||||
|
center.ratingCommand, center.likeCommand, center.dislikeCommand,
|
||||||
|
center.bookmarkCommand, center.changeRepeatModeCommand,
|
||||||
|
center.changeShuffleModeCommand, center.enableLanguageOptionCommand,
|
||||||
|
] {
|
||||||
|
command.isEnabled = false
|
||||||
|
}
|
||||||
|
for command in [
|
||||||
|
center.playCommand, center.pauseCommand, center.togglePlayPauseCommand,
|
||||||
|
center.nextTrackCommand, center.previousTrackCommand,
|
||||||
|
center.changePlaybackPositionCommand,
|
||||||
|
] {
|
||||||
|
command.isEnabled = true
|
||||||
|
}
|
||||||
|
|
||||||
|
center.playCommand.addTarget { [weak self] _ in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard self?.isPlaying == false else { return }
|
||||||
|
self?.togglePlayPause()
|
||||||
|
}
|
||||||
|
return .success
|
||||||
|
}
|
||||||
|
center.pauseCommand.addTarget { [weak self] _ in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard self?.isPlaying == true else { return }
|
||||||
|
self?.togglePlayPause()
|
||||||
|
}
|
||||||
|
return .success
|
||||||
|
}
|
||||||
|
center.togglePlayPauseCommand.addTarget { [weak self] _ in
|
||||||
|
Task { @MainActor in self?.togglePlayPause() }
|
||||||
|
return .success
|
||||||
|
}
|
||||||
|
center.nextTrackCommand.addTarget { [weak self] _ in
|
||||||
|
Task { @MainActor in self?.next() }
|
||||||
|
return .success
|
||||||
|
}
|
||||||
|
center.previousTrackCommand.addTarget { [weak self] _ in
|
||||||
|
Task { @MainActor in self?.previous() }
|
||||||
|
return .success
|
||||||
|
}
|
||||||
|
center.changePlaybackPositionCommand.addTarget { [weak self] event in
|
||||||
|
guard let event = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed }
|
||||||
|
Task { @MainActor in self?.seek(to: event.positionTime) }
|
||||||
|
return .success
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNowPlaying() {
|
||||||
|
let center = MPNowPlayingInfoCenter.default()
|
||||||
|
guard let track = current else {
|
||||||
|
center.nowPlayingInfo = nil
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var info: [String: Any] = [
|
||||||
|
MPMediaItemPropertyTitle: track.displayTitle,
|
||||||
|
MPMediaItemPropertyArtist: track.artistNames,
|
||||||
|
MPMediaItemPropertyPlaybackDuration: clock.duration,
|
||||||
|
MPNowPlayingInfoPropertyElapsedPlaybackTime: clock.currentTime,
|
||||||
|
MPNowPlayingInfoPropertyPlaybackRate: isPlaying ? 1.0 : 0.0,
|
||||||
|
MPNowPlayingInfoPropertyDefaultPlaybackRate: 1.0,
|
||||||
|
MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue,
|
||||||
|
MPNowPlayingInfoPropertyIsLiveStream: false,
|
||||||
|
MPNowPlayingInfoPropertyExternalContentIdentifier: track.trackID,
|
||||||
|
]
|
||||||
|
if let album = track.albums?.first?.title {
|
||||||
|
info[MPMediaItemPropertyAlbumTitle] = album
|
||||||
|
}
|
||||||
|
if !queue.isEmpty {
|
||||||
|
info[MPNowPlayingInfoPropertyPlaybackQueueCount] = queue.count
|
||||||
|
info[MPNowPlayingInfoPropertyPlaybackQueueIndex] = index
|
||||||
|
}
|
||||||
|
|
||||||
|
center.nowPlayingInfo = info
|
||||||
|
loadArtwork(for: track)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Something else on tvOS can clear the card; put it back if it is gone.
|
||||||
|
func repairNowPlayingIfNeeded() {
|
||||||
|
guard let track = current else { return }
|
||||||
|
let published = MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String
|
||||||
|
guard published != track.displayTitle else { return }
|
||||||
|
updateNowPlaying()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func loadArtwork(for track: Track) {
|
||||||
|
guard let url = track.coverURL(size: 300) else { return }
|
||||||
|
let trackID = track.trackID
|
||||||
|
|
||||||
|
Task {
|
||||||
|
guard let image = await ImageCache.shared.image(for: url),
|
||||||
|
current?.trackID == trackID
|
||||||
|
else { return }
|
||||||
|
|
||||||
|
var info = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [:]
|
||||||
|
info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
|
||||||
|
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Rotor stations are an endless chain: the server hands out a batch, the
|
||||||
|
/// client reports what happened to each track, and asks for more by naming the
|
||||||
|
/// last one it played.
|
||||||
|
extension PlayerController {
|
||||||
|
private static let clientName = "appletv-yamusek"
|
||||||
|
|
||||||
|
private static func resumeKey(_ station: String) -> String {
|
||||||
|
"rotorResume.\(station)"
|
||||||
|
}
|
||||||
|
|
||||||
|
func startRotor(station: String, name: String) {
|
||||||
|
isLoading = true
|
||||||
|
Task {
|
||||||
|
// Announce the start before asking for tracks, and continue from
|
||||||
|
// where this station left off; otherwise it replays its opening.
|
||||||
|
await YMClient.shared.rotorFeedback(
|
||||||
|
station: station,
|
||||||
|
type: "radioStarted",
|
||||||
|
from: Self.clientName
|
||||||
|
)
|
||||||
|
|
||||||
|
let resume = UserDefaults.standard.string(forKey: Self.resumeKey(station))
|
||||||
|
guard let result = try? await YMClient.shared.rotorTracks(station: station, queue: resume) else {
|
||||||
|
stopForEmptyStation()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var tracks = result.sequence.compactMap(\.track)
|
||||||
|
if let resume, tracks.count > 1, tracks.first?.trackID == resume {
|
||||||
|
tracks.removeFirst()
|
||||||
|
}
|
||||||
|
guard !tracks.isEmpty else {
|
||||||
|
stopForEmptyStation()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rotorBatchID = result.batchId
|
||||||
|
setQueue(tracks, source: .rotor(station: station, name: name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saved on start rather than on finish: a few seconds of listening is
|
||||||
|
/// enough for the station to move on next time.
|
||||||
|
func reportRotorTrackStarted() {
|
||||||
|
guard case let .rotor(station, _) = source, let track = current else { return }
|
||||||
|
let id = track.trackID
|
||||||
|
let batch = rotorBatchID
|
||||||
|
UserDefaults.standard.set(id, forKey: Self.resumeKey(station))
|
||||||
|
|
||||||
|
Task {
|
||||||
|
await YMClient.shared.rotorFeedback(
|
||||||
|
station: station,
|
||||||
|
type: "trackStarted",
|
||||||
|
trackID: id,
|
||||||
|
batchID: batch
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func reportTrackEnded(skipped: Bool) {
|
||||||
|
guard case let .rotor(station, _) = source, let track = current else { return }
|
||||||
|
let id = track.trackID
|
||||||
|
let batch = rotorBatchID
|
||||||
|
let played = clock.currentTime
|
||||||
|
|
||||||
|
Task {
|
||||||
|
await YMClient.shared.rotorFeedback(
|
||||||
|
station: station,
|
||||||
|
type: skipped ? "skip" : "trackFinished",
|
||||||
|
trackID: id,
|
||||||
|
batchID: batch,
|
||||||
|
totalPlayedSeconds: played
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetches the next batch while a couple of tracks are still queued.
|
||||||
|
func topUpRotorIfNeeded() {
|
||||||
|
guard case let .rotor(station, _) = source, queue.count - index <= 2 else { return }
|
||||||
|
let last = queue.last?.trackID
|
||||||
|
|
||||||
|
Task {
|
||||||
|
guard let result = try? await YMClient.shared.rotorTracks(station: station, queue: last) else { return }
|
||||||
|
rotorBatchID = result.batchId ?? rotorBatchID
|
||||||
|
appendToQueue(result.sequence.compactMap(\.track))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The queue ran dry; pull more and keep going.
|
||||||
|
func extendRotor(station: String, name: String) {
|
||||||
|
isLoading = true
|
||||||
|
let last = queue.last?.trackID
|
||||||
|
|
||||||
|
Task {
|
||||||
|
guard let result = try? await YMClient.shared.rotorTracks(station: station, queue: last) else {
|
||||||
|
stopForEmptyStation()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rotorBatchID = result.batchId ?? rotorBatchID
|
||||||
|
|
||||||
|
let before = queue.count
|
||||||
|
appendToQueue(result.sequence.compactMap(\.track))
|
||||||
|
guard queue.count > before else {
|
||||||
|
stopForEmptyStation()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
startPlaying(at: before)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
import AVFoundation
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Where the current queue came from. Rotor queues report feedback and refill
|
||||||
|
/// themselves; collections just play to the end.
|
||||||
|
enum QueueSource: Equatable {
|
||||||
|
case none
|
||||||
|
case collection(String)
|
||||||
|
case rotor(station: String, name: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
final class PlayerController: ObservableObject {
|
||||||
|
static let shared = PlayerController()
|
||||||
|
|
||||||
|
enum LyricsState: Equatable {
|
||||||
|
case idle
|
||||||
|
case loading
|
||||||
|
case ready
|
||||||
|
case unavailable
|
||||||
|
}
|
||||||
|
|
||||||
|
@Published private(set) var queue: [Track] = []
|
||||||
|
@Published private(set) var index = 0
|
||||||
|
@Published private(set) var isPlaying = false
|
||||||
|
@Published private(set) var source: QueueSource = .none
|
||||||
|
@Published private(set) var lyrics: Lyrics?
|
||||||
|
@Published private(set) var lyricsState: LyricsState = .idle
|
||||||
|
@Published private(set) var likedIDs: Set<String> = []
|
||||||
|
|
||||||
|
let clock = PlaybackClock()
|
||||||
|
|
||||||
|
var current: Track? { queue.indices.contains(index) ? queue[index] : nil }
|
||||||
|
|
||||||
|
let player = AVPlayer()
|
||||||
|
|
||||||
|
var rotorBatchID: String?
|
||||||
|
var isLoading = false
|
||||||
|
private var didReportStart = false
|
||||||
|
|
||||||
|
private var timeObserver: Any?
|
||||||
|
private var itemObservation: NSKeyValueObservation?
|
||||||
|
private var rateObservation: NSKeyValueObservation?
|
||||||
|
private var endObserver: NSObjectProtocol?
|
||||||
|
private var interruptionObserver: NSObjectProtocol?
|
||||||
|
private var resolveTask: Task<Void, Never>?
|
||||||
|
private var lyricsTask: Task<Void, Never>?
|
||||||
|
private var ticksSinceNowPlayingCheck = 0
|
||||||
|
|
||||||
|
private init() {
|
||||||
|
// Lossless is several times the size of an MP3, and the default
|
||||||
|
// "buffer enough never to stall" policy turns that into a long wait
|
||||||
|
// before the first note.
|
||||||
|
player.automaticallyWaitsToMinimizeStalling = false
|
||||||
|
|
||||||
|
configureAudioSession()
|
||||||
|
configureRemoteCommands()
|
||||||
|
observePlayer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Queue
|
||||||
|
|
||||||
|
func play(tracks: [Track], startAt: Int = 0, source: QueueSource) {
|
||||||
|
let playable = tracks.filter { $0.available ?? true }
|
||||||
|
guard !playable.isEmpty else { return }
|
||||||
|
|
||||||
|
// Keep the chosen track selected even if unavailable ones were dropped.
|
||||||
|
let anchor = tracks.indices.contains(startAt) ? tracks[startAt].trackID : nil
|
||||||
|
|
||||||
|
queue = playable
|
||||||
|
index = anchor.flatMap { id in playable.firstIndex { $0.trackID == id } } ?? 0
|
||||||
|
rotorBatchID = nil
|
||||||
|
self.source = source
|
||||||
|
loadCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
func togglePlayPause() {
|
||||||
|
guard player.currentItem != nil else {
|
||||||
|
if current != nil { loadCurrent() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if isPlaying {
|
||||||
|
player.pause()
|
||||||
|
} else {
|
||||||
|
player.play()
|
||||||
|
}
|
||||||
|
isPlaying.toggle()
|
||||||
|
updateNowPlaying()
|
||||||
|
}
|
||||||
|
|
||||||
|
func next() {
|
||||||
|
advance(skipped: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func previous() {
|
||||||
|
guard clock.currentTime <= 5, index > 0 else {
|
||||||
|
seek(to: 0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
index -= 1
|
||||||
|
loadCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
func seek(to seconds: Double) {
|
||||||
|
player.seek(
|
||||||
|
to: CMTime(seconds: max(0, seconds), preferredTimescale: 600),
|
||||||
|
toleranceBefore: .zero,
|
||||||
|
toleranceAfter: .zero
|
||||||
|
)
|
||||||
|
clock.currentTime = seconds
|
||||||
|
updateNowPlaying()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when a track ends or is skipped.
|
||||||
|
func advance(skipped: Bool) {
|
||||||
|
reportTrackEnded(skipped: skipped)
|
||||||
|
|
||||||
|
if index + 1 < queue.count {
|
||||||
|
index += 1
|
||||||
|
loadCurrent()
|
||||||
|
topUpRotorIfNeeded()
|
||||||
|
} else if case let .rotor(station, name) = source {
|
||||||
|
extendRotor(station: station, name: name)
|
||||||
|
} else {
|
||||||
|
player.pause()
|
||||||
|
isPlaying = false
|
||||||
|
updateNowPlaying()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendToQueue(_ tracks: [Track]) {
|
||||||
|
let known = Set(queue.map(\.trackID))
|
||||||
|
queue.append(contentsOf: tracks.filter { !known.contains($0.trackID) })
|
||||||
|
}
|
||||||
|
|
||||||
|
func startPlaying(at index: Int) {
|
||||||
|
self.index = index
|
||||||
|
loadCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
func setQueue(_ tracks: [Track], source: QueueSource) {
|
||||||
|
queue = tracks
|
||||||
|
index = 0
|
||||||
|
self.source = source
|
||||||
|
loadCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopForEmptyStation() {
|
||||||
|
isLoading = false
|
||||||
|
isPlaying = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Likes
|
||||||
|
|
||||||
|
func isLiked(_ track: Track?) -> Bool {
|
||||||
|
guard let track else { return false }
|
||||||
|
return likedIDs.contains(track.trackID) || likedIDs.contains(track.id.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func refreshLikes() async {
|
||||||
|
guard let ids = try? await YMClient.shared.likedTrackIDs() else { return }
|
||||||
|
likedIDs = ids
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates the local set immediately so the heart responds without waiting
|
||||||
|
/// on the round trip.
|
||||||
|
func toggleLikeCurrent() async {
|
||||||
|
guard let track = current else { return }
|
||||||
|
let wanted = !isLiked(track)
|
||||||
|
do {
|
||||||
|
try await YMClient.shared.setLiked(wanted, trackID: track.trackID)
|
||||||
|
for id in [track.trackID, track.id.value] {
|
||||||
|
if wanted { likedIDs.insert(id) } else { likedIDs.remove(id) }
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
log.error("like: \(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Loading
|
||||||
|
|
||||||
|
private func loadCurrent() {
|
||||||
|
guard let track = current else { return }
|
||||||
|
|
||||||
|
resolveTask?.cancel()
|
||||||
|
itemObservation?.invalidate()
|
||||||
|
isLoading = true
|
||||||
|
clock.currentTime = 0
|
||||||
|
clock.duration = track.duration
|
||||||
|
didReportStart = false
|
||||||
|
updateNowPlaying()
|
||||||
|
loadLyrics(for: track)
|
||||||
|
|
||||||
|
let trackID = track.trackID
|
||||||
|
resolveTask = Task { [weak self] in
|
||||||
|
do {
|
||||||
|
let stream = try await StreamResolver.resolve(trackID: trackID, preferring: .fileInfo)
|
||||||
|
guard !Task.isCancelled, let self, self.current?.trackID == trackID else { return }
|
||||||
|
self.attach(stream)
|
||||||
|
} catch {
|
||||||
|
guard !Task.isCancelled, let self else { return }
|
||||||
|
log.error("stream \(trackID): \(error.localizedDescription)")
|
||||||
|
self.isLoading = false
|
||||||
|
self.isPlaying = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func attach(_ stream: ResolvedStream) {
|
||||||
|
let item = AVPlayerItem(url: stream.url)
|
||||||
|
// A modest read-ahead instead of racing to fill the whole buffer.
|
||||||
|
item.preferredForwardBufferDuration = 10
|
||||||
|
|
||||||
|
itemObservation = item.observe(\.status, options: [.new]) { [weak self] item, _ in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard let self else { return }
|
||||||
|
switch item.status {
|
||||||
|
case .readyToPlay:
|
||||||
|
self.isLoading = false
|
||||||
|
let duration = item.duration.seconds
|
||||||
|
if duration.isFinite, duration > 0 { self.clock.duration = duration }
|
||||||
|
self.player.play()
|
||||||
|
self.isPlaying = true
|
||||||
|
self.reportTrackStarted()
|
||||||
|
self.updateNowPlaying()
|
||||||
|
case .failed:
|
||||||
|
log.error("playback: \(item.error?.localizedDescription ?? "unknown")")
|
||||||
|
self.isLoading = false
|
||||||
|
self.isPlaying = false
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
player.replaceCurrentItem(with: item)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func loadLyrics(for track: Track) {
|
||||||
|
lyricsTask?.cancel()
|
||||||
|
lyrics = nil
|
||||||
|
|
||||||
|
guard track.lyricsInfo?.hasSynced ?? true else {
|
||||||
|
lyricsState = .unavailable
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lyricsState = .loading
|
||||||
|
|
||||||
|
let trackID = track.trackID
|
||||||
|
lyricsTask = Task { [weak self] in
|
||||||
|
let loaded = try? await LyricsService.load(trackID: trackID)
|
||||||
|
guard !Task.isCancelled, let self, self.current?.trackID == trackID else { return }
|
||||||
|
if let loaded, loaded.synced, !loaded.lines.isEmpty {
|
||||||
|
self.lyrics = loaded
|
||||||
|
self.lyricsState = .ready
|
||||||
|
} else {
|
||||||
|
self.lyricsState = .unavailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func reportTrackStarted() {
|
||||||
|
guard !didReportStart else { return }
|
||||||
|
didReportStart = true
|
||||||
|
reportRotorTrackStarted()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Observation
|
||||||
|
|
||||||
|
private func observePlayer() {
|
||||||
|
timeObserver = player.addPeriodicTimeObserver(
|
||||||
|
forInterval: CMTime(seconds: 0.2, preferredTimescale: 600),
|
||||||
|
queue: .main
|
||||||
|
) { [weak self] time in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard let self else { return }
|
||||||
|
self.clock.currentTime = time.seconds.isFinite ? time.seconds : 0
|
||||||
|
if let duration = self.player.currentItem?.duration.seconds,
|
||||||
|
duration.isFinite, duration > 0 {
|
||||||
|
self.clock.duration = duration
|
||||||
|
}
|
||||||
|
self.tickNowPlaying()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
endObserver = NotificationCenter.default.addObserver(
|
||||||
|
forName: .AVPlayerItemDidPlayToEndTime,
|
||||||
|
object: nil,
|
||||||
|
queue: .main
|
||||||
|
) { [weak self] _ in
|
||||||
|
Task { @MainActor in self?.advance(skipped: false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stay honest if AVPlayer stalls or resumes on its own.
|
||||||
|
rateObservation = player.observe(\.timeControlStatus, options: [.new]) { [weak self] player, _ in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard let self else { return }
|
||||||
|
let playing = player.timeControlStatus == .playing
|
||||||
|
guard playing != self.isPlaying, !self.isLoading else { return }
|
||||||
|
self.isPlaying = playing
|
||||||
|
self.updateNowPlaying()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func configureAudioSession() {
|
||||||
|
do {
|
||||||
|
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
|
||||||
|
try AVAudioSession.sharedInstance().setActive(true)
|
||||||
|
} catch {
|
||||||
|
log.error("audio session: \(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
|
||||||
|
interruptionObserver = NotificationCenter.default.addObserver(
|
||||||
|
forName: AVAudioSession.interruptionNotification,
|
||||||
|
object: AVAudioSession.sharedInstance(),
|
||||||
|
queue: .main
|
||||||
|
) { [weak self] note in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard let self,
|
||||||
|
let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
|
||||||
|
let type = AVAudioSession.InterruptionType(rawValue: raw)
|
||||||
|
else { return }
|
||||||
|
|
||||||
|
switch type {
|
||||||
|
case .began:
|
||||||
|
self.player.pause()
|
||||||
|
self.isPlaying = false
|
||||||
|
case .ended:
|
||||||
|
let options = (note.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt)
|
||||||
|
.map(AVAudioSession.InterruptionOptions.init(rawValue:)) ?? []
|
||||||
|
guard options.contains(.shouldResume) else { return }
|
||||||
|
try? AVAudioSession.sharedInstance().setActive(true)
|
||||||
|
self.player.play()
|
||||||
|
self.isPlaying = true
|
||||||
|
@unknown default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
self.updateNowPlaying()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Republishes Now Playing once a second if the system has dropped it.
|
||||||
|
private func tickNowPlaying() {
|
||||||
|
ticksSinceNowPlayingCheck += 1
|
||||||
|
guard ticksSinceNowPlayingCheck >= 5 else { return }
|
||||||
|
ticksSinceNowPlayingCheck = 0
|
||||||
|
repairNowPlayingIfNeeded()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct AlbumView: View {
|
||||||
|
let album: Album
|
||||||
|
@EnvironmentObject private var player: PlayerController
|
||||||
|
|
||||||
|
@State private var full: Album?
|
||||||
|
@State private var tracks: [Track] = []
|
||||||
|
@State private var isLoading = true
|
||||||
|
|
||||||
|
private var resolved: Album { full ?? album }
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 40) {
|
||||||
|
header
|
||||||
|
|
||||||
|
if isLoading {
|
||||||
|
LoadingState(text: "Загружаем альбом…").frame(height: 300)
|
||||||
|
} else {
|
||||||
|
LazyVStack(spacing: 6) {
|
||||||
|
ForEach(Array(tracks.enumerated()), id: \.offset) { pair in
|
||||||
|
HStack(spacing: 0) {
|
||||||
|
Text("\(pair.offset + 1)")
|
||||||
|
.font(.headline.monospacedDigit())
|
||||||
|
.foregroundStyle(.white.opacity(0.35))
|
||||||
|
.frame(width: 60, alignment: .trailing)
|
||||||
|
|
||||||
|
TrackRow(
|
||||||
|
track: pair.element,
|
||||||
|
isCurrent: player.current?.trackID == pair.element.trackID
|
||||||
|
) {
|
||||||
|
play(from: pair.offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.top, 120)
|
||||||
|
.padding(.bottom, 60)
|
||||||
|
}
|
||||||
|
.background(backdrop)
|
||||||
|
.task { await load() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private var backdrop: some View {
|
||||||
|
BlurredBackdrop(url: resolved.coverURL(size: 200))
|
||||||
|
}
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
HStack(alignment: .top, spacing: 50) {
|
||||||
|
CoverImage(url: resolved.coverURL(size: 400), corner: 16)
|
||||||
|
.frame(width: 340, height: 340)
|
||||||
|
|
||||||
|
VStack(alignment: .leading, spacing: 14) {
|
||||||
|
Text(resolved.displayTitle)
|
||||||
|
.font(.system(size: 52, weight: .bold))
|
||||||
|
.lineLimit(3)
|
||||||
|
|
||||||
|
if let artist = resolved.artists?.first {
|
||||||
|
NavigationLink(value: MusicRoute.artist(artist)) {
|
||||||
|
Text(resolved.artistNames)
|
||||||
|
.font(.title3)
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
}
|
||||||
|
.buttonStyle(RowButtonStyle())
|
||||||
|
.fixedSize()
|
||||||
|
} else {
|
||||||
|
Text(resolved.artistNames)
|
||||||
|
.font(.title3)
|
||||||
|
.foregroundStyle(.white.opacity(0.6))
|
||||||
|
}
|
||||||
|
|
||||||
|
if !resolved.subtitleLine.isEmpty {
|
||||||
|
Text(resolved.subtitleLine)
|
||||||
|
.font(.body)
|
||||||
|
.foregroundStyle(.white.opacity(0.55))
|
||||||
|
}
|
||||||
|
|
||||||
|
HStack(spacing: 20) {
|
||||||
|
Button { play(from: 0) } label: {
|
||||||
|
Label("Слушать", systemImage: "play.fill")
|
||||||
|
}
|
||||||
|
.disabled(tracks.isEmpty)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
player.play(
|
||||||
|
tracks: tracks.shuffled(),
|
||||||
|
startAt: 0,
|
||||||
|
source: .collection(resolved.displayTitle)
|
||||||
|
)
|
||||||
|
} label: {
|
||||||
|
Label("Вперемешку", systemImage: "shuffle")
|
||||||
|
}
|
||||||
|
.disabled(tracks.isEmpty)
|
||||||
|
}
|
||||||
|
.padding(.top, 10)
|
||||||
|
|
||||||
|
if let description = resolved.shortDescription, !description.isEmpty {
|
||||||
|
Text(description)
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundStyle(.white.opacity(0.6))
|
||||||
|
.frame(maxWidth: 900, alignment: .leading)
|
||||||
|
.padding(.top, 8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func play(from index: Int) {
|
||||||
|
guard !tracks.isEmpty else { return }
|
||||||
|
player.play(tracks: tracks, startAt: index, source: .collection(resolved.displayTitle))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func load() async {
|
||||||
|
isLoading = true
|
||||||
|
defer { isLoading = false }
|
||||||
|
do {
|
||||||
|
let loaded = try await YMClient.shared.album(albumID: album.id.value)
|
||||||
|
full = loaded
|
||||||
|
tracks = (loaded.volumes ?? []).flatMap { $0 }
|
||||||
|
} catch {
|
||||||
|
log.error("\(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct ArtistView: View {
|
||||||
|
let artist: Artist
|
||||||
|
@EnvironmentObject private var player: PlayerController
|
||||||
|
|
||||||
|
@State private var info: ArtistBriefInfo?
|
||||||
|
@State private var isLoading = true
|
||||||
|
@State private var showAllTracks = false
|
||||||
|
|
||||||
|
private var resolved: Artist { info?.artist ?? artist }
|
||||||
|
private var popular: [Track] { info?.popularTracks ?? [] }
|
||||||
|
private var albums: [Album] { info?.albums ?? [] }
|
||||||
|
private var alsoAlbums: [Album] { info?.alsoAlbums ?? [] }
|
||||||
|
private var similar: [Artist] { info?.similarArtists ?? [] }
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 50) {
|
||||||
|
header
|
||||||
|
|
||||||
|
if isLoading {
|
||||||
|
LoadingState(text: "Загружаем исполнителя…").frame(height: 300)
|
||||||
|
} else {
|
||||||
|
if !popular.isEmpty { popularSection }
|
||||||
|
if !albums.isEmpty { albumShelf("Альбомы", albums) }
|
||||||
|
if !alsoAlbums.isEmpty { albumShelf("Сборники и участие", alsoAlbums) }
|
||||||
|
if !similar.isEmpty { similarSection }
|
||||||
|
if let text = resolved.description?.text, !text.isEmpty { about(text) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.top, 120)
|
||||||
|
.padding(.bottom, 60)
|
||||||
|
}
|
||||||
|
.background(backdrop)
|
||||||
|
.task { await load() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Header
|
||||||
|
|
||||||
|
private var backdrop: some View {
|
||||||
|
BlurredBackdrop(url: resolved.coverURL(size: 200))
|
||||||
|
}
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
HStack(alignment: .center, spacing: 50) {
|
||||||
|
CoverImage(url: resolved.coverURL(size: 400), corner: 160)
|
||||||
|
.frame(width: 320, height: 320)
|
||||||
|
|
||||||
|
VStack(alignment: .leading, spacing: 14) {
|
||||||
|
Text(resolved.name)
|
||||||
|
.font(.system(size: 60, weight: .bold))
|
||||||
|
.lineLimit(2)
|
||||||
|
|
||||||
|
if let genres = resolved.genres, !genres.isEmpty {
|
||||||
|
Text(genres.prefix(3).joined(separator: " · ").capitalized)
|
||||||
|
.font(.title3)
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
}
|
||||||
|
if let counts = resolved.countsLine {
|
||||||
|
Text(counts)
|
||||||
|
.font(.body)
|
||||||
|
.foregroundStyle(.white.opacity(0.6))
|
||||||
|
}
|
||||||
|
|
||||||
|
HStack(spacing: 20) {
|
||||||
|
Button {
|
||||||
|
play(popular, title: resolved.name)
|
||||||
|
} label: {
|
||||||
|
Label("Слушать", systemImage: "play.fill")
|
||||||
|
}
|
||||||
|
.disabled(popular.isEmpty)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
player.startRotor(
|
||||||
|
station: "artist:\(resolved.id.value)",
|
||||||
|
name: "Волна: \(resolved.name)"
|
||||||
|
)
|
||||||
|
} label: {
|
||||||
|
Label("Волна артиста", systemImage: "dot.radiowaves.left.and.right")
|
||||||
|
}
|
||||||
|
|
||||||
|
Button {
|
||||||
|
playAllTracks()
|
||||||
|
} label: {
|
||||||
|
Label("Все треки", systemImage: "music.note.list")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.top, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Sections
|
||||||
|
|
||||||
|
private var popularSection: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
HStack(alignment: .firstTextBaseline) {
|
||||||
|
Text("Популярные треки").font(.title2.weight(.semibold))
|
||||||
|
Spacer()
|
||||||
|
if popular.count > 8 {
|
||||||
|
Button(showAllTracks ? "Свернуть" : "Показать все") {
|
||||||
|
showAllTracks.toggle()
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.font(.callout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let shown = showAllTracks ? popular : Array(popular.prefix(8))
|
||||||
|
LazyVStack(spacing: 6) {
|
||||||
|
ForEach(Array(shown.enumerated()), id: \.offset) { pair in
|
||||||
|
TrackRow(
|
||||||
|
track: pair.element,
|
||||||
|
isCurrent: player.current?.trackID == pair.element.trackID
|
||||||
|
) {
|
||||||
|
play(popular, startAt: pair.offset, title: resolved.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func albumShelf(_ title: String, _ list: [Album]) -> some View {
|
||||||
|
Shelf(title: title) {
|
||||||
|
ForEach(list, id: \.id) { album in
|
||||||
|
PosterLink(
|
||||||
|
title: album.displayTitle,
|
||||||
|
subtitle: album.subtitleLine,
|
||||||
|
imageURL: album.coverURL(size: 200),
|
||||||
|
route: .album(album)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var similarSection: some View {
|
||||||
|
Shelf(title: "Похожие исполнители") {
|
||||||
|
ForEach(similar, id: \.id) { other in
|
||||||
|
PosterLink(
|
||||||
|
title: other.name,
|
||||||
|
subtitle: nil,
|
||||||
|
imageURL: other.coverURL(size: 200),
|
||||||
|
route: .artist(other),
|
||||||
|
circular: true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func about(_ text: String) -> some View {
|
||||||
|
VStack(alignment: .leading, spacing: 16) {
|
||||||
|
Text("Об исполнителе").font(.title2.weight(.semibold))
|
||||||
|
Text(text)
|
||||||
|
.font(.body)
|
||||||
|
.foregroundStyle(.white.opacity(0.7))
|
||||||
|
.frame(maxWidth: 1200, alignment: .leading)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Actions
|
||||||
|
|
||||||
|
private func play(_ list: [Track], startAt: Int = 0, title: String) {
|
||||||
|
guard !list.isEmpty else { return }
|
||||||
|
player.play(tracks: list, startAt: startAt, source: .collection(title))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func playAllTracks() {
|
||||||
|
Task {
|
||||||
|
do {
|
||||||
|
let all = try await YMClient.shared.artistTracks(artistID: resolved.id.value)
|
||||||
|
play(all, title: resolved.name)
|
||||||
|
} catch {
|
||||||
|
log.error("\(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func load() async {
|
||||||
|
isLoading = true
|
||||||
|
defer { isLoading = false }
|
||||||
|
do {
|
||||||
|
info = try await YMClient.shared.artistBriefInfo(artistID: artist.id.value)
|
||||||
|
} catch {
|
||||||
|
log.error("\(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// Yandex Music yellow, used sparingly as the single accent.
|
||||||
|
extension Color {
|
||||||
|
static let ymAccent = Color(red: 1.0, green: 0.87, blue: 0.16)
|
||||||
|
static let ymCard = Color.white.opacity(0.08)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CoverImage: View {
|
||||||
|
let url: URL?
|
||||||
|
var corner: CGFloat = 12
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
var body: some View {
|
||||||
|
let image = AsyncImage(url: url) { phase in
|
||||||
|
switch phase {
|
||||||
|
case let .success(image):
|
||||||
|
image.resizable().aspectRatio(contentMode: .fill)
|
||||||
|
default:
|
||||||
|
Color.ymCard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if corner > 0 {
|
||||||
|
image.clipShape(RoundedRectangle(cornerRadius: corner))
|
||||||
|
} else {
|
||||||
|
image.clipped()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A poster-style button used for playlists and stations.
|
||||||
|
struct CardButton: View {
|
||||||
|
let title: String
|
||||||
|
let subtitle: String?
|
||||||
|
let imageURL: URL?
|
||||||
|
var width: CGFloat = 280
|
||||||
|
let action: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: action) {
|
||||||
|
CoverImage(url: imageURL, corner: 12)
|
||||||
|
.frame(width: width, height: width)
|
||||||
|
}
|
||||||
|
.buttonStyle(CardButtonStyle())
|
||||||
|
.overlay(alignment: .bottomLeading) {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(title)
|
||||||
|
.font(.caption)
|
||||||
|
.lineLimit(1)
|
||||||
|
if let subtitle {
|
||||||
|
Text(subtitle)
|
||||||
|
.font(.caption2)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(width: width, alignment: .leading)
|
||||||
|
.offset(y: width * 0.22)
|
||||||
|
}
|
||||||
|
.padding(.bottom, subtitle == nil ? 46 : 66)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TrackRow: View {
|
||||||
|
let track: Track
|
||||||
|
let isCurrent: Bool
|
||||||
|
let action: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: action) {
|
||||||
|
HStack(spacing: 20) {
|
||||||
|
CoverImage(url: track.coverURL(size: 100))
|
||||||
|
.frame(width: 70, height: 70)
|
||||||
|
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text(track.displayTitle)
|
||||||
|
.font(.headline)
|
||||||
|
.lineLimit(1)
|
||||||
|
Text(track.artistNames)
|
||||||
|
.font(.subheadline)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(minLength: 12)
|
||||||
|
|
||||||
|
if isCurrent {
|
||||||
|
Image(systemName: "waveform")
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
}
|
||||||
|
if track.available == false {
|
||||||
|
Image(systemName: "nosign").foregroundStyle(.secondary)
|
||||||
|
} else {
|
||||||
|
Text(formatTime(track.duration))
|
||||||
|
.font(.subheadline.monospacedDigit())
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.vertical, 6)
|
||||||
|
}
|
||||||
|
.buttonStyle(RowButtonStyle())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A list row that actually shows where the focus is — `.plain` on tvOS does not.
|
||||||
|
struct RowButtonStyle: ButtonStyle {
|
||||||
|
func makeBody(configuration: Configuration) -> some View {
|
||||||
|
StyleBody(configuration: configuration)
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct StyleBody: View {
|
||||||
|
@Environment(\.isFocused) private var isFocused
|
||||||
|
let configuration: ButtonStyleConfiguration
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
configuration.label
|
||||||
|
.padding(.horizontal, 24)
|
||||||
|
.padding(.vertical, 8)
|
||||||
|
.background {
|
||||||
|
RoundedRectangle(cornerRadius: 16, style: .continuous)
|
||||||
|
.fill(.white.opacity(isFocused ? 0.16 : 0))
|
||||||
|
}
|
||||||
|
// No scaling here: a row that grows on focus spills over its
|
||||||
|
// neighbours in a tightly packed list.
|
||||||
|
.opacity(configuration.isPressed ? 0.7 : 1)
|
||||||
|
.animation(.easeOut(duration: 0.15), value: isFocused)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Round artwork (artists) that focuses without a square card behind it.
|
||||||
|
struct CircleCardStyle: ButtonStyle {
|
||||||
|
func makeBody(configuration: Configuration) -> some View {
|
||||||
|
StyleBody(configuration: configuration)
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct StyleBody: View {
|
||||||
|
@Environment(\.isFocused) private var isFocused
|
||||||
|
let configuration: ButtonStyleConfiguration
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
configuration.label
|
||||||
|
.overlay {
|
||||||
|
if isFocused {
|
||||||
|
Circle().strokeBorder(.white.opacity(0.95), lineWidth: 5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.scaleEffect(configuration.isPressed ? 0.96 : (isFocused ? 1.05 : 1))
|
||||||
|
.animation(.spring(response: 0.3, dampingFraction: 0.7), value: isFocused)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ErrorBanner: View {
|
||||||
|
let message: String
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(alignment: .top, spacing: 12) {
|
||||||
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
|
.foregroundStyle(.orange)
|
||||||
|
Text(message)
|
||||||
|
.font(.footnote)
|
||||||
|
.foregroundStyle(.white.opacity(0.9))
|
||||||
|
.multilineTextAlignment(.leading)
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
.padding(16)
|
||||||
|
.background(Color.white.opacity(0.1), in: RoundedRectangle(cornerRadius: 12, style: .continuous))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct LoadingState: View {
|
||||||
|
let text: String
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 16) {
|
||||||
|
ProgressView()
|
||||||
|
Text(text).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatTime(_ seconds: Double) -> String {
|
||||||
|
guard seconds.isFinite, seconds >= 0 else { return "--:--" }
|
||||||
|
let total = Int(seconds.rounded())
|
||||||
|
return String(format: "%d:%02d", total / 60, total % 60)
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
/// Four colours sampled from the corners of a cover, already darkened.
|
||||||
|
struct CoverPalette: Equatable {
|
||||||
|
let topLeading: Color
|
||||||
|
let topTrailing: Color
|
||||||
|
let bottomLeading: Color
|
||||||
|
let bottomTrailing: Color
|
||||||
|
|
||||||
|
static let dark = CoverPalette(
|
||||||
|
topLeading: Color(white: 0.09),
|
||||||
|
topTrailing: Color(white: 0.06),
|
||||||
|
bottomLeading: Color(white: 0.05),
|
||||||
|
bottomTrailing: Color(white: 0.03)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Downloads artwork for the backdrop and the Now Playing card.
|
||||||
|
///
|
||||||
|
/// Artwork in the interface goes through `AsyncImage`; this exists for the two
|
||||||
|
/// places that need the bitmap itself.
|
||||||
|
@MainActor
|
||||||
|
final class ImageCache {
|
||||||
|
static let shared = ImageCache()
|
||||||
|
|
||||||
|
private var palettes: [URL: CoverPalette] = [:]
|
||||||
|
|
||||||
|
private init() {}
|
||||||
|
|
||||||
|
func image(for url: URL) async -> UIImage? {
|
||||||
|
guard let (data, response) = try? await URLSession.shared.data(from: url) else { return nil }
|
||||||
|
if let http = response as? HTTPURLResponse, !(200 ..< 300).contains(http.statusCode) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return UIImage(data: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func palette(for url: URL) async -> CoverPalette {
|
||||||
|
if let hit = palettes[url] { return hit }
|
||||||
|
guard let image = await image(for: url) else { return .dark }
|
||||||
|
|
||||||
|
let palette = await Task.detached(priority: .utility) {
|
||||||
|
Self.palette(from: image)
|
||||||
|
}.value
|
||||||
|
|
||||||
|
palettes[url] = palette
|
||||||
|
if palettes.count > 40 { palettes.removeAll() }
|
||||||
|
return palette
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Squash the cover down to 2x2 and read the four pixels. A gradient built
|
||||||
|
/// from those reads as an out-of-focus version of the artwork without
|
||||||
|
/// drawing, blurring or stretching a single bitmap.
|
||||||
|
nonisolated private static func palette(from image: UIImage) -> CoverPalette {
|
||||||
|
let size = CGSize(width: 2, height: 2)
|
||||||
|
var pixels = [UInt8](repeating: 0, count: 16)
|
||||||
|
|
||||||
|
guard let space = CGColorSpace(name: CGColorSpace.sRGB),
|
||||||
|
let context = CGContext(
|
||||||
|
data: &pixels,
|
||||||
|
width: 2,
|
||||||
|
height: 2,
|
||||||
|
bitsPerComponent: 8,
|
||||||
|
bytesPerRow: 8,
|
||||||
|
space: space,
|
||||||
|
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
|
||||||
|
),
|
||||||
|
let cg = image.cgImage
|
||||||
|
else { return .dark }
|
||||||
|
|
||||||
|
context.interpolationQuality = .medium
|
||||||
|
context.draw(cg, in: CGRect(origin: .zero, size: size))
|
||||||
|
|
||||||
|
func colour(_ index: Int) -> Color {
|
||||||
|
let base = index * 4
|
||||||
|
return darkened(
|
||||||
|
red: Double(pixels[base]) / 255,
|
||||||
|
green: Double(pixels[base + 1]) / 255,
|
||||||
|
blue: Double(pixels[base + 2]) / 255
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CGContext origin is bottom-left, so rows come back flipped.
|
||||||
|
return CoverPalette(
|
||||||
|
topLeading: colour(2),
|
||||||
|
topTrailing: colour(3),
|
||||||
|
bottomLeading: colour(0),
|
||||||
|
bottomTrailing: colour(1)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pulls every colour down to a dark ceiling, so a mostly white sleeve does
|
||||||
|
/// not turn the whole screen into a lightbox.
|
||||||
|
nonisolated private static func darkened(red: Double, green: Double, blue: Double) -> Color {
|
||||||
|
let luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue
|
||||||
|
let ceiling = 0.20
|
||||||
|
let scale = luminance > 0.001 ? min(1, ceiling / luminance) : 1
|
||||||
|
return Color(
|
||||||
|
.sRGB,
|
||||||
|
red: red * scale,
|
||||||
|
green: green * scale,
|
||||||
|
blue: blue * scale,
|
||||||
|
opacity: 1
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ambient wash behind the player, artist and album screens.
|
||||||
|
///
|
||||||
|
/// A gradient rather than a blurred bitmap: no decode, no stretching, and a
|
||||||
|
/// single fill for the compositor.
|
||||||
|
struct BlurredBackdrop: View {
|
||||||
|
let url: URL?
|
||||||
|
|
||||||
|
@State private var palette: CoverPalette = .dark
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ZStack {
|
||||||
|
Color.black
|
||||||
|
LinearGradient(
|
||||||
|
stops: [
|
||||||
|
.init(color: palette.topLeading, location: 0),
|
||||||
|
.init(color: palette.topTrailing, location: 0.38),
|
||||||
|
.init(color: palette.bottomLeading, location: 0.72),
|
||||||
|
.init(color: palette.bottomTrailing, location: 1),
|
||||||
|
],
|
||||||
|
startPoint: .topLeading,
|
||||||
|
endPoint: .bottomTrailing
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.ignoresSafeArea()
|
||||||
|
.animation(.easeInOut(duration: 0.6), value: palette)
|
||||||
|
.task(id: url) {
|
||||||
|
guard let url else {
|
||||||
|
palette = .dark
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let loaded = await ImageCache.shared.palette(for: url)
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
palette = loaded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct LikesView: View {
|
||||||
|
@EnvironmentObject private var player: PlayerController
|
||||||
|
|
||||||
|
@State private var tracks: [Track] = []
|
||||||
|
@State private var isLoading = true
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationStack {
|
||||||
|
content
|
||||||
|
.musicDestinations()
|
||||||
|
}
|
||||||
|
.task { await load() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A real `List` rather than a `ScrollView` + `LazyVStack`: on tvOS the list
|
||||||
|
/// recycles its rows and owns the focus animation, where a lazy stack of a
|
||||||
|
/// hundred and fifty custom buttons does neither.
|
||||||
|
private var content: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 0) {
|
||||||
|
// Everything on this screen shares the tighter margin.
|
||||||
|
// Outside the List on purpose: inside a section header SwiftUI
|
||||||
|
// paints everything as secondary, which greys out the buttons.
|
||||||
|
header
|
||||||
|
.padding(.top, 30)
|
||||||
|
.padding(.bottom, 24)
|
||||||
|
|
||||||
|
List {
|
||||||
|
ForEach(Array(tracks.enumerated()), id: \.offset) { pair in
|
||||||
|
TrackRow(
|
||||||
|
track: pair.element,
|
||||||
|
isCurrent: player.current?.trackID == pair.element.trackID
|
||||||
|
) {
|
||||||
|
player.play(
|
||||||
|
tracks: tracks,
|
||||||
|
startAt: pair.offset,
|
||||||
|
source: .collection("Мне нравится")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.listStyle(.plain)
|
||||||
|
.overlay {
|
||||||
|
if isLoading {
|
||||||
|
LoadingState(text: "Загружаем вашу коллекцию…")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
HStack(alignment: .firstTextBaseline) {
|
||||||
|
Text("Мне нравится")
|
||||||
|
.font(.system(size: 56, weight: .bold))
|
||||||
|
Spacer()
|
||||||
|
if !tracks.isEmpty {
|
||||||
|
Text("\(tracks.count) треков").foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tracks.isEmpty {
|
||||||
|
HStack(spacing: 20) {
|
||||||
|
Button {
|
||||||
|
player.play(tracks: tracks, startAt: 0, source: .collection("Мне нравится"))
|
||||||
|
} label: {
|
||||||
|
Label("Слушать", systemImage: "play.fill")
|
||||||
|
}
|
||||||
|
Button {
|
||||||
|
player.play(
|
||||||
|
tracks: tracks.shuffled(),
|
||||||
|
startAt: 0,
|
||||||
|
source: .collection("Мне нравится")
|
||||||
|
)
|
||||||
|
} label: {
|
||||||
|
Label("Вперемешку", systemImage: "shuffle")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole library, a hundred at a time, so a big collection starts
|
||||||
|
/// showing immediately instead of after every batch has arrived.
|
||||||
|
private func load() async {
|
||||||
|
guard tracks.isEmpty else { return }
|
||||||
|
isLoading = true
|
||||||
|
defer { isLoading = false }
|
||||||
|
do {
|
||||||
|
let keys = try await YMClient.shared.likedTrackKeys()
|
||||||
|
for chunk in stride(from: 0, to: keys.count, by: 100).map({
|
||||||
|
Array(keys[$0 ..< min($0 + 100, keys.count)])
|
||||||
|
}) {
|
||||||
|
let batch = try await YMClient.shared.tracks(keys: chunk)
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
tracks.append(contentsOf: batch)
|
||||||
|
isLoading = false
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
log.error("\(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import CoreImage.CIFilterBuiltins
|
||||||
|
import SwiftUI
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
struct LoginView: View {
|
||||||
|
@EnvironmentObject private var state: AppState
|
||||||
|
|
||||||
|
@State private var code: DeviceCode?
|
||||||
|
@State private var error: String?
|
||||||
|
@State private var status = "Запрашиваем код…"
|
||||||
|
@State private var manualToken = ""
|
||||||
|
@State private var pollTask: Task<Void, Never>?
|
||||||
|
@State private var showManual = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ZStack {
|
||||||
|
LinearGradient(
|
||||||
|
colors: [Color(red: 0.08, green: 0.07, blue: 0.11), .black],
|
||||||
|
startPoint: .topLeading,
|
||||||
|
endPoint: .bottomTrailing
|
||||||
|
)
|
||||||
|
.ignoresSafeArea()
|
||||||
|
|
||||||
|
HStack(spacing: 80) {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
Text("YaMusek")
|
||||||
|
.font(.system(size: 76, weight: .heavy, design: .rounded))
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
Text("Неофициальный клиент Яндекс.Музыки для Apple TV")
|
||||||
|
.font(.title3)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.frame(maxWidth: 520, alignment: .leading)
|
||||||
|
|
||||||
|
if let error {
|
||||||
|
ErrorBanner(message: error).frame(maxWidth: 520)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
|
||||||
|
VStack(alignment: .leading, spacing: 16) {
|
||||||
|
Button("Запросить код заново") { startDeviceFlow() }
|
||||||
|
Button(showManual ? "Скрыть ручной ввод" : "Ввести токен вручную") {
|
||||||
|
showManual.toggle()
|
||||||
|
}
|
||||||
|
if showManual {
|
||||||
|
TextField("OAuth-токен", text: $manualToken)
|
||||||
|
.frame(maxWidth: 520)
|
||||||
|
Button("Войти с этим токеном") {
|
||||||
|
Task { await state.signIn(with: manualToken) }
|
||||||
|
}
|
||||||
|
.disabled(manualToken.trimmingCharacters(in: .whitespaces).isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxWidth: 620, alignment: .leading)
|
||||||
|
|
||||||
|
VStack(spacing: 24) {
|
||||||
|
if let code {
|
||||||
|
Text("Откройте на телефоне")
|
||||||
|
.font(.title3)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Text(code.verificationUrl)
|
||||||
|
.font(.title2.weight(.semibold))
|
||||||
|
|
||||||
|
if let qr = qrImage(for: code.verificationUrl) {
|
||||||
|
Image(uiImage: qr)
|
||||||
|
.interpolation(.none)
|
||||||
|
.resizable()
|
||||||
|
.frame(width: 260, height: 260)
|
||||||
|
.padding(12)
|
||||||
|
.background(.white, in: RoundedRectangle(cornerRadius: 16))
|
||||||
|
}
|
||||||
|
|
||||||
|
Text("и введите код")
|
||||||
|
.font(.title3)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Text(code.userCode)
|
||||||
|
.font(.system(size: 64, weight: .bold, design: .monospaced))
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
} else {
|
||||||
|
ProgressView()
|
||||||
|
}
|
||||||
|
Text(status)
|
||||||
|
.font(.footnote)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
.frame(width: 520)
|
||||||
|
.padding(40)
|
||||||
|
.background(Color.white.opacity(0.06), in: RoundedRectangle(cornerRadius: 28, style: .continuous))
|
||||||
|
}
|
||||||
|
.padding(80)
|
||||||
|
}
|
||||||
|
.onAppear { startDeviceFlow() }
|
||||||
|
.onDisappear { pollTask?.cancel() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func qrImage(for string: String) -> UIImage? {
|
||||||
|
let filter = CIFilter.qrCodeGenerator()
|
||||||
|
filter.message = Data(string.utf8)
|
||||||
|
filter.correctionLevel = "M"
|
||||||
|
guard let output = filter.outputImage else { return nil }
|
||||||
|
let scaled = output.transformed(by: CGAffineTransform(scaleX: 10, y: 10))
|
||||||
|
let context = CIContext()
|
||||||
|
guard let cgImage = context.createCGImage(scaled, from: scaled.extent) else { return nil }
|
||||||
|
return UIImage(cgImage: cgImage)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startDeviceFlow() {
|
||||||
|
pollTask?.cancel()
|
||||||
|
code = nil
|
||||||
|
error = nil
|
||||||
|
status = "Запрашиваем код…"
|
||||||
|
pollTask = Task {
|
||||||
|
do {
|
||||||
|
let received = try await DeviceAuth.requestCode()
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
code = received
|
||||||
|
status = "Ждём подтверждения…"
|
||||||
|
let interval = Double(received.interval ?? 5)
|
||||||
|
let deadline = Date().addingTimeInterval(Double(received.expiresIn))
|
||||||
|
|
||||||
|
while !Task.isCancelled, Date() < deadline {
|
||||||
|
try await Task.sleep(nanoseconds: UInt64(interval * 1_000_000_000))
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
switch try await DeviceAuth.poll(deviceCode: received.deviceCode) {
|
||||||
|
case .pending:
|
||||||
|
continue
|
||||||
|
case let .token(token):
|
||||||
|
status = "Готово!"
|
||||||
|
await state.signIn(with: token)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !Task.isCancelled {
|
||||||
|
status = "Код истёк"
|
||||||
|
error = "Код истёк — запросите новый."
|
||||||
|
}
|
||||||
|
} catch is CancellationError {
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
self.error = error.localizedDescription
|
||||||
|
status = "Ошибка"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// Everything that can be pushed onto a tab's navigation stack.
|
||||||
|
enum MusicRoute: Hashable {
|
||||||
|
case artist(Artist)
|
||||||
|
case album(Album)
|
||||||
|
}
|
||||||
|
|
||||||
|
extension View {
|
||||||
|
/// Attach once per NavigationStack so artist and album links work anywhere
|
||||||
|
/// inside that tab, including recursively (artist → album → artist → …).
|
||||||
|
func musicDestinations() -> some View {
|
||||||
|
navigationDestination(for: MusicRoute.self) { route in
|
||||||
|
switch route {
|
||||||
|
case let .artist(artist):
|
||||||
|
ArtistView(artist: artist)
|
||||||
|
case let .album(album):
|
||||||
|
AlbumView(album: album)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poster tile that pushes a route instead of running an action.
|
||||||
|
struct PosterLink: View {
|
||||||
|
let title: String
|
||||||
|
let subtitle: String?
|
||||||
|
let imageURL: URL?
|
||||||
|
let route: MusicRoute
|
||||||
|
var circular = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationLink(value: route) {
|
||||||
|
CoverImage(url: imageURL, corner: circular ? 140 : 12)
|
||||||
|
.frame(width: 280, height: 280)
|
||||||
|
}
|
||||||
|
.buttonStyle(circular ? AnyButtonStyle(CircleCardStyle()) : AnyButtonStyle(CardButtonStyle()))
|
||||||
|
.overlay(alignment: circular ? .bottom : .bottomLeading) {
|
||||||
|
VStack(alignment: circular ? .center : .leading, spacing: 2) {
|
||||||
|
Text(title)
|
||||||
|
.font(.caption)
|
||||||
|
.lineLimit(1)
|
||||||
|
if let subtitle, !subtitle.isEmpty {
|
||||||
|
Text(subtitle)
|
||||||
|
.font(.caption2)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(width: 280, alignment: circular ? .center : .leading)
|
||||||
|
.offset(y: 62)
|
||||||
|
}
|
||||||
|
.padding(.bottom, 70)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Type eraser so one view can pick between two button styles.
|
||||||
|
struct AnyButtonStyle: ButtonStyle {
|
||||||
|
private let makeBodyClosure: (Configuration) -> AnyView
|
||||||
|
|
||||||
|
init<S: ButtonStyle>(_ style: S) {
|
||||||
|
makeBodyClosure = { AnyView(style.makeBody(configuration: $0)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeBody(configuration: Configuration) -> some View {
|
||||||
|
makeBodyClosure(configuration)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stock tvOS card treatment, wrapped so it can be erased alongside others.
|
||||||
|
struct CardButtonStyle: ButtonStyle {
|
||||||
|
func makeBody(configuration: Configuration) -> some View {
|
||||||
|
StyleBody(configuration: configuration)
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct StyleBody: View {
|
||||||
|
@Environment(\.isFocused) private var isFocused
|
||||||
|
let configuration: ButtonStyleConfiguration
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
configuration.label
|
||||||
|
.overlay {
|
||||||
|
if isFocused {
|
||||||
|
RoundedRectangle(cornerRadius: 12)
|
||||||
|
.strokeBorder(.white.opacity(0.95), lineWidth: 5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.scaleEffect(configuration.isPressed ? 0.97 : (isFocused ? 1.05 : 1))
|
||||||
|
.animation(.spring(response: 0.3, dampingFraction: 0.7), value: isFocused)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Horizontal shelf used by the artist and album pages.
|
||||||
|
struct Shelf<Content: View>: View {
|
||||||
|
let title: String
|
||||||
|
@ViewBuilder let content: Content
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
Text(title).font(.title2.weight(.semibold))
|
||||||
|
ScrollView(.horizontal, showsIndicators: false) {
|
||||||
|
HStack(alignment: .top, spacing: 60) {
|
||||||
|
content
|
||||||
|
}
|
||||||
|
.padding(.vertical, 24)
|
||||||
|
}
|
||||||
|
.scrollClipDisabled()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies the focus shadow only while focused, so unfocused cells cost nothing.
|
||||||
|
struct FocusShadow: ViewModifier {
|
||||||
|
let active: Bool
|
||||||
|
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
if active {
|
||||||
|
content.shadow(color: .black.opacity(0.5), radius: 24, y: 12)
|
||||||
|
} else {
|
||||||
|
content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct MyWaveView: View {
|
||||||
|
@EnvironmentObject private var player: PlayerController
|
||||||
|
@EnvironmentObject private var state: AppState
|
||||||
|
@State private var stations: [Station] = []
|
||||||
|
@State private var isLoading = true
|
||||||
|
@State private var showSignOut = false
|
||||||
|
|
||||||
|
// Six across, as asked; the cards size themselves to the columns.
|
||||||
|
private let columns = Array(repeating: GridItem(.flexible(), spacing: 28), count: 6)
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationStack {
|
||||||
|
content
|
||||||
|
.musicDestinations()
|
||||||
|
}
|
||||||
|
.task { await load() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private var content: some View {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 44) {
|
||||||
|
header
|
||||||
|
|
||||||
|
WaveHeroButton {
|
||||||
|
player.startRotor(station: "user:onyourwave", name: "Моя волна")
|
||||||
|
}
|
||||||
|
|
||||||
|
if isLoading {
|
||||||
|
LoadingState(text: "Загружаем станции…").frame(height: 300)
|
||||||
|
} else if !stations.isEmpty {
|
||||||
|
VStack(alignment: .leading, spacing: 24) {
|
||||||
|
Text("Станции")
|
||||||
|
.font(.title2.weight(.semibold))
|
||||||
|
|
||||||
|
LazyVGrid(columns: columns, spacing: 40) {
|
||||||
|
ForEach(stations, id: \.id) { station in
|
||||||
|
CardButton(
|
||||||
|
title: station.name ?? station.id.tag,
|
||||||
|
subtitle: nil,
|
||||||
|
imageURL: YMImage.url(station.icon?.imageUrl, size: 200),
|
||||||
|
width: 250
|
||||||
|
) {
|
||||||
|
player.startRotor(
|
||||||
|
station: station.id.stringValue,
|
||||||
|
name: station.name ?? station.id.tag
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.vertical, 40)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
HStack(alignment: .firstTextBaseline) {
|
||||||
|
Text("Волна")
|
||||||
|
.font(.system(size: 56, weight: .bold))
|
||||||
|
Spacer()
|
||||||
|
if showSignOut {
|
||||||
|
Button("Выйти", role: .destructive) { state.signOut() }
|
||||||
|
} else {
|
||||||
|
Button {
|
||||||
|
showSignOut = true
|
||||||
|
} label: {
|
||||||
|
Label(
|
||||||
|
state.accountName.isEmpty ? "Аккаунт" : state.accountName,
|
||||||
|
systemImage: "person.crop.circle"
|
||||||
|
)
|
||||||
|
.font(.callout)
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func load() async {
|
||||||
|
isLoading = true
|
||||||
|
defer { isLoading = false }
|
||||||
|
do {
|
||||||
|
let dashboard = try await YMClient.shared.rotorDashboard()
|
||||||
|
var all = dashboard.stations.map(\.station)
|
||||||
|
if let list = try? await YMClient.shared.rotorStations() {
|
||||||
|
let known = Set(all.map(\.id.stringValue))
|
||||||
|
all += list.map(\.station).filter { !known.contains($0.id.stringValue) }
|
||||||
|
}
|
||||||
|
stations = all
|
||||||
|
} catch {
|
||||||
|
log.error("\(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one thing people actually come to this screen for, so it gets to be big.
|
||||||
|
struct WaveHeroButton: View {
|
||||||
|
let action: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: action) {
|
||||||
|
EmptyView()
|
||||||
|
}
|
||||||
|
.buttonStyle(WaveHeroStyle())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct WaveHeroStyle: ButtonStyle {
|
||||||
|
func makeBody(configuration: Configuration) -> some View {
|
||||||
|
StyleBody(configuration: configuration)
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct StyleBody: View {
|
||||||
|
@Environment(\.isFocused) private var isFocused
|
||||||
|
let configuration: ButtonStyleConfiguration
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ZStack(alignment: .leading) {
|
||||||
|
LinearGradient(
|
||||||
|
colors: [
|
||||||
|
Color(red: 0.42, green: 0.16, blue: 0.62),
|
||||||
|
Color(red: 0.75, green: 0.22, blue: 0.35),
|
||||||
|
Color(red: 0.95, green: 0.62, blue: 0.13),
|
||||||
|
],
|
||||||
|
startPoint: .topLeading,
|
||||||
|
endPoint: .bottomTrailing
|
||||||
|
)
|
||||||
|
|
||||||
|
HStack(spacing: 40) {
|
||||||
|
VStack(alignment: .leading, spacing: 14) {
|
||||||
|
Label("Радио", systemImage: "dot.radiowaves.left.and.right")
|
||||||
|
.font(.caption.weight(.semibold))
|
||||||
|
.foregroundStyle(.white.opacity(0.85))
|
||||||
|
.padding(.horizontal, 16)
|
||||||
|
.padding(.vertical, 8)
|
||||||
|
.background(.white.opacity(0.18), in: Capsule())
|
||||||
|
|
||||||
|
Text("Моя волна")
|
||||||
|
.font(.system(size: 68, weight: .heavy))
|
||||||
|
.foregroundStyle(.white)
|
||||||
|
|
||||||
|
Text("Бесконечный поток под ваш вкус")
|
||||||
|
.font(.title3)
|
||||||
|
.foregroundStyle(.white.opacity(0.8))
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
|
||||||
|
EqualizerBars(animating: isFocused)
|
||||||
|
.frame(width: 180, height: 130)
|
||||||
|
|
||||||
|
ZStack {
|
||||||
|
Circle()
|
||||||
|
.fill(.white)
|
||||||
|
.frame(width: 110, height: 110)
|
||||||
|
Image(systemName: "play.fill")
|
||||||
|
.font(.system(size: 42, weight: .bold))
|
||||||
|
.foregroundStyle(Color(red: 0.42, green: 0.16, blue: 0.62))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 56)
|
||||||
|
.padding(.vertical, 48)
|
||||||
|
}
|
||||||
|
.frame(height: 300)
|
||||||
|
.clipShape(RoundedRectangle(cornerRadius: 28))
|
||||||
|
.overlay {
|
||||||
|
if isFocused {
|
||||||
|
RoundedRectangle(cornerRadius: 28).strokeBorder(.white.opacity(0.9), lineWidth: 5)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Shadow only while focused, and no scaling: both are offscreen
|
||||||
|
// render passes on a card this large, and scaling a focused view is
|
||||||
|
// what makes tvOS swap in a snapshot of the screen.
|
||||||
|
.modifier(FocusShadow(active: isFocused))
|
||||||
|
.opacity(configuration.isPressed ? 0.85 : 1)
|
||||||
|
.animation(.easeOut(duration: 0.15), value: isFocused)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Five bars that idle flat and start dancing once the card takes focus.
|
||||||
|
struct EqualizerBars: View {
|
||||||
|
let animating: Bool
|
||||||
|
|
||||||
|
private let heights: [CGFloat] = [0.45, 0.95, 0.65, 1.0, 0.55]
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
TimelineView(.animation(minimumInterval: 1.0 / 20, paused: !animating)) { timeline in
|
||||||
|
let t = timeline.date.timeIntervalSinceReferenceDate
|
||||||
|
GeometryReader { geo in
|
||||||
|
HStack(alignment: .center, spacing: 14) {
|
||||||
|
ForEach(heights.indices, id: \.self) { index in
|
||||||
|
let phase = t * 2.4 + Double(index) * 0.7
|
||||||
|
// At rest the bars still read as an equaliser, just frozen.
|
||||||
|
let wobble = animating ? (sin(phase) * 0.35 + 0.65) : 0.75
|
||||||
|
Capsule()
|
||||||
|
.fill(.white.opacity(0.9))
|
||||||
|
.frame(height: geo.size.height * heights[index] * wobble)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(width: geo.size.width, height: geo.size.height, alignment: .center)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// Synced lyrics, with a run-in before the first line.
|
||||||
|
struct LyricsPane: View {
|
||||||
|
let lyrics: Lyrics?
|
||||||
|
|
||||||
|
/// Intros longer than this get dots for their whole length; shorter ones
|
||||||
|
/// only for the last few seconds.
|
||||||
|
private let longIntro: Double = 5
|
||||||
|
private let shortLead: Double = 4
|
||||||
|
/// Words appear this far before the dots run out, so the first line is
|
||||||
|
/// already on screen and rolls away instead of appearing from nothing.
|
||||||
|
private let wordsLead: Double = 1
|
||||||
|
|
||||||
|
@ObservedObject private var clock = PlayerController.shared.clock
|
||||||
|
|
||||||
|
init(lyrics: Lyrics?) {
|
||||||
|
self.lyrics = lyrics
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
// Dots and words share an origin, so the first line lands exactly where
|
||||||
|
// the dots were.
|
||||||
|
ZStack(alignment: .topLeading) {
|
||||||
|
if !linesVisible, let range = countdownRange {
|
||||||
|
CountdownDots(start: range.start, end: range.end)
|
||||||
|
.transition(.opacity)
|
||||||
|
}
|
||||||
|
|
||||||
|
if linesVisible {
|
||||||
|
LyricsLines(
|
||||||
|
lyrics: lyrics,
|
||||||
|
activeID: lyrics?.activeIndex(at: clock.currentTime),
|
||||||
|
armed: armed
|
||||||
|
)
|
||||||
|
.equatable()
|
||||||
|
.transition(.opacity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.animation(.easeInOut(duration: 0.45), value: linesVisible)
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var firstLineTime: Double? {
|
||||||
|
lyrics?.lines.first(where: { !$0.isBlank })?.time
|
||||||
|
}
|
||||||
|
|
||||||
|
private var countdownStart: Double {
|
||||||
|
guard let first = firstLineTime else { return 0 }
|
||||||
|
return first > longIntro ? 0 : max(first - shortLead, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var countdownRange: (start: Double, end: Double)? {
|
||||||
|
guard let first = firstLineTime else { return nil }
|
||||||
|
let now = clock.currentTime
|
||||||
|
guard now >= countdownStart, now < first else { return nil }
|
||||||
|
return (countdownStart, first)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var linesVisible: Bool {
|
||||||
|
guard let first = firstLineTime else { return true }
|
||||||
|
return clock.currentTime >= first - wordsLead
|
||||||
|
}
|
||||||
|
|
||||||
|
private var armed: Bool {
|
||||||
|
guard firstLineTime != nil else { return true }
|
||||||
|
return clock.currentTime >= countdownStart
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Three dots filling one after another across the run-in. Each fills all the
|
||||||
|
/// way before the next one starts.
|
||||||
|
private struct CountdownDots: View {
|
||||||
|
let start: Double
|
||||||
|
let end: Double
|
||||||
|
|
||||||
|
@ObservedObject private var clock = PlayerController.shared.clock
|
||||||
|
|
||||||
|
init(start: Double, end: Double) {
|
||||||
|
self.start = start
|
||||||
|
self.end = end
|
||||||
|
}
|
||||||
|
|
||||||
|
private var progress: Double {
|
||||||
|
let span = max(end - start, 0.001)
|
||||||
|
return min(max((clock.currentTime - start) / span, 0), 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(spacing: 22) {
|
||||||
|
ForEach(0 ..< 3, id: \.self) { index in
|
||||||
|
let fill = min(max(progress * 3 - Double(index), 0), 1)
|
||||||
|
Circle()
|
||||||
|
.fill(.white.opacity(0.18 + 0.77 * fill))
|
||||||
|
.frame(width: 30, height: 30)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.top, 26)
|
||||||
|
// The clock ticks five times a second; this rides between the ticks.
|
||||||
|
.animation(.linear(duration: 0.2), value: progress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The line being sung sits at the top, the lines still to come fade away below
|
||||||
|
/// it, and everything already sung is gone.
|
||||||
|
///
|
||||||
|
/// Not a ScrollView: driving a scroll offset from a timer made the highlight
|
||||||
|
/// drift out of view.
|
||||||
|
private struct LyricsLines: View, Equatable {
|
||||||
|
let lyrics: Lyrics?
|
||||||
|
let activeID: Int?
|
||||||
|
let armed: Bool
|
||||||
|
|
||||||
|
private let window = 6
|
||||||
|
|
||||||
|
/// Equatable collapses five ticks a second into one rebuild per line.
|
||||||
|
static func == (lhs: Self, rhs: Self) -> Bool {
|
||||||
|
lhs.activeID == rhs.activeID
|
||||||
|
&& lhs.armed == rhs.armed
|
||||||
|
&& lhs.lyrics == rhs.lyrics
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
rolling
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var visible: [LyricsLine] {
|
||||||
|
guard armed else { return [] }
|
||||||
|
let sung = (lyrics?.lines ?? []).filter { !$0.isBlank }
|
||||||
|
guard let anchor = activeID ?? sung.first?.id else { return [] }
|
||||||
|
return Array(sung.filter { $0.id >= anchor }.prefix(window))
|
||||||
|
}
|
||||||
|
|
||||||
|
private var rolling: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 34) {
|
||||||
|
ForEach(visible) { line in
|
||||||
|
Text(line.text)
|
||||||
|
.font(.system(size: line.id == activeID ? 96 : 76, weight: .bold))
|
||||||
|
.foregroundStyle(.white.opacity(opacity(for: line)))
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.transition(.opacity)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
.animation(.easeInOut(duration: 0.35), value: activeID)
|
||||||
|
.clipped()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sung line is solid; each line further ahead is dimmer than the last.
|
||||||
|
private func opacity(for line: LyricsLine) -> Double {
|
||||||
|
guard let activeID else { return 0.4 }
|
||||||
|
if line.id == activeID { return 1 }
|
||||||
|
let position = visible.firstIndex(where: { $0.id == line.id }) ?? 0
|
||||||
|
return max(0.08, 0.32 - Double(position) * 0.07)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// The player screen.
|
||||||
|
///
|
||||||
|
/// Every width and height here is a constant. Whether a track has lyrics comes
|
||||||
|
/// from its metadata, which arrives with the track, so the two columns are
|
||||||
|
/// placed once per song and never move while it plays.
|
||||||
|
struct NowPlayingView: View {
|
||||||
|
@EnvironmentObject private var player: PlayerController
|
||||||
|
|
||||||
|
private enum Control: Hashable { case chrome, scrubber, previous, play, next, like }
|
||||||
|
|
||||||
|
private let stageHeight: CGFloat = 620
|
||||||
|
private let detailsWidth: CGFloat = 430
|
||||||
|
private let lyricsWidth: CGFloat = 1150
|
||||||
|
|
||||||
|
@State private var likeBusy = false
|
||||||
|
@FocusState private var focus: Control?
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ZStack {
|
||||||
|
BlurredBackdrop(url: player.current?.coverURL(size: 200))
|
||||||
|
if let track = player.current {
|
||||||
|
content(for: track)
|
||||||
|
} else {
|
||||||
|
idle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var idle: some View {
|
||||||
|
VStack(spacing: 16) {
|
||||||
|
Image(systemName: "music.note")
|
||||||
|
.font(.system(size: 80))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Text("Ничего не играет")
|
||||||
|
.font(.title2)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Layout
|
||||||
|
|
||||||
|
private func content(for track: Track) -> some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
// The tab bar floats over the content: this strip reserves room for
|
||||||
|
// it and gives focus a step on the way back up to it.
|
||||||
|
Color.clear
|
||||||
|
.frame(height: 96)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.focusable()
|
||||||
|
.focused($focus, equals: .chrome)
|
||||||
|
|
||||||
|
HStack(alignment: .top, spacing: showsLyrics ? 72 : 0) {
|
||||||
|
details(for: track)
|
||||||
|
.frame(width: detailsWidth, height: stageHeight, alignment: .top)
|
||||||
|
.clipped()
|
||||||
|
|
||||||
|
LyricsPane(lyrics: player.lyricsState == .ready ? player.lyrics : nil)
|
||||||
|
.frame(
|
||||||
|
width: showsLyrics ? lyricsWidth : 0,
|
||||||
|
height: stageHeight,
|
||||||
|
alignment: .topLeading
|
||||||
|
)
|
||||||
|
.clipped()
|
||||||
|
.opacity(showsLyrics ? 1 : 0)
|
||||||
|
}
|
||||||
|
.frame(
|
||||||
|
maxWidth: .infinity,
|
||||||
|
maxHeight: .infinity,
|
||||||
|
alignment: showsLyrics ? .topLeading : .top
|
||||||
|
)
|
||||||
|
|
||||||
|
transportBar
|
||||||
|
}
|
||||||
|
.padding(.bottom, 24)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var showsLyrics: Bool {
|
||||||
|
player.current?.lyricsInfo?.hasSynced ?? true
|
||||||
|
}
|
||||||
|
|
||||||
|
private func details(for track: Track) -> some View {
|
||||||
|
VStack(alignment: .leading, spacing: 24) {
|
||||||
|
CoverImage(url: track.coverURL(size: 400), corner: 18)
|
||||||
|
.frame(width: 390, height: 390)
|
||||||
|
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
sourceLabel
|
||||||
|
Text(track.displayTitle)
|
||||||
|
.font(.system(size: 40, weight: .bold))
|
||||||
|
.lineLimit(2)
|
||||||
|
Text(track.artistNames)
|
||||||
|
.font(.system(size: 26))
|
||||||
|
.foregroundStyle(.white.opacity(0.65))
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var sourceLabel: some View {
|
||||||
|
switch player.source {
|
||||||
|
case let .rotor(_, name):
|
||||||
|
Label(name.uppercased(), systemImage: "dot.radiowaves.left.and.right")
|
||||||
|
.font(.caption.weight(.semibold))
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
case let .collection(name):
|
||||||
|
Text(name.uppercased())
|
||||||
|
.font(.caption.weight(.semibold))
|
||||||
|
.foregroundStyle(Color.ymAccent)
|
||||||
|
case .none:
|
||||||
|
EmptyView()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Transport
|
||||||
|
|
||||||
|
private var transportBar: some View {
|
||||||
|
VStack(alignment: .trailing, spacing: 16) {
|
||||||
|
HStack(spacing: 20) {
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
|
||||||
|
Button { player.previous() } label: {
|
||||||
|
Image(systemName: "backward.fill")
|
||||||
|
}
|
||||||
|
.buttonStyle(GlyphButtonStyle())
|
||||||
|
.focused($focus, equals: .previous)
|
||||||
|
|
||||||
|
Button { player.togglePlayPause() } label: {
|
||||||
|
Image(systemName: player.isPlaying ? "pause.fill" : "play.fill")
|
||||||
|
}
|
||||||
|
.buttonStyle(GlyphButtonStyle(prominent: true))
|
||||||
|
.focused($focus, equals: .play)
|
||||||
|
|
||||||
|
Button { player.next() } label: {
|
||||||
|
Image(systemName: "forward.fill")
|
||||||
|
}
|
||||||
|
.buttonStyle(GlyphButtonStyle())
|
||||||
|
.focused($focus, equals: .next)
|
||||||
|
|
||||||
|
Button { toggleLike() } label: {
|
||||||
|
Image(systemName: isLiked ? "heart.fill" : "heart")
|
||||||
|
}
|
||||||
|
.buttonStyle(GlyphButtonStyle(tinted: isLiked))
|
||||||
|
.focused($focus, equals: .like)
|
||||||
|
.disabled(likeBusy)
|
||||||
|
}
|
||||||
|
|
||||||
|
Scrubber(
|
||||||
|
seek: { player.seek(to: $0) },
|
||||||
|
togglePlayPause: { player.togglePlayPause() }
|
||||||
|
)
|
||||||
|
.focused($focus, equals: .scrubber)
|
||||||
|
}
|
||||||
|
.focusSection()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var isLiked: Bool { player.isLiked(player.current) }
|
||||||
|
|
||||||
|
private func toggleLike() {
|
||||||
|
likeBusy = true
|
||||||
|
Task {
|
||||||
|
await player.toggleLikeCurrent()
|
||||||
|
likeBusy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A glyph that takes a solid disc on focus. No scaling: growing a focused view
|
||||||
|
/// makes tvOS swap in a snapshot of the screen.
|
||||||
|
private struct GlyphButtonStyle: ButtonStyle {
|
||||||
|
var tinted = false
|
||||||
|
var prominent = false
|
||||||
|
|
||||||
|
func makeBody(configuration: Configuration) -> some View {
|
||||||
|
StyleBody(configuration: configuration, tinted: tinted, prominent: prominent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct StyleBody: View {
|
||||||
|
@Environment(\.isFocused) private var isFocused
|
||||||
|
@Environment(\.isEnabled) private var isEnabled
|
||||||
|
let configuration: ButtonStyleConfiguration
|
||||||
|
let tinted: Bool
|
||||||
|
let prominent: Bool
|
||||||
|
|
||||||
|
private var foreground: Color {
|
||||||
|
if isFocused { return .black }
|
||||||
|
return tinted ? .ymAccent : .white
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
configuration.label
|
||||||
|
.font(.system(size: prominent ? 34 : 28, weight: .semibold))
|
||||||
|
.foregroundStyle(foreground)
|
||||||
|
.opacity(isEnabled ? (configuration.isPressed ? 0.7 : 1) : 0.3)
|
||||||
|
.frame(width: prominent ? 88 : 72, height: prominent ? 88 : 72)
|
||||||
|
.background {
|
||||||
|
Circle().fill(
|
||||||
|
isFocused
|
||||||
|
? AnyShapeStyle(.white)
|
||||||
|
: AnyShapeStyle(.white.opacity(prominent ? 0.22 : 0.12))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.animation(.easeOut(duration: 0.15), value: isFocused)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// Full-width transport bar.
|
||||||
|
///
|
||||||
|
/// Swipes in the same direction build up speed, the target is previewed while
|
||||||
|
/// scrubbing, and the seek is committed once the swiping stops.
|
||||||
|
struct Scrubber: View {
|
||||||
|
let seek: (Double) -> Void
|
||||||
|
let togglePlayPause: () -> Void
|
||||||
|
|
||||||
|
private let steps: [Double] = [5, 10, 20, 30, 45, 60]
|
||||||
|
private let streakWindow: TimeInterval = 0.4
|
||||||
|
private let commitDelay: UInt64 = 500_000_000
|
||||||
|
|
||||||
|
@ObservedObject private var clock = PlayerController.shared.clock
|
||||||
|
@FocusState private var focused: Bool
|
||||||
|
|
||||||
|
@State private var preview: Double?
|
||||||
|
@State private var lastMove = Date.distantPast
|
||||||
|
@State private var streak = 0
|
||||||
|
@State private var commitTask: Task<Void, Never>?
|
||||||
|
|
||||||
|
private var position: Double { preview ?? clock.currentTime }
|
||||||
|
|
||||||
|
private var fraction: Double {
|
||||||
|
guard clock.duration > 0 else { return 0 }
|
||||||
|
return min(max(position / clock.duration, 0), 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 12) {
|
||||||
|
bar.frame(height: 16)
|
||||||
|
|
||||||
|
HStack {
|
||||||
|
Text(formatTime(position))
|
||||||
|
Spacer()
|
||||||
|
Text("-" + formatTime(max(clock.duration - position, 0)))
|
||||||
|
}
|
||||||
|
.font(.system(size: 24, weight: .medium).monospacedDigit())
|
||||||
|
.foregroundStyle(.white.opacity(focused ? 0.95 : 0.55))
|
||||||
|
}
|
||||||
|
.padding(.vertical, 10)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.focusable()
|
||||||
|
.focused($focused)
|
||||||
|
.onMoveCommand { direction in
|
||||||
|
switch direction {
|
||||||
|
case .left: nudge(-1)
|
||||||
|
case .right: nudge(1)
|
||||||
|
default: break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onExitCommand { cancelScrub() }
|
||||||
|
.onPlayPauseCommand { togglePlayPause() }
|
||||||
|
.onChange(of: focused) { _, isFocused in
|
||||||
|
if !isFocused { cancelScrub() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fixed height; only the drawing inside reacts to focus, so taking focus
|
||||||
|
/// never re-lays-out the screen.
|
||||||
|
private var bar: some View {
|
||||||
|
GeometryReader { geo in
|
||||||
|
let height: CGFloat = focused ? 14 : 8
|
||||||
|
let knob: CGFloat = preview == nil ? 26 : 34
|
||||||
|
|
||||||
|
ZStack(alignment: .leading) {
|
||||||
|
Capsule()
|
||||||
|
.fill(.white.opacity(focused ? 0.32 : 0.2))
|
||||||
|
.frame(height: height)
|
||||||
|
Capsule()
|
||||||
|
.fill(.white)
|
||||||
|
.frame(width: geo.size.width * fraction, height: height)
|
||||||
|
if focused {
|
||||||
|
Circle()
|
||||||
|
.fill(.white)
|
||||||
|
.frame(width: knob, height: knob)
|
||||||
|
.offset(x: geo.size.width * fraction - knob / 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(width: geo.size.width, height: geo.size.height, alignment: .leading)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func nudge(_ direction: Double) {
|
||||||
|
guard clock.duration > 0 else { return }
|
||||||
|
|
||||||
|
let now = Date()
|
||||||
|
streak = now.timeIntervalSince(lastMove) < streakWindow
|
||||||
|
? min(streak + 1, steps.count - 1)
|
||||||
|
: 0
|
||||||
|
lastMove = now
|
||||||
|
|
||||||
|
let target = (preview ?? clock.currentTime) + direction * steps[streak]
|
||||||
|
preview = min(max(target, 0), clock.duration)
|
||||||
|
|
||||||
|
commitTask?.cancel()
|
||||||
|
commitTask = Task {
|
||||||
|
try? await Task.sleep(nanoseconds: commitDelay)
|
||||||
|
guard !Task.isCancelled, let target = preview else { return }
|
||||||
|
seek(target)
|
||||||
|
preview = nil
|
||||||
|
streak = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func cancelScrub() {
|
||||||
|
commitTask?.cancel()
|
||||||
|
preview = nil
|
||||||
|
streak = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct RootView: View {
|
||||||
|
@EnvironmentObject private var player: PlayerController
|
||||||
|
@State private var selection = 0
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
TabView(selection: $selection) {
|
||||||
|
MyWaveView()
|
||||||
|
.tabItem { Label("Волна", systemImage: "dot.radiowaves.left.and.right") }
|
||||||
|
.tag(0)
|
||||||
|
|
||||||
|
LikesView()
|
||||||
|
.tabItem { Label("Мне нравится", systemImage: "heart.fill") }
|
||||||
|
.tag(1)
|
||||||
|
|
||||||
|
NowPlayingView()
|
||||||
|
.tabItem { Label("Сейчас играет", systemImage: "play.circle.fill") }
|
||||||
|
.tag(2)
|
||||||
|
|
||||||
|
SearchView()
|
||||||
|
.tabItem { Image(systemName: "magnifyingglass") }
|
||||||
|
.tag(3)
|
||||||
|
}
|
||||||
|
.onPlayPauseCommand { player.togglePlayPause() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct SearchView: View {
|
||||||
|
@EnvironmentObject private var player: PlayerController
|
||||||
|
|
||||||
|
@State private var query = ""
|
||||||
|
@State private var tracks: [Track] = []
|
||||||
|
@State private var albums: [Album] = []
|
||||||
|
@State private var artists: [Artist] = []
|
||||||
|
@State private var isSearching = false
|
||||||
|
@State private var searchTask: Task<Void, Never>?
|
||||||
|
|
||||||
|
private let grid = [GridItem(.adaptive(minimum: 280), spacing: 60)]
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationStack {
|
||||||
|
results
|
||||||
|
// tvOS turns this into the system search scene: keyboard on the
|
||||||
|
// left, these results on the right, exactly like Apple Music.
|
||||||
|
.searchable(text: $query, prompt: "Исполнители, треки, альбомы")
|
||||||
|
.musicDestinations()
|
||||||
|
}
|
||||||
|
.onChange(of: query) { _, new in scheduleSearch(for: new) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var results: some View {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 50) {
|
||||||
|
if isSearching {
|
||||||
|
LoadingState(text: "Ищем…").frame(height: 400)
|
||||||
|
} else if query.trimmingCharacters(in: .whitespaces).isEmpty {
|
||||||
|
placeholder
|
||||||
|
} else if tracks.isEmpty, albums.isEmpty, artists.isEmpty {
|
||||||
|
placeholder
|
||||||
|
} else {
|
||||||
|
if !artists.isEmpty { artistSection.focusSection() }
|
||||||
|
if !tracks.isEmpty { trackSection.focusSection() }
|
||||||
|
if !albums.isEmpty { albumSection.focusSection() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.vertical, 40)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var placeholder: some View {
|
||||||
|
VStack(spacing: 16) {
|
||||||
|
Image(systemName: "magnifyingglass")
|
||||||
|
.font(.system(size: 72))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Text(query.isEmpty ? "Что послушаем?" : "Ничего не нашлось")
|
||||||
|
.font(.title2)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity)
|
||||||
|
.padding(.top, 120)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var artistSection: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
Text("Исполнители").font(.title2.weight(.semibold))
|
||||||
|
ScrollView(.horizontal, showsIndicators: false) {
|
||||||
|
HStack(alignment: .top, spacing: 60) {
|
||||||
|
ForEach(artists.prefix(12), id: \.id) { artist in
|
||||||
|
PosterLink(
|
||||||
|
title: artist.name,
|
||||||
|
subtitle: nil,
|
||||||
|
imageURL: artist.coverURL(size: 200),
|
||||||
|
route: .artist(artist),
|
||||||
|
circular: true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.vertical, 24)
|
||||||
|
}
|
||||||
|
.scrollClipDisabled()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var trackSection: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
HStack(alignment: .firstTextBaseline) {
|
||||||
|
Text("Треки").font(.title2.weight(.semibold))
|
||||||
|
Spacer()
|
||||||
|
Button {
|
||||||
|
play(tracks, from: 0, title: "Поиск: \(query)")
|
||||||
|
} label: {
|
||||||
|
Label("Слушать всё", systemImage: "play.fill").font(.callout)
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyVGrid(columns: grid, spacing: 60) {
|
||||||
|
ForEach(Array(tracks.prefix(24).enumerated()), id: \.offset) { pair in
|
||||||
|
CardButton(
|
||||||
|
title: pair.element.displayTitle,
|
||||||
|
subtitle: pair.element.artistNames,
|
||||||
|
imageURL: pair.element.coverURL(size: 200)
|
||||||
|
) {
|
||||||
|
play(tracks, from: pair.offset, title: "Поиск: \(query)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var albumSection: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
Text("Альбомы").font(.title2.weight(.semibold))
|
||||||
|
LazyVGrid(columns: grid, spacing: 60) {
|
||||||
|
ForEach(albums.prefix(12), id: \.id) { album in
|
||||||
|
PosterLink(
|
||||||
|
title: album.displayTitle,
|
||||||
|
subtitle: album.artistNames,
|
||||||
|
imageURL: album.coverURL(size: 200),
|
||||||
|
route: .album(album)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Actions
|
||||||
|
|
||||||
|
private func play(_ list: [Track], from index: Int, title: String) {
|
||||||
|
player.play(tracks: list, startAt: index, source: .collection(title))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Search
|
||||||
|
|
||||||
|
private func scheduleSearch(for text: String) {
|
||||||
|
searchTask?.cancel()
|
||||||
|
let trimmed = text.trimmingCharacters(in: .whitespaces)
|
||||||
|
guard trimmed.count >= 2 else {
|
||||||
|
tracks = []; albums = []; artists = []
|
||||||
|
isSearching = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isSearching = true
|
||||||
|
searchTask = Task {
|
||||||
|
// Let the on-screen keyboard settle before hitting the API.
|
||||||
|
try? await Task.sleep(nanoseconds: 450_000_000)
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
do {
|
||||||
|
let result = try await YMClient.shared.search(trimmed, type: "all")
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
tracks = result.tracks?.results ?? []
|
||||||
|
albums = result.albums?.results ?? []
|
||||||
|
artists = result.artists?.results ?? []
|
||||||
|
} catch {
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
log.error("\(error.localizedDescription)")
|
||||||
|
}
|
||||||
|
isSearching = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
name: YaMusek
|
||||||
|
options:
|
||||||
|
bundleIdPrefix: com.yamusek
|
||||||
|
deploymentTarget:
|
||||||
|
tvOS: "17.0"
|
||||||
|
createIntermediateGroups: true
|
||||||
|
groupSortPosition: top
|
||||||
|
|
||||||
|
settings:
|
||||||
|
base:
|
||||||
|
SWIFT_VERSION: "5.0"
|
||||||
|
DEVELOPMENT_TEAM: ""
|
||||||
|
CODE_SIGN_STYLE: Automatic
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING: YES
|
||||||
|
SWIFT_STRICT_CONCURRENCY: minimal
|
||||||
|
|
||||||
|
targets:
|
||||||
|
YaMusek:
|
||||||
|
type: application
|
||||||
|
platform: tvOS
|
||||||
|
deploymentTarget: "17.0"
|
||||||
|
sources:
|
||||||
|
- path: Sources
|
||||||
|
- path: Resources/Assets.xcassets
|
||||||
|
info:
|
||||||
|
path: Resources/Info.plist
|
||||||
|
properties:
|
||||||
|
CFBundleDisplayName: YaMusek
|
||||||
|
CFBundleShortVersionString: "1.0"
|
||||||
|
CFBundleVersion: "1"
|
||||||
|
UIBackgroundModes: [audio]
|
||||||
|
UIUserInterfaceStyle: Dark
|
||||||
|
NSAppTransportSecurity:
|
||||||
|
NSAllowsArbitraryLoads: true
|
||||||
|
settings:
|
||||||
|
base:
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER: com.yamusek.tv
|
||||||
|
ASSETCATALOG_COMPILER_APPICON_NAME: "App Icon & Top Shelf Image"
|
||||||
|
TARGETED_DEVICE_FAMILY: "3"
|
||||||
|
INFOPLIST_KEY_UIUserInterfaceStyle: Dark
|
||||||
|
SWIFT_EMIT_LOC_STRINGS: YES
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Re-sign and reinstall YaMusek so a free 7-day provisioning profile never
|
||||||
|
# expires in your face. Meant to be run by launchd once a day; see
|
||||||
|
# tools/install-autorefresh.sh.
|
||||||
|
#
|
||||||
|
# Config comes from tools/.autorefresh.env (written by install-autorefresh.sh):
|
||||||
|
# TEAM=XXXXXXXXXX
|
||||||
|
# BUNDLE=com.yamusek.tv
|
||||||
|
# DEVICE=<Apple TV name or UDID>
|
||||||
|
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
LOG="${TMPDIR:-/tmp}/yamusek-autorefresh.log"
|
||||||
|
exec >>"$LOG" 2>&1
|
||||||
|
echo "=== $(date '+%Y-%m-%d %H:%M:%S') refresh start"
|
||||||
|
|
||||||
|
ENV_FILE="tools/.autorefresh.env"
|
||||||
|
if [[ ! -f "$ENV_FILE" ]]; then
|
||||||
|
echo "no $ENV_FILE - run tools/install-autorefresh.sh first"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# shellcheck disable=SC1090
|
||||||
|
source "$ENV_FILE"
|
||||||
|
|
||||||
|
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
|
||||||
|
|
||||||
|
# Nothing to do if the Apple TV is off or off-network; launchd will try again.
|
||||||
|
if ! xcrun devicectl list devices 2>/dev/null | grep -q -- "$DEVICE"; then
|
||||||
|
echo "device '$DEVICE' not reachable, skipping"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
./tools/install.sh "$TEAM" "$BUNDLE" "$DEVICE"
|
||||||
|
status=$?
|
||||||
|
echo "=== refresh finished with status $status"
|
||||||
|
exit $status
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Sanity-check a Yandex Music OAuth token and both stream-signing schemes
|
||||||
|
# from the Mac, before blaming the Apple TV.
|
||||||
|
#
|
||||||
|
# ./tools/check-api.sh <OAUTH_TOKEN> [TRACK_ID]
|
||||||
|
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
TOKEN="${1:-}"
|
||||||
|
TRACK="${2:-}"
|
||||||
|
API="https://api.music.yandex.net"
|
||||||
|
CLIENT="YandexMusicAndroid/24023621"
|
||||||
|
WEB_SECRET="${YM_WEB_SECRET:-7tvSmFbyf5hJnIHhCimDDD}"
|
||||||
|
LEGACY_SALT="XGRlBW9FXlekgbPrRHuSiA"
|
||||||
|
|
||||||
|
if [[ -z "$TOKEN" ]]; then
|
||||||
|
echo "usage: $0 <OAUTH_TOKEN> [TRACK_ID]" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
api() {
|
||||||
|
curl -sS -H "Authorization: OAuth $TOKEN" \
|
||||||
|
-H "X-Yandex-Music-Client: $CLIENT" \
|
||||||
|
-H "User-Agent: Yandex-Music-API" \
|
||||||
|
"$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
say() { printf "\n\033[1m== %s\033[0m\n" "$1"; }
|
||||||
|
|
||||||
|
say "account/status"
|
||||||
|
STATUS=$(api "$API/account/status")
|
||||||
|
UID_=$(printf '%s' "$STATUS" | python3 -c 'import sys,json;print(json.load(sys.stdin)["result"]["account"].get("uid",""))' 2>/dev/null)
|
||||||
|
if [[ -z "$UID_" ]]; then
|
||||||
|
echo "FAILED - token rejected:"; printf '%s' "$STATUS" | head -c 500; echo; exit 1
|
||||||
|
fi
|
||||||
|
printf '%s' "$STATUS" | python3 -c '
|
||||||
|
import sys, json
|
||||||
|
r = json.load(sys.stdin)["result"]
|
||||||
|
a = r["account"]
|
||||||
|
print("uid: ", a.get("uid"))
|
||||||
|
print("login: ", a.get("login"))
|
||||||
|
print("name: ", a.get("displayName") or a.get("fullName"))
|
||||||
|
print("has plus: ", (r.get("plus") or {}).get("hasPlus"))
|
||||||
|
'
|
||||||
|
|
||||||
|
if [[ -z "$TRACK" ]]; then
|
||||||
|
say "likes/tracks"
|
||||||
|
LIKES=$(api "$API/users/$UID_/likes/tracks")
|
||||||
|
TRACK=$(printf '%s' "$LIKES" | python3 -c '
|
||||||
|
import sys, json
|
||||||
|
t = json.load(sys.stdin)["result"]["library"]["tracks"]
|
||||||
|
sys.stderr.write("%d liked tracks\n" % len(t))
|
||||||
|
print(t[0]["id"] if t else "")
|
||||||
|
')
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "$TRACK" ]]; then
|
||||||
|
echo "No track to test the stream with - pass TRACK_ID as the second argument."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
echo "track under test: $TRACK"
|
||||||
|
|
||||||
|
say "get-file-info (HMAC-SHA256, lossless)"
|
||||||
|
TS=$(date +%s)
|
||||||
|
QUALITY="lossless"
|
||||||
|
CODECS="flac,aac,he-aac,mp3"
|
||||||
|
TRANSPORT="raw"
|
||||||
|
# The signature joins the codec list WITHOUT commas; the URL keeps them.
|
||||||
|
MSG="${TS}${TRACK}${QUALITY}${CODECS//,/}${TRANSPORT}"
|
||||||
|
SIGN=$(printf '%s' "$MSG" | openssl dgst -sha256 -hmac "$WEB_SECRET" -binary | base64 | tr -d '=')
|
||||||
|
SIGN_ENC=$(python3 -c 'import sys,urllib.parse;print(urllib.parse.quote(sys.argv[1],safe=""))' "$SIGN")
|
||||||
|
RESP=$(curl -sS -H "Authorization: OAuth $TOKEN" \
|
||||||
|
-H "X-Yandex-Music-Client: YandexMusicWebNext/1.0.0" \
|
||||||
|
-H "X-Yandex-Music-Without-Invocation-Info: 1" \
|
||||||
|
-H "Origin: https://music.yandex.ru" \
|
||||||
|
-H "Referer: https://music.yandex.ru/" \
|
||||||
|
"$API/get-file-info?ts=$TS&trackId=$TRACK&quality=$QUALITY&codecs=flac%2Caac%2Che-aac%2Cmp3&transports=$TRANSPORT&sign=$SIGN_ENC")
|
||||||
|
printf '%s' "$RESP" | head -c 700; echo
|
||||||
|
|
||||||
|
FI_URL=$(printf '%s' "$RESP" | python3 -c '
|
||||||
|
import sys, json
|
||||||
|
try:
|
||||||
|
d = json.load(sys.stdin)
|
||||||
|
except Exception:
|
||||||
|
print(""); sys.exit()
|
||||||
|
info = d.get("downloadInfo") or (d.get("result") or {}).get("downloadInfo") or {}
|
||||||
|
url = info.get("url") or (info.get("urls") or [""])[0]
|
||||||
|
print(url)
|
||||||
|
')
|
||||||
|
if [[ -n "$FI_URL" ]]; then
|
||||||
|
echo "probe: $(curl -o /dev/null -sS -w '%{http_code} %{content_type} %{size_download}B' -r 0-2047 "$FI_URL")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
say "download-info (MD5, mp3)"
|
||||||
|
DI=$(api "$API/tracks/$TRACK/download-info")
|
||||||
|
INFO_URL=$(printf '%s' "$DI" | python3 -c '
|
||||||
|
import sys, json
|
||||||
|
try:
|
||||||
|
items = json.load(sys.stdin)["result"]
|
||||||
|
except Exception:
|
||||||
|
print(""); sys.exit()
|
||||||
|
items = [i for i in items if not i.get("preview")]
|
||||||
|
if not items:
|
||||||
|
print(""); sys.exit()
|
||||||
|
best = max(items, key=lambda i: i.get("bitrateInKbps") or 0)
|
||||||
|
print(best.get("downloadInfoUrl", ""))
|
||||||
|
')
|
||||||
|
if [[ -z "$INFO_URL" ]]; then
|
||||||
|
echo "download-info empty:"; printf '%s' "$DI" | head -c 400; echo
|
||||||
|
else
|
||||||
|
XML=$(api "$INFO_URL")
|
||||||
|
read -r HOST XPATH XTS XS <<<"$(printf '%s' "$XML" | python3 -c '
|
||||||
|
import sys, xml.dom.minidom as m
|
||||||
|
d = m.parseString(sys.stdin.read())
|
||||||
|
g = lambda t: d.getElementsByTagName(t)[0].firstChild.data
|
||||||
|
print(g("host"), g("path"), g("ts"), g("s"))
|
||||||
|
')"
|
||||||
|
MD5=$(printf '%s' "${LEGACY_SALT}${XPATH:1}${XS}" | openssl md5 -r | cut -d' ' -f1)
|
||||||
|
URL="https://$HOST/get-mp3/$MD5/$XTS$XPATH"
|
||||||
|
echo "direct: $URL"
|
||||||
|
echo "probe: $(curl -o /dev/null -sS -w '%{http_code} %{content_type} %{size_download}B' -r 0-2047 "$URL")"
|
||||||
|
fi
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Install a launchd agent that re-signs and reinstalls YaMusek every day, so the
|
||||||
|
# 7-day free provisioning profile never lapses.
|
||||||
|
#
|
||||||
|
# ./tools/install-autorefresh.sh <TEAM_ID> [BUNDLE_ID] [DEVICE_NAME_OR_UDID]
|
||||||
|
#
|
||||||
|
# Remove it again with:
|
||||||
|
# launchctl bootout gui/$UID ~/Library/LaunchAgents/com.yamusek.refresh.plist
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
REPO="$(pwd)"
|
||||||
|
|
||||||
|
TEAM="${1:-}"
|
||||||
|
BUNDLE="${2:-com.yamusek.tv}"
|
||||||
|
DEVICE="${3:-}"
|
||||||
|
|
||||||
|
if [[ -z "$TEAM" ]]; then
|
||||||
|
echo "usage: $0 <TEAM_ID> [BUNDLE_ID] [DEVICE_NAME_OR_UDID]" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "$DEVICE" ]]; then
|
||||||
|
echo "==> paired devices"
|
||||||
|
xcrun devicectl list devices
|
||||||
|
echo
|
||||||
|
read -r -p "Device name or UDID: " DEVICE
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat > tools/.autorefresh.env <<EOF
|
||||||
|
TEAM=$TEAM
|
||||||
|
BUNDLE=$BUNDLE
|
||||||
|
DEVICE=$DEVICE
|
||||||
|
EOF
|
||||||
|
chmod 600 tools/.autorefresh.env
|
||||||
|
|
||||||
|
PLIST="$HOME/Library/LaunchAgents/com.yamusek.refresh.plist"
|
||||||
|
mkdir -p "$(dirname "$PLIST")"
|
||||||
|
cat > "$PLIST" <<EOF
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key><string>com.yamusek.refresh</string>
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
<string>$REPO/tools/auto-refresh.sh</string>
|
||||||
|
</array>
|
||||||
|
<key>StartCalendarInterval</key>
|
||||||
|
<dict>
|
||||||
|
<key>Hour</key><integer>4</integer>
|
||||||
|
<key>Minute</key><integer>30</integer>
|
||||||
|
</dict>
|
||||||
|
<key>RunAtLoad</key><false/>
|
||||||
|
<key>StandardOutPath</key><string>${TMPDIR:-/tmp}/yamusek-autorefresh.out</string>
|
||||||
|
<key>StandardErrorPath</key><string>${TMPDIR:-/tmp}/yamusek-autorefresh.err</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
|
EOF
|
||||||
|
|
||||||
|
launchctl bootout "gui/$UID" "$PLIST" 2>/dev/null || true
|
||||||
|
launchctl bootstrap "gui/$UID" "$PLIST"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Agent installed. It runs daily at 04:30 and quietly skips days when the"
|
||||||
|
echo "Apple TV is off or off-network, so the signature never gets close to expiring."
|
||||||
|
echo "Log: ${TMPDIR:-/tmp}/yamusek-autorefresh.log"
|
||||||
|
echo "Run it once now with: ./tools/auto-refresh.sh"
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Build YaMusek and install it on a paired Apple TV.
|
||||||
|
#
|
||||||
|
# ./tools/install.sh <TEAM_ID> [BUNDLE_ID] [DEVICE_NAME_OR_UDID]
|
||||||
|
#
|
||||||
|
# TEAM_ID comes from Xcode > Settings > Accounts > Manage Certificates,
|
||||||
|
# or from `security find-identity -v -p codesigning` (the 10-char id in
|
||||||
|
# parentheses of "Apple Development: you (XXXXXXXXXX)").
|
||||||
|
#
|
||||||
|
# The Apple TV must already be paired: Xcode > Window > Devices and Simulators,
|
||||||
|
# with the TV on Settings > Remotes and Devices > Remote App and Devices.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
TEAM="${1:-}"
|
||||||
|
BUNDLE="${2:-com.yamusek.tv}"
|
||||||
|
DEVICE="${3:-}"
|
||||||
|
|
||||||
|
if [[ -z "$TEAM" ]]; then
|
||||||
|
echo "usage: $0 <TEAM_ID> [BUNDLE_ID] [DEVICE_NAME_OR_UDID]" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! command -v xcodegen >/dev/null; then
|
||||||
|
echo "xcodegen is required: brew install xcodegen" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> regenerating project"
|
||||||
|
xcodegen generate
|
||||||
|
|
||||||
|
DERIVED="build"
|
||||||
|
echo "==> building for tvOS device (team $TEAM, bundle $BUNDLE)"
|
||||||
|
xcodebuild \
|
||||||
|
-project YaMusek.xcodeproj \
|
||||||
|
-scheme YaMusek \
|
||||||
|
-configuration Release \
|
||||||
|
-destination 'generic/platform=tvOS' \
|
||||||
|
-derivedDataPath "$DERIVED" \
|
||||||
|
DEVELOPMENT_TEAM="$TEAM" \
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER="$BUNDLE" \
|
||||||
|
CODE_SIGN_STYLE=Automatic \
|
||||||
|
-allowProvisioningUpdates \
|
||||||
|
build
|
||||||
|
|
||||||
|
APP="$DERIVED/Build/Products/Release-appletvos/YaMusek.app"
|
||||||
|
if [[ ! -d "$APP" ]]; then
|
||||||
|
echo "build produced no app at $APP" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "$DEVICE" ]]; then
|
||||||
|
echo "==> paired devices"
|
||||||
|
xcrun devicectl list devices
|
||||||
|
echo
|
||||||
|
read -r -p "Device name or UDID: " DEVICE
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> installing to $DEVICE"
|
||||||
|
xcrun devicectl device install app --device "$DEVICE" "$APP"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Installed. Launch YaMusek from the Apple TV home screen."
|
||||||
|
echo "With a free Apple ID the signature expires after 7 days - rerun this script to refresh it."
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
#!/usr/bin/env swift
|
||||||
|
// Renders the tvOS brand assets (layered app icon + top shelf images).
|
||||||
|
// Run: swift tools/make-assets.swift (from the repo root)
|
||||||
|
|
||||||
|
import AppKit
|
||||||
|
import CoreGraphics
|
||||||
|
import CoreText
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
let root = FileManager.default.currentDirectoryPath
|
||||||
|
let catalog = "\(root)/Resources/Assets.xcassets"
|
||||||
|
|
||||||
|
func makeContext(_ width: Int, _ height: Int) -> CGContext {
|
||||||
|
let ctx = CGContext(
|
||||||
|
data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
|
||||||
|
space: CGColorSpace(name: CGColorSpace.sRGB)!,
|
||||||
|
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
|
||||||
|
)!
|
||||||
|
ctx.setAllowsAntialiasing(true)
|
||||||
|
ctx.interpolationQuality = .high
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func write(_ ctx: CGContext, to path: String) {
|
||||||
|
let image = ctx.makeImage()!
|
||||||
|
let rep = NSBitmapImageRep(cgImage: image)
|
||||||
|
let data = rep.representation(using: .png, properties: [:])!
|
||||||
|
try! FileManager.default.createDirectory(
|
||||||
|
atPath: (path as NSString).deletingLastPathComponent,
|
||||||
|
withIntermediateDirectories: true
|
||||||
|
)
|
||||||
|
try! data.write(to: URL(fileURLWithPath: path))
|
||||||
|
print("wrote \(path)")
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawText(
|
||||||
|
_ ctx: CGContext, _ text: String, size: CGFloat, color: NSColor,
|
||||||
|
center: CGPoint, weight: NSFont.Weight = .heavy
|
||||||
|
) {
|
||||||
|
let font = NSFont.systemFont(ofSize: size, weight: weight)
|
||||||
|
let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color]
|
||||||
|
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: attrs))
|
||||||
|
let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds)
|
||||||
|
ctx.textPosition = CGPoint(x: center.x - bounds.width / 2 - bounds.origin.x,
|
||||||
|
y: center.y - bounds.height / 2 - bounds.origin.y)
|
||||||
|
CTLineDraw(line, ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
let ink = NSColor(srgbRed: 0.06, green: 0.06, blue: 0.08, alpha: 1)
|
||||||
|
let accent = NSColor(srgbRed: 1.0, green: 0.87, blue: 0.16, alpha: 1)
|
||||||
|
|
||||||
|
/// Back: flat dark field with a soft vignette.
|
||||||
|
func drawBack(_ ctx: CGContext, w: Int, h: Int) {
|
||||||
|
ctx.setFillColor(ink.cgColor)
|
||||||
|
ctx.fill(CGRect(x: 0, y: 0, width: w, height: h))
|
||||||
|
let colors = [
|
||||||
|
NSColor(srgbRed: 0.16, green: 0.13, blue: 0.20, alpha: 1).cgColor,
|
||||||
|
NSColor(srgbRed: 0.05, green: 0.05, blue: 0.07, alpha: 1).cgColor,
|
||||||
|
] as CFArray
|
||||||
|
let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB)!,
|
||||||
|
colors: colors, locations: [0, 1])!
|
||||||
|
ctx.drawRadialGradient(
|
||||||
|
gradient,
|
||||||
|
startCenter: CGPoint(x: Double(w) * 0.3, y: Double(h) * 0.75), startRadius: 0,
|
||||||
|
endCenter: CGPoint(x: Double(w) * 0.5, y: Double(h) * 0.5), endRadius: Double(max(w, h)) * 0.8,
|
||||||
|
options: []
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Middle: the accent disc that gets the parallax lift.
|
||||||
|
func drawMiddle(_ ctx: CGContext, w: Int, h: Int) {
|
||||||
|
ctx.clear(CGRect(x: 0, y: 0, width: w, height: h))
|
||||||
|
let d = Double(h) * 0.62
|
||||||
|
let rect = CGRect(x: Double(w) / 2 - d / 2, y: Double(h) / 2 - d / 2, width: d, height: d)
|
||||||
|
ctx.setFillColor(accent.withAlphaComponent(0.18).cgColor)
|
||||||
|
ctx.fillEllipse(in: rect.insetBy(dx: -d * 0.12, dy: -d * 0.12))
|
||||||
|
ctx.setFillColor(accent.cgColor)
|
||||||
|
ctx.fillEllipse(in: rect)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Front: the wordmark that floats on top.
|
||||||
|
func drawFront(_ ctx: CGContext, w: Int, h: Int) {
|
||||||
|
ctx.clear(CGRect(x: 0, y: 0, width: w, height: h))
|
||||||
|
drawText(ctx, "\u{042F}", size: Double(h) * 0.42, color: ink,
|
||||||
|
center: CGPoint(x: Double(w) / 2, y: Double(h) * 0.53))
|
||||||
|
}
|
||||||
|
|
||||||
|
let iconSizes: [(String, Int, Int)] = [
|
||||||
|
("App Icon.imagestack", 400, 240),
|
||||||
|
("App Icon - App Store.imagestack", 1280, 768),
|
||||||
|
]
|
||||||
|
|
||||||
|
let layers: [(String, (CGContext, Int, Int) -> Void)] = [
|
||||||
|
("Back", drawBack), ("Middle", drawMiddle), ("Front", drawFront),
|
||||||
|
]
|
||||||
|
|
||||||
|
func imagesetContents(_ entries: [(String, String)]) -> String {
|
||||||
|
let images = entries.map { """
|
||||||
|
{
|
||||||
|
"idiom" : "tv",
|
||||||
|
"filename" : "\($0.1)",
|
||||||
|
"scale" : "\($0.0)"
|
||||||
|
}
|
||||||
|
""" }.joined(separator: ",\n")
|
||||||
|
return """
|
||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
\(images)
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(_ text: String, to path: String) {
|
||||||
|
try! FileManager.default.createDirectory(
|
||||||
|
atPath: (path as NSString).deletingLastPathComponent,
|
||||||
|
withIntermediateDirectories: true
|
||||||
|
)
|
||||||
|
try! text.write(toFile: path, atomically: true, encoding: .utf8)
|
||||||
|
}
|
||||||
|
|
||||||
|
let brand = "\(catalog)/App Icon & Top Shelf Image.brandassets"
|
||||||
|
|
||||||
|
for (stack, w, h) in iconSizes {
|
||||||
|
let isStore = stack.contains("App Store")
|
||||||
|
for (layer, draw) in layers {
|
||||||
|
let layerDir = "\(brand)/\(stack)/\(layer).imagestacklayer"
|
||||||
|
writeJSON("""
|
||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
""", to: "\(layerDir)/Contents.json")
|
||||||
|
|
||||||
|
var entries: [(String, String)] = []
|
||||||
|
let scales = isStore ? [1] : [1, 2]
|
||||||
|
for scale in scales {
|
||||||
|
let name = "\(layer.lowercased())@\(scale)x.png"
|
||||||
|
let ctx = makeContext(w * scale, h * scale)
|
||||||
|
draw(ctx, w * scale, h * scale)
|
||||||
|
write(ctx, to: "\(layerDir)/Content.imageset/\(name)")
|
||||||
|
entries.append(("\(scale)x", name))
|
||||||
|
}
|
||||||
|
writeJSON(imagesetContents(entries), to: "\(layerDir)/Content.imageset/Contents.json")
|
||||||
|
}
|
||||||
|
writeJSON("""
|
||||||
|
{
|
||||||
|
"layers" : [
|
||||||
|
{ "filename" : "Front.imagestacklayer" },
|
||||||
|
{ "filename" : "Middle.imagestacklayer" },
|
||||||
|
{ "filename" : "Back.imagestacklayer" }
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
""", to: "\(brand)/\(stack)/Contents.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Top shelf art: the same language, stretched wide.
|
||||||
|
func drawShelf(_ ctx: CGContext, w: Int, h: Int) {
|
||||||
|
drawBack(ctx, w: w, h: h)
|
||||||
|
let d = Double(h) * 0.5
|
||||||
|
let cx = Double(w) * 0.34
|
||||||
|
let rect = CGRect(x: cx - d / 2, y: Double(h) / 2 - d / 2, width: d, height: d)
|
||||||
|
ctx.setFillColor(accent.cgColor)
|
||||||
|
ctx.fillEllipse(in: rect)
|
||||||
|
drawText(ctx, "\u{042F}", size: d * 0.62, color: ink,
|
||||||
|
center: CGPoint(x: cx, y: Double(h) * 0.515))
|
||||||
|
drawText(ctx, "YaMusek", size: Double(h) * 0.19, color: .white,
|
||||||
|
center: CGPoint(x: cx + d * 0.72 + Double(h) * 0.42, y: Double(h) * 0.5), weight: .bold)
|
||||||
|
}
|
||||||
|
|
||||||
|
let shelves: [(String, Int, Int)] = [
|
||||||
|
("Top Shelf Image", 1920, 720),
|
||||||
|
("Top Shelf Image Wide", 2320, 720),
|
||||||
|
]
|
||||||
|
|
||||||
|
for (name, w, h) in shelves {
|
||||||
|
let dir = "\(brand)/\(name).imageset"
|
||||||
|
var entries: [(String, String)] = []
|
||||||
|
for scale in [1, 2] {
|
||||||
|
let file = "\(name.replacingOccurrences(of: " ", with: "-").lowercased())@\(scale)x.png"
|
||||||
|
let ctx = makeContext(w * scale, h * scale)
|
||||||
|
drawShelf(ctx, w: w * scale, h: h * scale)
|
||||||
|
write(ctx, to: "\(dir)/\(file)")
|
||||||
|
entries.append(("\(scale)x", file))
|
||||||
|
}
|
||||||
|
writeJSON(imagesetContents(entries), to: "\(dir)/Contents.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON("""
|
||||||
|
{
|
||||||
|
"assets" : [
|
||||||
|
{ "filename" : "App Icon - App Store.imagestack", "idiom" : "tv", "role" : "primary-app-icon", "size" : "1280x768" },
|
||||||
|
{ "filename" : "App Icon.imagestack", "idiom" : "tv", "role" : "primary-app-icon", "size" : "400x240" },
|
||||||
|
{ "filename" : "Top Shelf Image Wide.imageset", "idiom" : "tv", "role" : "top-shelf-image-wide", "size" : "2320x720" },
|
||||||
|
{ "filename" : "Top Shelf Image.imageset", "idiom" : "tv", "role" : "top-shelf-image", "size" : "1920x720" }
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
""", to: "\(brand)/Contents.json")
|
||||||
|
|
||||||
|
writeJSON("""
|
||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
""", to: "\(catalog)/Contents.json")
|
||||||
|
|
||||||
|
/// Launch image shown while the app boots.
|
||||||
|
let launchDir = "\(catalog)/LaunchImage.imageset"
|
||||||
|
var launchEntries: [(String, String)] = []
|
||||||
|
for scale in [1, 2] {
|
||||||
|
let ctx = makeContext(1920 * scale, 1080 * scale)
|
||||||
|
drawBack(ctx, w: 1920 * scale, h: 1080 * scale)
|
||||||
|
let d = Double(1080 * scale) * 0.22
|
||||||
|
let rect = CGRect(x: Double(1920 * scale) / 2 - d / 2, y: Double(1080 * scale) / 2 - d / 2, width: d, height: d)
|
||||||
|
ctx.setFillColor(accent.cgColor)
|
||||||
|
ctx.fillEllipse(in: rect)
|
||||||
|
drawText(ctx, "\u{042F}", size: d * 0.6, color: ink,
|
||||||
|
center: CGPoint(x: Double(1920 * scale) / 2, y: Double(1080 * scale) * 0.503))
|
||||||
|
let file = "launch@\(scale)x.png"
|
||||||
|
write(ctx, to: "\(launchDir)/\(file)")
|
||||||
|
launchEntries.append(("\(scale)x", file))
|
||||||
|
}
|
||||||
|
writeJSON(imagesetContents(launchEntries), to: "\(launchDir)/Contents.json")
|
||||||
|
|
||||||
|
print("assets done")
|
||||||