Yandex Music client for Apple TV

tvOS 17+ SwiftUI client for the unofficial Yandex Music API: rotor stations
with feedback, library, search, artist and album pages, synced lyrics, and
system Now Playing integration.
This commit is contained in:
2026-09-17 20:38:19 +03:00
commit acd50280bc
70 changed files with 4588 additions and 0 deletions
+37
View File
@@ -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
+122
View File
@@ -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
+69
View File
@@ -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"
+66
View File
@@ -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."
+226
View File
@@ -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")