Mulberry/mulberry/online.py
Claude a0b83cd4e3
Mulberry 1.2.1: CD fixes, web links, lyrics priority, portable playlists
- Fix crash after CD ripping (running QThread was destroyed)
- Audio CDs always use mpv (bundled on Windows) even when Qt is the main engine
  — fixes 'several tracks failed to play' on Windows
- YouTube/SoundCloud/Bandcamp links resolved with bundled yt-dlp
- Lyrics: Auto prefers synced from any source (LRCLIB > NetEase > embedded >
  local); explicit choices no longer fall back; NetEase uses cloudsearch
  (search/get/web is encrypted outside China)
- Playlist export uses absolute paths by default; import remaps paths from
  other machines/OSes via the library
- HTTPS: certificate fallback (system bundles, certifi) for packaged builds;
  cover search shows real errors, more fallbacks, Last.fm covers
- MusicBrainz: retry without album, cleaner album artist, async genre
- CI self-tests require bundled libmpv (Windows), yt-dlp and TLS certs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
2026-10-10 00:45:03 -05:00

510 lines
21 KiB
Python

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.

"""Online metadata: MusicBrainz tags, cover art (Cover Art Archive, iTunes,
Deezer, Last.fm), synced lyrics (LRCLIB), artist info (Last.fm / Wikipedia),
AcoustID fingerprint lookup. All functions are blocking — call via run_async."""
from __future__ import annotations
import json
import re
import shutil
import subprocess
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from .config import USER_AGENT, settings
from .song import Song
_mb_lock = threading.Lock()
_mb_last = [0.0]
_SSL_CTX = None
def ssl_context():
"""A TLS context that works everywhere. Packaged builds carry an OpenSSL
compiled for another distro whose default CA path may not exist here
(e.g. Ubuntu's /usr/lib/ssl on Arch), which silently broke every HTTPS
request. Fall back to known system bundles, then to certifi."""
global _SSL_CTX
if _SSL_CTX is not None:
return _SSL_CTX
import os
import ssl
ctx = ssl.create_default_context()
try:
have = ctx.cert_store_stats().get("x509_ca", 0)
except Exception: # noqa: BLE001
have = 0
if not have:
for cand in ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/ca-bundle.pem", "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
"/etc/ssl/cert.pem"):
if os.path.exists(cand):
try:
ctx.load_verify_locations(cafile=cand)
have = 1
break
except Exception: # noqa: BLE001
pass
if not have:
try:
import certifi
ctx.load_verify_locations(cafile=certifi.where())
except Exception: # noqa: BLE001
pass
_SSL_CTX = ctx
return ctx
def http_get(url: str, params: dict | None = None, timeout=12, headers=None, raw=False):
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, **(headers or {})})
with urllib.request.urlopen(req, timeout=timeout, context=ssl_context()) as r:
data = r.read()
if raw:
return data
return json.loads(data.decode("utf-8", "replace"))
def http_post(url: str, data: dict | bytes, timeout=12, headers=None):
body = data if isinstance(data, bytes) else urllib.parse.urlencode(data).encode()
req = urllib.request.Request(url, data=body, method="POST",
headers={"User-Agent": USER_AGENT, **(headers or {})})
with urllib.request.urlopen(req, timeout=timeout, context=ssl_context()) as r:
return json.loads(r.read().decode("utf-8", "replace") or "{}")
def mb_get(path: str, params: dict):
with _mb_lock: # MusicBrainz: max 1 request/second
wait = 1.05 - (time.time() - _mb_last[0])
if wait > 0:
time.sleep(wait)
_mb_last[0] = time.time()
return http_get(f"https://musicbrainz.org/ws/2/{path}", {**params, "fmt": "json"})
def _clean(s: str) -> str:
s = re.sub(r"\s*[\(\[](feat\.?|ft\.?|with|remaster(ed)?|\d{4} remaster|live|explicit|bonus)[^\)\]]*[\)\]]", "", s, flags=re.I)
return s.strip()
def _q(s: str) -> str:
return re.sub(r'([+\-&|!(){}\[\]^"~*?:\\/])', r"\\\1", s)
# ------------------------------------------------------------------ MusicBrainz
def musicbrainz_search(song: Song, limit=15) -> list[dict]:
"""Search recordings; returns flattened candidates (one per release)."""
parts = []
if song.title:
parts.append(f'recording:"{_q(_clean(song.title))}"')
if song.display_artist():
parts.append(f'artist:"{_q(song.display_artist())}"')
if song.album:
parts.append(f'release:"{_q(_clean(song.album))}"')
if not parts:
return []
res = mb_get("recording", {"query": " AND ".join(parts[:2]) + (f" AND ({parts[2]})" if len(parts) > 2 else ""),
"limit": limit})
if not res.get("recordings") and len(parts) > 2:
# album tag differs from MusicBrainz ("(Deluxe)", typos…): search without it
res = mb_get("recording", {"query": " AND ".join(parts[:2]), "limit": limit})
out = []
for rec in res.get("recordings", []):
credits = rec.get("artist-credit", [])
artist = "".join(a.get("name", "") + a.get("joinphrase", "") for a in credits)
main_artist = credits[0].get("name", artist) if credits else artist
for rel in rec.get("releases", [])[:4] or [{}]:
media = (rel.get("media") or [{}])[0]
trk = (media.get("track") or [{}])[0]
ra = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rel.get("artist-credit", [])) or main_artist
out.append({
"title": rec.get("title", ""), "artist": artist, "album": rel.get("title", ""),
"albumartist": ra, "year": int((rel.get("date") or "0")[:4] or 0),
"track": int(re.sub(r"\D", "", str(trk.get("number", "0"))) or 0),
"disc": int(media.get("position", 0) or 0),
"length": (rec.get("length") or 0) / 1000,
"mb_trackid": rec.get("id", ""), "mb_albumid": rel.get("id", ""),
"score": int(rec.get("score", 0)), "country": rel.get("country", ""),
"status": rel.get("status", ""),
})
# prefer close length + official releases
if song.length:
for c in out:
if c["length"]:
c["score"] -= min(40, abs(c["length"] - song.length) * 2)
for c in out:
if c["status"] == "Official":
c["score"] += 5
out.sort(key=lambda c: -c["score"])
return out
def musicbrainz_genre(mb_albumid: str) -> str:
try:
r = mb_get(f"release/{mb_albumid}", {"inc": "genres+release-groups"})
g = sorted(r.get("genres", []), key=lambda x: -x.get("count", 0))
return g[0]["name"].title() if g else ""
except Exception: # noqa: BLE001
return ""
def acoustid_lookup(path: str) -> list[dict]:
key = settings.get("online/acoustid_key")
fpcalc = shutil.which("fpcalc")
if not key or not fpcalc:
raise RuntimeError("AcoustID needs an API key (Settings › Metadata) and the 'fpcalc' tool (chromaprint).")
out = subprocess.run([fpcalc, "-json", path], capture_output=True, text=True, timeout=60)
fp = json.loads(out.stdout)
res = http_post("https://api.acoustid.org/v2/lookup", {
"client": key, "meta": "recordings releases", "duration": int(fp["duration"]),
"fingerprint": fp["fingerprint"]})
cands = []
for r in res.get("results", []):
for rec in r.get("recordings", []) or []:
artist = ", ".join(a["name"] for a in rec.get("artists", []))
for rel in (rec.get("releases") or [{}])[:3]:
cands.append({"title": rec.get("title", ""), "artist": artist, "album": rel.get("title", ""),
"albumartist": artist, "year": (rel.get("date") or {}).get("year", 0),
"track": 0, "disc": 0, "mb_trackid": rec.get("id", ""),
"mb_albumid": rel.get("id", ""), "score": int(r.get("score", 0) * 100),
"length": rec.get("duration", 0)})
return cands
# ------------------------------------------------------------------ covers
def cover_candidates(artist: str, album: str, title: str = "") -> list[dict]:
"""Return [{'url','thumb','source','size'}] from several providers."""
out: list[dict] = []
term = f"{artist} {album or title}".strip()
errors = []
def itunes():
r = http_get("https://itunes.apple.com/search", {"term": term, "entity": "album" if album else "song", "limit": 8})
if not r.get("results") and album:
r = http_get("https://itunes.apple.com/search", {"term": f"{artist} {title or album}", "entity": "song",
"limit": 8})
for it in r.get("results", []):
u = it.get("artworkUrl100")
if u:
out.append({"url": u.replace("100x100bb", "1200x1200bb"), "thumb": u.replace("100x100bb", "300x300bb"),
"source": "iTunes", "label": f"{it.get('artistName', '')} – {it.get('collectionName', '')}"})
def deezer():
r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'})
if not r.get("data"):
r = http_get("https://api.deezer.com/search/album", {"q": term})
for it in (r.get("data") or [])[:8]:
if it.get("cover_xl"):
out.append({"url": it["cover_xl"], "thumb": it.get("cover_medium") or it["cover_xl"],
"source": "Deezer", "label": f"{it.get('artist', {}).get('name', '')} – {it.get('title', '')}"})
def caa():
if not album:
return
r = mb_get("release", {"query": f'release:"{_q(album)}" AND artist:"{_q(artist)}"', "limit": 5})
for rel in r.get("releases", [])[:5]:
rid = rel["id"]
out.append({"url": f"https://coverartarchive.org/release/{rid}/front",
"thumb": f"https://coverartarchive.org/release/{rid}/front-250",
"source": "Cover Art Archive",
"label": f"{rel.get('title', '')} ({(rel.get('date') or '')[:4]})"})
def lastfm():
from .scrobble import LastFM
key = LastFM.key()[0]
if not key or not album:
return
r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "album.getinfo", "api_key": key,
"artist": artist, "album": album, "format": "json",
"autocorrect": 1})
imgs = r.get("album", {}).get("image", [])
if imgs and imgs[-1].get("#text"):
u = imgs[-1]["#text"]
out.append({"url": re.sub(r"/\d+x\d+/", "/", u), "thumb": u, "source": "Last.fm", "label": album})
threads = []
for fn in (itunes, deezer, caa, lastfm):
def wrap(f=fn):
try:
f()
except Exception as e: # noqa: BLE001
errors.append(str(e))
t = threading.Thread(target=wrap, daemon=True)
t.start()
threads.append(t)
for t in threads:
t.join(20)
order = {"Cover Art Archive": 0, "iTunes": 1, "Deezer": 2, "Last.fm": 3}
out.sort(key=lambda c: order.get(c["source"], 9))
# de-duplicate identical image URLs
seen, uniq = set(), []
for c in out:
if c["url"] not in seen:
seen.add(c["url"])
uniq.append(c)
if not uniq and errors:
raise RuntimeError("Couldn't reach the cover services — " + errors[0][:160])
return uniq
def best_cover(artist: str, album: str, title: str = "") -> bytes | None:
"""Automatic fetch: try providers in order, return image bytes."""
if not artist and not album:
return None
for fn in (_auto_itunes, _auto_deezer, _auto_lastfm):
try:
u = fn(artist, album, title)
if u:
data = http_get(u, raw=True, timeout=15)
if data and len(data) > 1000:
return data
except Exception: # noqa: BLE001
continue
return None
def _norm(s):
return re.sub(r"[^a-z0-9]", "", (s or "").lower())
def _auto_itunes(artist, album, title):
term = f"{artist} {album or title}"
r = http_get("https://itunes.apple.com/search", {"term": term, "entity": "album" if album else "song", "limit": 6})
for it in r.get("results", []):
if _norm(artist) and _norm(artist) not in _norm(it.get("artistName")) and _norm(it.get("artistName")) not in _norm(artist):
continue
if album and _norm(_clean(album))[:12] not in _norm(it.get("collectionName")):
continue
u = it.get("artworkUrl100")
if u:
return u.replace("100x100bb", "1000x1000bb")
return None
def _auto_lastfm(artist, album, title):
from .scrobble import LastFM
key = LastFM.key()[0]
if not key or not album:
return None
r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "album.getinfo", "api_key": key,
"artist": artist, "album": album, "format": "json",
"autocorrect": 1})
imgs = (r.get("album") or {}).get("image") or []
u = imgs[-1].get("#text") if imgs else ""
return re.sub(r"/\d+x\d+/", "/", u) if u else None
def _auto_deezer(artist, album, title):
r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'})
for it in r.get("data") or []:
if _norm(artist) in _norm(it.get("artist", {}).get("name")):
return it.get("cover_xl")
return None
def download(url: str) -> bytes:
return http_get(url, raw=True, timeout=20)
# ------------------------------------------------------------------ lyrics
def _lyr_query(song: Song):
artist = song.display_artist()
title = song.display_title()
if song.is_stream and song.stream_title and " - " in song.stream_title:
artist, title = [x.strip() for x in song.stream_title.split(" - ", 1)]
return artist, title
def lyrics_lrclib(song: Song) -> str:
artist, title = _lyr_query(song)
if not title:
return ""
params = {"artist_name": artist, "track_name": _clean(title)}
if song.album and not song.is_stream:
params["album_name"] = song.album
if song.duration() and not song.is_stream:
params["duration"] = int(round(song.duration()))
try:
r = http_get("https://lrclib.net/api/get", params)
if r.get("instrumental"):
return "[instrumental]"
txt = r.get("syncedLyrics") or r.get("plainLyrics") or ""
if txt:
return txt
except urllib.error.HTTPError:
pass
r = http_get("https://lrclib.net/api/search", {"track_name": _clean(title), "artist_name": artist})
best = None
for it in r or []:
if song.duration() and it.get("duration") and abs(it["duration"] - song.duration()) > 6:
continue
if it.get("syncedLyrics"):
best = it
break
best = best or it
return (best.get("syncedLyrics") or best.get("plainLyrics") or "") if best else ""
_NE_HEADERS = {"Referer": "https://music.163.com/",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/124.0 Safari/537.36"}
_NE_CREDIT = re.compile(r"^\s*\[[^\]]*\]\s*(作词|作曲|编曲|制作人|监制|混音|母带|和声|吉他|贝斯|鼓|词|曲|"
r"Lyricist|Lyrics by|Composer|Composed by|Arranger|Producer|Written by)\s*[::]", re.I)
def lyrics_netease(song: Song) -> str:
artist, title = _lyr_query(song)
if not title:
return ""
q = f"{_clean(title)} {artist}".strip()
# cloudsearch/pc returns plain JSON abroad (search/get/web is encrypted
# for non-Chinese IPs, which made NetEase silently return nothing)
r = http_get("https://music.163.com/api/cloudsearch/pc",
{"s": q, "type": 1, "offset": 0, "limit": 10}, headers=_NE_HEADERS)
songs = (r.get("result") or {}).get("songs") or []
best, best_score = None, -1e9
for it in songs:
score = 0.0
names = " ".join(a.get("name", "") for a in (it.get("ar") or it.get("artists") or []))
if _norm(artist) and (_norm(artist) in _norm(names) or _norm(names) in _norm(artist)):
score += 50
if _norm(_clean(title)) == _norm(_clean(it.get("name", ""))):
score += 30
dur = it.get("dt") or it.get("duration")
if song.duration() and dur:
score -= min(40, abs(dur / 1000 - song.duration()) * 4)
if score > best_score:
best, best_score = it, score
if not best or best_score < 0:
return ""
lr = http_get("https://music.163.com/api/song/lyric",
{"id": best["id"], "lv": 1, "kv": 1, "tv": -1}, headers=_NE_HEADERS)
txt = ((lr.get("lrc") or {}).get("lyric") or "").strip()
if lr.get("nolyric") or lr.get("uncollected"):
return ""
return "\n".join(ln for ln in txt.splitlines() if not _NE_CREDIT.match(ln))
ONLINE_PROVIDERS = {"lrclib": ("LRCLIB", lyrics_lrclib), "netease": ("NetEase", lyrics_netease)}
def fetch_lyrics(song: Song, source: str = "auto") -> tuple[str, str]:
"""Return (lyrics_text, provider label). In auto mode synced results win:
LRCLIB first, then NetEase; a plain result is kept only as a fallback."""
order = ["lrclib", "netease"] if source == "auto" else [source]
fallback = ("", "")
errors = []
for key in order:
if key not in ONLINE_PROVIDERS:
continue
label, fn = ONLINE_PROVIDERS[key]
try:
txt = fn(song)
except Exception as e: # noqa: BLE001
errors.append(str(e))
continue
if not txt:
continue
if txt == "[instrumental]" or LRC_RE.search(txt):
return txt, label
if not fallback[0]:
fallback = (txt, label)
if fallback[0]:
return fallback
if errors and len(errors) == len(order):
raise RuntimeError(errors[0])
return "", ""
LRC_RE = re.compile(r"\[(\d+):(\d+(?:[.:]\d+)?)\]")
def parse_lrc(text: str) -> tuple[list[tuple[float, str]], bool]:
"""Return ([(time, line)], synced). Unsynced text -> times are -1."""
lines = []
offset = 0.0
m = re.search(r"\[offset:\s*([-+]?\d+)\]", text or "", re.I)
if m:
offset = int(m.group(1)) / 1000
synced = False
for raw in (text or "").splitlines():
stamps = LRC_RE.findall(raw)
content = LRC_RE.sub("", raw).strip()
content = re.sub(r"<\d+:\d+(?:\.\d+)?>", "", content) # enhanced LRC word stamps
if stamps:
synced = True
for mm, ss in stamps:
t = int(mm) * 60 + float(ss.replace(":", ".")) - offset
lines.append((max(t, 0.0), content))
elif not re.match(r"^\[[a-z]+:.*\]$", raw.strip(), re.I):
lines.append((-1.0, raw.strip()))
if synced:
lines = sorted([x for x in lines if x[0] >= 0], key=lambda x: x[0])
return lines, synced
# ------------------------------------------------------------------ artist info
def artist_info(artist: str) -> str:
from .scrobble import LastFM
key = LastFM.key()[0]
if key:
try:
r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "artist.getinfo", "artist": artist,
"api_key": key, "format": "json", "autocorrect": 1})
txt = r.get("artist", {}).get("bio", {}).get("content", "")
txt = re.sub(r"<a href.*?</a>\.?", "", txt).strip()
if txt:
return txt
except Exception: # noqa: BLE001
pass
try:
r = http_get("https://en.wikipedia.org/api/rest_v1/page/summary/" + urllib.parse.quote(artist.replace(" ", "_")))
if r.get("type") == "disambiguation":
r = http_get("https://en.wikipedia.org/api/rest_v1/page/summary/" +
urllib.parse.quote(artist.replace(" ", "_") + "_(band)"))
return r.get("extract", "")
except Exception: # noqa: BLE001
return ""
# ------------------------------------------------------------------ web video/audio links
RESOLVE_HOSTS = ("youtube.com", "youtu.be", "music.youtube.com", "soundcloud.com", "bandcamp.com",
"vimeo.com", "mixcloud.com", "twitch.tv", "dailymotion.com", "audiomack.com",
"archive.org", "bilibili.com", "nicovideo.jp", "odysee.com", "rumble.com")
def needs_resolve(url: str) -> bool:
"""Page links (YouTube, SoundCloud…) need yt-dlp; radio streams don't."""
host = urllib.parse.urlparse(url).netloc.lower()
return any(host == h or host.endswith("." + h) for h in RESOLVE_HOSTS)
def resolve_stream(url: str) -> dict:
"""Use yt-dlp (bundled as a Python module) to get a playable audio URL."""
try:
import yt_dlp
except ImportError as e:
raise RuntimeError("Playing web links needs yt-dlp (pip install yt-dlp).") from e
opts = {"format": "bestaudio[acodec!=none]/bestaudio/best", "quiet": True, "no_warnings": True,
"noplaylist": True, "skip_download": True, "socket_timeout": 15, "extract_flat": False}
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
if info.get("_type") == "playlist" and info.get("entries"):
info = next(e for e in info["entries"] if e)
direct = info.get("url")
if not direct and info.get("requested_formats"):
direct = info["requested_formats"][0].get("url")
if not direct:
raise RuntimeError("No playable audio found at that link.")
title = info.get("track") or info.get("title") or url
artist = info.get("artist") or info.get("uploader") or info.get("channel") or ""
thumbs = sorted(info.get("thumbnails") or [], key=lambda t: (t.get("preference") or 0, t.get("width") or 0))
thumb = info.get("thumbnail") or (thumbs[-1]["url"] if thumbs else "")
return {"url": direct, "title": title, "artist": artist, "album": info.get("album") or "",
"duration": float(info.get("duration") or 0), "live": bool(info.get("is_live")),
"thumbnail": thumb, "headers": info.get("http_headers") or {}}