Sort_YM/sort_ym/auth.py
Andrew Pimenov 353be65e3a init: сортировка лайков Яндекс.Музыки по жанру и языку
CLI на yandex-music (device-flow auth, fetch/report/apply), жанр через
реальное дерево client.genres(), язык гибридом (track_supplement + алфавит).
2026-07-06 09:49:36 +03:00

42 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
from pathlib import Path
from yandex_music import Client, DeviceCode
from yandex_music.exceptions import DeviceAuthError
def load_token(token_file: Path) -> str | None:
if token_file.exists():
token = token_file.read_text(encoding="utf-8").strip()
return token or None
return None
def save_token(token_file: Path, token: str) -> None:
token_file.parent.mkdir(parents=True, exist_ok=True)
token_file.write_text(token, encoding="utf-8")
def _on_code(code: DeviceCode) -> None:
print(f"Откройте {code.verification_url} и введите код: {code.user_code}")
print("Ожидание подтверждения...")
def device_login(token_file: Path) -> str:
client = Client()
try:
oauth_token = client.device_auth(_on_code)
except DeviceAuthError as e:
raise SystemExit(f"Не удалось авторизоваться: {e}") from e
save_token(token_file, oauth_token.access_token)
print("Токен сохранён.")
return oauth_token.access_token
def get_token(token_file: Path) -> str:
token = load_token(token_file)
if token:
return token
return device_login(token_file)