"""Синхронизация с Яндекс Музыкой. Работает с личным токеном владельца подписки. Два режима: --check проверить токен и показать аккаунт --likes выгрузить «Мне нравится» (метаданные) --playlists выгрузить плейлисты (метаданные) --download N скачать N треков из «Мне нравится» в библиотеку Токен: /root/.yandex-token (одна строка). Как получить — см. YANDEX-MUSIC.md. Важно: API неофициальный. Скачивание доступно только владельцу подписки Плюс и только для личного офлайн-прослушивания; публикация файлов нарушает условия сервиса. """ import json import os import re import sys import time import urllib.error import urllib.parse import urllib.request API = "https://api.music.yandex.net" TOKEN_FILE = "/root/.yandex-token" MUSIC_DIR = os.environ.get("MUSIC_DIR", "/mnt/media/music") def token(): if not os.path.exists(TOKEN_FILE): return None t = open(TOKEN_FILE, encoding="utf-8").read().strip() return t or None def call(path, params=None, method="GET", body=None, timeout=25): url = API + path if params: url += "?" + urllib.parse.urlencode(params) headers = {"Authorization": "OAuth " + (token() or ""), "Accept": "application/json"} data = json.dumps(body).encode() if body is not None else None if data: headers["Content-Type"] = "application/json" req = urllib.request.Request(url, data=data, method=method, headers=headers) try: with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read() or b"{}"), None except urllib.error.HTTPError as e: return None, f"HTTP {e.code}" except Exception as e: return None, str(e)[:120] def check(): if not token(): print("нет токена:", TOKEN_FILE) print("как получить — см. ops/media/YANDEX-MUSIC.md") return 1 data, err = call("/account/status") if err: print("токен не работает:", err) return 1 result = (data or {}).get("result") or {} acc = result.get("account") or {} print(" аккаунт:", acc.get("displayName") or acc.get("login") or acc.get("uid")) print(" подписка:", (result.get("plus") or {}).get("hasPlus")) print(" uid:", acc.get("uid")) return 0 def uid(): data, err = call("/account/status") if err: return None, err result = (data or {}).get("result") or {} return ((result.get("account") or {}).get("uid")), None def track_details(ids): """Пачками тянет детали треков: /tracks?track-ids=...""" out = {} ids = [str(i) for i in ids if i] for i in range(0, len(ids), 100): chunk = ids[i:i + 100] data, err = call("/tracks", {"track-ids": ",".join(chunk)}) if err: continue for t in (data or {}).get("result") or []: artists = ", ".join(a.get("name") for a in (t.get("artists") or [])) albums = t.get("albums") or [] album = albums[0].get("title") if albums else "" out[str(t.get("id"))] = { "id": t.get("id"), "title": t.get("title"), "artists": artists, "album": album, "duration": t.get("durationMs"), } return out def artist_match(track_artists, term): """Точное совпадение по одному из исполнителей (без подстрок вроде Atlantis).""" term = (term or "").strip().lower() if not term: return False for a in (track_artists or "").split(","): if a.strip().lower() == term: return True return False def likes(limit=1000): u, err = uid() if not u: return None, err or "нет uid" data, err = call(f"/users/{u}/likes/tracks", {"limit": limit}) if err: return None, err result = (data or {}).get("result") or {} tracks = result.get("library", {}).get("tracks") or [] if not tracks: return [], None ids = [t.get("id") for t in tracks] details = track_details(ids) out = [] for t in tracks: d = details.get(str(t.get("id"))) if d: out.append(d) return out, None def playlists(): u, err = uid() if not u: return None, err or "нет uid" data, err = call(f"/users/{u}/playlists/list") if err: return None, err result = (data or {}).get("result") or [] out = [] for p in result: out.append({"kind": p.get("kind"), "title": p.get("title"), "tracks": p.get("trackCount"), "owner": (p.get("owner") or {}).get("name")}) return out, None def safe(name): return re.sub(r'[<>:"/\\|?*]', "_", (name or "unknown")).strip()[:80] def tag_file(path, title, artists, album, year=None): """Прописывает ID3-теги (нужен mutagen из venv).""" try: from mutagen.id3 import ID3, TIT2, TPE1, TALB, TDRC except Exception: return False try: try: tags = ID3(path) except Exception: tags = ID3() tags.delall("TIT2") tags.delall("TPE1") tags.delall("TALB") tags.add(TIT2(encoding=3, text=title or "")) tags.add(TPE1(encoding=3, text=artists or "")) if album: tags.add(TALB(encoding=3, text=album)) if year: tags.add(TDRC(encoding=3, text=str(year))) tags.save(path) return True except Exception: return False def download_track(track_id, title, artists, album): """Получить прямой URL и сохранить файл с тегами.""" data, err = call(f"/tracks/{track_id}/download-info") if err: return None, err infos = (data or {}).get("result") or [] if not infos: return None, "нет ссылок (нужна подписка Плюс?)" best = sorted(infos, key=lambda i: i.get("bitrateInKbps") or 0)[-1] url = best.get("downloadInfoUrl") if not url: return None, "нет downloadInfoUrl" # download-info отдаёт XML с полями host/path/ts/s try: with urllib.request.urlopen(url, timeout=25) as r: xml = r.read().decode("utf-8", "replace") except Exception as e: return None, "download-info: " + str(e)[:60] def field(name): m = re.search(rf"<{name}>([^<]+)", xml) return m.group(1) if m else None host, path, ts, s = field("host"), field("path"), field("ts"), field("s") if not all([host, path, ts, s]): return None, "не разобрал download-info" sign = urllib.parse.quote(f"{ts}{s}".encode().hex() if False else __import__("hashlib").md5( ("XGRlBW9FXlekgbPrRHuSiA" + path[1:] + s).encode()).hexdigest()) link = f"https://{host}/get-mp3/{sign}/{ts}{path}" folder = os.path.join(MUSIC_DIR, safe(artists), safe(album or "Без альбома")) os.makedirs(folder, exist_ok=True) fname = safe(f"{artists} - {title}") + ".mp3" dest = os.path.join(folder, fname) if os.path.exists(dest): return dest, None try: req = urllib.request.Request(link, headers={"User-Agent": "Mozilla/5.0"}) with urllib.request.urlopen(req, timeout=60) as r, open(dest, "wb") as f: f.write(r.read()) except Exception as e: return None, "скачивание: " + str(e)[:60] tag_file(dest, title, artists, album) return dest, None def local_index(): """Индекс локальных файлов: «исполнитель - название» → путь.""" idx = {} for root, _dirs, files in os.walk(MUSIC_DIR): for f in files: if not f.lower().endswith((".mp3", ".flac", ".ogg", ".m4a", ".wav")): continue path = os.path.join(root, f) stem = os.path.splitext(f)[0].lower() idx[stem] = path return idx def norm(s): return re.sub(r"[^a-zа-я0-9]+", " ", (s or "").lower()).strip() def write_m3u(tracks, name="Яндекс - Мне нравится"): """Пишет M3U-плейлист из треков, которые уже есть локально.""" idx = local_index() lines = ["#EXTM3U"] found = 0 for t in tracks: key = norm(f"{t['artists']} - {t['title']}") hit = None for stem, path in idx.items(): if norm(stem) == key or (norm(t["title"]) and norm(t["title"]) in norm(stem)): hit = path break if hit: lines.append(os.path.relpath(hit, MUSIC_DIR)) found += 1 if found: dest = os.path.join(MUSIC_DIR, safe(name) + ".m3u") with open(dest, "w", encoding="utf-8") as f: f.write("\n".join(lines) + "\n") return dest, found return None, 0 def main(): args = sys.argv[1:] if not args or args[0] in ("-h", "--help"): print(__doc__) return 0 mode = args[0] if mode == "--check": return check() if mode in ("--likes", "--playlists"): if not token(): print("нет токена:", TOKEN_FILE) return 1 data, err = (likes() if mode == "--likes" else playlists()) if err: print("ошибка:", err) return 1 print(f" записей: {len(data)}") for x in data[:20]: if mode == "--likes": print(f" • {x['artists']} — {x['title']} ({x['album']})") else: print(f" • {x['title']} — треков: {x['tracks']}") return 0 if mode == "--m3u": if not token(): print("нет токена:", TOKEN_FILE) return 1 tracks, err = likes() if err: print("ошибка:", err) return 1 dest, found = write_m3u(tracks) if dest: print(f" плейлист: {dest} — треков: {found}") else: print(" ни один трек из «Мне нравится» не найден локально") return 0 if mode == "--artist": if not token(): print("нет токена:", TOKEN_FILE) return 1 term = (args[1] if len(args) > 1 else "").strip().lower() if not term: print("укажите имя: --artist ATL") return 1 tracks, err = likes() if err: print("ошибка:", err) return 1 hits = [t for t in tracks if artist_match(t.get("artists"), term)] print(f" найдено: {len(hits)}") for t in hits: print(f" • {t['artists']} — {t['title']} ({t['album']})") return 0 if mode == "--download-artist": if not token(): print("нет токена:", TOKEN_FILE) return 1 term = (args[1] if len(args) > 1 else "").strip().lower() if not term: print("укажите имя: --download-artist ATL") return 1 tracks, err = likes() if err: print("ошибка:", err) return 1 hits = [t for t in tracks if artist_match(t.get("artists"), term)] if not hits: print(" у этого исполнителя нет треков в «Мне нравится»") return 0 print(f" треков у {args[1]}: {len(hits)}") ok, fail = 0, 0 for t in hits: path, e = download_track(t["id"], t["title"], t["artists"], t["album"]) if path: print(" ✅", os.path.basename(path)[:70]) ok += 1 else: print(" ❌", t["title"][:40], "—", e) fail += 1 time.sleep(1) print(f"\n скачано: {ok}, ошибок: {fail}") return 0 if mode == "--download": n = int(args[1]) if len(args) > 1 else 5 if not token(): print("нет токена:", TOKEN_FILE) return 1 tracks, err = likes() if err: print("ошибка:", err) return 1 ok, fail = 0, 0 for t in tracks[:n]: path, e = download_track(t["id"], t["title"], t["artists"], t["album"]) if path: print(" ✅", os.path.basename(path)[:70]) ok += 1 else: print(" ❌", t["title"][:40], "—", e) fail += 1 time.sleep(1) print(f"\n скачано: {ok}, ошибок: {fail}") return 0 print("неизвестный режим:", mode) return 2 if __name__ == "__main__": sys.exit(main())