Mulberry/mulberry/scrobble.py
Claude 2cc0338156
Mulberry 1.2.0: fix packaged playback, track-synced visualizer, Last.fm login
- Packaged builds: keep Qt6Quick/Qml (the FFmpeg media plugin links them);
  pruning them disabled all playback in the AppImage/tarball
- Visualizer decodes each track ahead (QAudioDecoder) and follows the playback
  position: works with mpv and Qt, no PipeWire monitor needed for local files
- Packaged Linux builds default to the self-contained Qt engine
- Last.fm: built-in app key, browser login returns to a 127.0.0.1 callback;
  now-playing is re-sent on resume
- Export all playlists (folder, file type, replace/skip/number)
- Unknown/burned CDs: CD placeholder art, no online lookups
- install.sh: --uninstall, --purge, requirement checks, launch log
- CI self-tests now play a file and assert decoding + visualizer output

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

342 lines
13 KiB
Python

"""Last.fm and ListenBrainz scrobbling with an offline cache."""
from __future__ import annotations
import hashlib
import json
import threading
import time
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
from .config import SCROBBLE_CACHE, run_async, settings
from .online import http_get, http_post
from .song import Song
LFM_API = "https://ws.audioscrobbler.com/2.0/"
class LastFMError(RuntimeError):
code = 0
def app_credentials() -> tuple[str, str]:
"""Bundled application key (see lastfm_app.py), env vars, or json file."""
import os
from . import lastfm_app
from .config import CONFIG_DIR
key = os.environ.get("MULBERRY_LASTFM_KEY") or lastfm_app.API_KEY
sec = os.environ.get("MULBERRY_LASTFM_SECRET") or lastfm_app.API_SECRET
if not (key and sec):
try:
d = json.loads((CONFIG_DIR / "lastfm_app.json").read_text())
key, sec = d.get("key", ""), d.get("secret", "")
except (OSError, ValueError):
pass
return key or "", sec or ""
class CallbackServer(QObject):
"""Tiny one-shot HTTP server on 127.0.0.1 that receives Last.fm's
redirect (…/lastfm?token=XYZ) after the user approves in the browser."""
token = pyqtSignal(str)
PAGE = ("<!doctype html><meta charset=utf-8><title>Mulberry</title>"
"<body style='font-family:system-ui,sans-serif;background:#1d1b20;color:#e6e0e9;display:grid;"
"place-items:center;height:100vh;margin:0'><div style='text-align:center'>"
"<div style='font-size:56px'>🫐</div><h2>Mulberry is connected to Last.fm</h2>"
"<p style='opacity:.7'>You can close this tab and go back to the app.</p></div></body>")
def __init__(self, port: int):
super().__init__()
self.port = port
self.httpd = None
def start(self) -> bool:
import http.server
outer = self
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
import urllib.parse
q = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
tok = (q.get("token") or [""])[0]
self.send_response(200 if tok else 404)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write((outer.PAGE if tok else "Not found").encode())
if tok:
outer.token.emit(tok)
def log_message(self, *a):
pass
try:
self.httpd = http.server.HTTPServer(("127.0.0.1", self.port), H)
except OSError:
return False
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
return True
def stop(self):
if self.httpd is not None:
threading.Thread(target=self.httpd.shutdown, daemon=True).start()
self.httpd = None
class LastFM:
@staticmethod
def key():
own = settings.get("lastfm/use_own_key")
uk, us = settings.get("lastfm/api_key"), settings.get("lastfm/api_secret")
if own and uk and us:
return uk, us
ak, asec = app_credentials()
if ak and asec:
return ak, asec
return uk, us
@staticmethod
def has_key() -> bool:
k, s = LastFM.key()
return bool(k and s)
@classmethod
def sign(cls, params: dict) -> dict:
_, secret = cls.key()
s = "".join(f"{k}{params[k]}" for k in sorted(params) if k not in ("format", "callback"))
params["api_sig"] = hashlib.md5((s + secret).encode("utf-8")).hexdigest()
return params
@classmethod
def call(cls, method: str, params: dict, post=True, auth=True):
key, _ = cls.key()
p = {"method": method, "api_key": key, **{k: str(v) for k, v in params.items() if v not in (None, "")}}
if auth:
p["sk"] = settings.get("lastfm/session")
cls.sign(p)
p["format"] = "json"
import urllib.error
try:
res = http_post(LFM_API, p) if post else http_get(LFM_API, p)
except urllib.error.HTTPError as e:
try:
res = json.loads(e.read().decode("utf-8", "replace"))
except (ValueError, OSError):
raise RuntimeError(f"Last.fm: HTTP {e.code}") from e
if "error" in res:
err = LastFMError(f"Last.fm: {res.get('message', res['error'])}")
err.code = int(res.get("error", 0))
raise err
return res
# ------------------------------------------------ desktop auth flow
@classmethod
def begin_auth(cls) -> str:
res = cls.call("auth.getToken", {}, post=False, auth=False)
return res["token"]
@classmethod
def web_auth_url(cls, port: int) -> str:
import urllib.parse
key, _ = cls.key()
cb = urllib.parse.quote(f"http://127.0.0.1:{port}/lastfm", safe="")
return f"https://www.last.fm/api/auth/?api_key={key}&cb={cb}"
@classmethod
def auth_url(cls, token: str) -> str:
key, _ = cls.key()
return f"https://www.last.fm/api/auth/?api_key={key}&token={token}"
@classmethod
def finish_auth(cls, token: str) -> tuple[str, str]:
res = cls.call("auth.getSession", {"token": token}, post=False, auth=False)
sess = res["session"]
return sess["key"], sess["name"]
@staticmethod
def track_params(s: Song, prefix="", idx=None):
sfx = f"[{idx}]" if idx is not None else ""
artist, title = s.display_artist(), s.display_title()
if s.is_stream and s.stream_title and " - " in s.stream_title:
artist, title = [x.strip() for x in s.stream_title.split(" - ", 1)]
p = {f"artist{sfx}": artist, f"track{sfx}": title}
if s.album and not s.is_stream:
p[f"album{sfx}"] = s.album
if s.albumartist and s.albumartist != s.artist:
p[f"albumArtist{sfx}"] = s.albumartist
if s.track:
p[f"trackNumber{sfx}"] = s.track
if s.duration():
p[f"duration{sfx}"] = int(s.duration())
if s.mb_trackid:
p[f"mbid{sfx}"] = s.mb_trackid
return p
class Scrobbler(QObject):
status = pyqtSignal(str)
loved_changed = pyqtSignal(bool)
def __init__(self, player):
super().__init__()
self.player = player
self.lock = threading.Lock()
self.cache: list[dict] = self._load_cache()
player.track_started.connect(self._now_playing)
player.state_changed.connect(self._on_state)
self._announced = None # (id(song), monotonic) of last now-playing
player.track_finished.connect(self._finished)
self.flush_timer = QTimer(self, interval=5 * 60 * 1000)
self.flush_timer.timeout.connect(self.flush)
self.flush_timer.start()
QTimer.singleShot(10_000, self.flush)
# ------------------------------------------------ cache
def _load_cache(self):
try:
return json.loads(SCROBBLE_CACHE.read_text())
except (OSError, ValueError):
return []
def _save_cache(self):
try:
SCROBBLE_CACHE.write_text(json.dumps(self.cache))
except OSError:
pass
@staticmethod
def lfm_on():
return bool(settings.get("lastfm/enabled") and settings.get("lastfm/session") and LastFM.has_key())
@staticmethod
def lb_on():
return settings.get("listenbrainz/enabled") and settings.get("listenbrainz/token")
# ------------------------------------------------ events
def _on_state(self, st):
"""Re-announce 'now playing' when playback (re)starts — e.g. resuming
the track restored at startup, or after a long pause (Last.fm drops
now-playing after a while)."""
s = self.player.song
if st != "playing" or s is None:
return
import time as _t
last = self._announced
if last is None or last[0] != id(s) or _t.monotonic() - last[1] > 240:
self._now_playing(s)
def _now_playing(self, s: Song):
import time as _t
self._announced = (id(s), _t.monotonic())
if s.is_cd and (not s.title or s.title.startswith("Track ")) and not s.mb_trackid:
return
if self.lfm_on():
run_async(LastFM.call, "track.updateNowPlaying", LastFM.track_params(s),
on_error=lambda e: self.status.emit(e))
if self.lb_on():
run_async(self._lb_submit, "playing_now", [self._lb_payload(s, None)],
on_error=lambda e: self.status.emit(e))
def _finished(self, s: Song, listened: float, started: int):
dur = s.duration() or 0
if s.is_stream:
ok = listened >= 30
else:
ok = dur >= 30 and (listened >= min(dur / 2, 240))
if not ok:
return
if not s.display_artist() or not s.display_title():
return
entry = {"song": s.to_dict(), "ts": started, "stream_title": s.stream_title}
with self.lock:
if self.lfm_on():
self.cache.append({**entry, "svc": "lastfm"})
if self.lb_on():
self.cache.append({**entry, "svc": "listenbrainz"})
self._save_cache()
self.flush()
def flush(self):
if not self.cache:
return
run_async(self._flush_work, on_done=lambda n: n and self.status.emit(f"Scrobbled {n} track(s)"),
on_error=lambda e: self.status.emit(f"Scrobbling deferred: {e}"))
def _flush_work(self):
sent = 0
with self.lock:
pending = list(self.cache)
lfm = [e for e in pending if e["svc"] == "lastfm"][:50]
lb = [e for e in pending if e["svc"] == "listenbrainz"][:100]
done_ids = set()
if lfm and self.lfm_on():
params = {}
for i, e in enumerate(lfm):
s = Song.from_dict(e["song"])
s.stream_title = e.get("stream_title", "")
params.update(LastFM.track_params(s, idx=i))
params[f"timestamp[{i}]"] = e["ts"]
LastFM.call("track.scrobble", params)
done_ids |= {id(e) for e in lfm}
sent += len(lfm)
if lb and self.lb_on():
payload = []
for e in lb:
s = Song.from_dict(e["song"])
s.stream_title = e.get("stream_title", "")
payload.append(self._lb_payload(s, e["ts"]))
self._lb_submit("import" if len(payload) > 1 else "single", payload)
done_ids |= {id(e) for e in lb}
sent += len(lb)
with self.lock:
self.cache = [e for e in self.cache if id(e) not in done_ids]
self._save_cache()
return sent
# ------------------------------------------------ ListenBrainz
@staticmethod
def _lb_payload(s: Song, ts):
artist, title = s.display_artist(), s.display_title()
if s.is_stream and s.stream_title and " - " in s.stream_title:
artist, title = [x.strip() for x in s.stream_title.split(" - ", 1)]
meta = {"artist_name": artist, "track_name": title}
if s.album:
meta["release_name"] = s.album
info = {"media_player": "Mulberry", "submission_client": "Mulberry", "submission_client_version": "1.0"}
if s.duration():
info["duration_ms"] = int(s.duration() * 1000)
if s.mb_trackid:
info["recording_mbid"] = s.mb_trackid
if s.mb_albumid:
info["release_mbid"] = s.mb_albumid
meta["additional_info"] = info
p = {"track_metadata": meta}
if ts:
p["listened_at"] = int(ts)
return p
@staticmethod
def _lb_submit(kind, payload):
body = json.dumps({"listen_type": kind, "payload": payload}).encode()
return http_post("https://api.listenbrainz.org/1/submit-listens", body,
headers={"Authorization": f"Token {settings.get('listenbrainz/token')}",
"Content-Type": "application/json"})
# ------------------------------------------------ love
def love(self, s: Song, loved: bool):
if self.lfm_on():
run_async(LastFM.call, "track.love" if loved else "track.unlove",
{"artist": s.display_artist(), "track": s.display_title()},
on_done=lambda _: self.status.emit("Loved on Last.fm" if loved else "Unloved on Last.fm"),
on_error=lambda e: self.status.emit(e))
if self.lb_on() and s.mb_trackid:
body = json.dumps({"recording_mbid": s.mb_trackid, "score": 1 if loved else 0}).encode()
run_async(http_post, "https://api.listenbrainz.org/1/feedback/recording-feedback", body,
headers={"Authorization": f"Token {settings.get('listenbrainz/token')}",
"Content-Type": "application/json"})
def pending(self) -> int:
return len(self.cache)
def now() -> int:
return int(time.time())