Mulberry/mulberry/scrobble.py
Mulberry 615b21d64a
Mulberry 1.1.0: Material You music player for Linux and Windows
- KDE/Windows accent-driven Material 3 theme, live updating
- Library, tabbed playlists, smart/saved lists, queue, ratings
- mpv and Qt Multimedia engines, EQ, ReplayGain, gapless
- Synced lyrics (LRCLIB, NetEase, local .lrc), covers, MusicBrainz tags
- Last.fm/ListenBrainz scrobbling, MPRIS, Windows media keys
- Audio CD playback and ripping
- PyInstaller, Inno Setup and AppImage builds via GitHub Actions

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

272 lines
10 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 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 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.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 _now_playing(self, s: Song):
if s.is_cd and not s.title:
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())