repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
discord-presence923 lines34.0 KiBraw download
#!/usr/bin/env python3
"""Discord Rich Presence daemon for rmpc / MPD.

Watches MPD over its idle protocol (instant reaction to song change, pause,
seek, stop — no polling) and mirrors playback to Discord as a "Listening to"
activity with title, artist, album, a live progress bar and album art.
Works with the official Discord client as well as Vesktop/arRPC.

MPD address and password are read from rmpc's config.ron so both stay in
sync automatically.

Album art
---------
Discord renders images by URL, so cover art has to be reachable over the
network. Local art wins by default because it is always the *right* cover:
the picture embedded in the file (MPD `readpicture`, falling back to
`albumart` for a folder cover) is downscaled to a 600 px JPEG and uploaded
to catbox.moe, with litterbox (72 h) as a fallback. Uploads are keyed by
the image's sha256, so each distinct cover is uploaded exactly once no
matter how many tracks share it.

Only the cover image ever leaves this machine — never track names, files or
listening history. Set RMPC_DISCORD_ART_UPLOAD=none to disable uploads
entirely and rely on the online lookups alone.

When a file carries no embedded art, iTunes and Deezer are searched instead.
Candidates are scored on artist+album similarity and rejected below 0.80,
with the artist gated so a matching album title cannot rescue a wrong
artist — without that, a library of Spotify-playlist rips ("This Is The
Browning") reliably matches the playlist cover instead of the real album.

Environment overrides:
  RMPC_DISCORD_CLIENT_ID    Discord application id. Default is the public
                            "Music" app id used by mpd-discord-rpc.
  RMPC_DISCORD_DISPLAY      status line under your name: artist|title|name
  RMPC_DISCORD_PAUSED       show (keep card while paused) | clear
  RMPC_DISCORD_ART          ordered art providers, default "local,itunes,deezer"
  RMPC_DISCORD_ART_UPLOAD   catbox (permanent) | litterbox (72 h) | none
  RMPC_DISCORD_ART_PX       max edge of the uploaded JPEG, default 600
  RMPC_DISCORD_FALLBACK_ART asset key or image URL when no art is found
                            ("notes" exists on the default app; empty to disable)
  MPD_HOST / MPD_PORT       override MPD address (MPD_HOST may be a socket
                            path or "password@host")

Intended to run as a systemd user service (rmpc-discord-presence.service).
Both MPD and Discord connections are retried forever, so start order and
client restarts don't matter.
"""

import hashlib
import io
import json
import os
import re
import select
import signal
import socket
import struct
import sys
import time
import unicodedata
import uuid
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

CLIENT_ID = os.environ.get("RMPC_DISCORD_CLIENT_ID", "677226551607033903")
DISPLAY = os.environ.get("RMPC_DISCORD_DISPLAY", "artist")
PAUSED = os.environ.get("RMPC_DISCORD_PAUSED", "show")
ART_PROVIDERS = [p.strip().lower() for p
                 in os.environ.get("RMPC_DISCORD_ART", "local,itunes,deezer").split(",")
                 if p.strip()]
ART_UPLOAD = os.environ.get("RMPC_DISCORD_ART_UPLOAD", "catbox").strip().lower()
ART_PX = max(64, int(os.environ.get("RMPC_DISCORD_ART_PX", "600") or 600))
FALLBACK_ART = os.environ.get("RMPC_DISCORD_FALLBACK_ART", "notes")
RMPC_CONFIG = Path(os.environ.get("RMPC_CONFIG", "~/.config/rmpc/config.ron")).expanduser()
CACHE_FILE = Path("~/.cache/rmpc-discord-presence/art-cache.json").expanduser()
USER_AGENT = "rmpc-discord-presence/2.0 (MPD Discord Rich Presence; local user script)"
DISCORD_RETRY_S = 15.0
HTTP_TIMEOUT_S = 12.0
UPLOAD_TIMEOUT_S = 40.0
MAX_ART_BYTES = 12 * 1024 * 1024
ACCEPT_SCORE = 0.80


# Discord rejects activity strings shorter than 2 or longer than 128 chars,
# and asset strings longer than 256.
def clamp(s, limit=128):
    s = " ".join(str(s).split())
    if len(s) > limit:
        s = s[: limit - 1].rstrip() + "…"
    if len(s) == 1:
        s += " "
    return s


def log(msg):
    print(msg, flush=True)


# ------------------------------------------------------------------ matching

# Qualifiers that describe an edition rather than identify the record.
_QUALIFIERS = (r"remaster|remastered|deluxe|edition|version|explicit|clean|bonus|"
               r"anniversary|expanded|reissue|re-issue|mono|stereo|live|feat\.?|ft\.?|"
               r"featuring|with|single|ep|album|edit|radio|disc|disk|cd")
_RX_BRACKET = re.compile(r"\s*[\(\[][^\)\]]*\b(?:" + _QUALIFIERS + r")\b[^\)\]]*[\)\]]", re.I)
_RX_DASH_REMASTER = re.compile(r"\s*[-–—]\s*(?:\d{4}\s*)?(?:digital\s*)?remaster(?:ed)?\b.*$", re.I)
_RX_FEAT = re.compile(r"\s+(?:feat\.?|ft\.?|featuring)\s+.*$", re.I)
_RX_DISC = re.compile(r"\s*[-–—:]?\s*\b(?:disc|disk|cd)\s*\d+\b.*$", re.I)
_RX_NONALNUM = re.compile(r"[^a-z0-9]+")


def strip_qualifiers(s):
    """Drop "(Remastered 2015)", "- 2009 Remaster", "feat. X", "Disc 2" tails."""
    out = _RX_BRACKET.sub("", str(s or ""))
    out = _RX_DASH_REMASTER.sub("", out)
    out = _RX_FEAT.sub("", out)
    out = _RX_DISC.sub("", out)
    return out.strip()


def normalize(s):
    """Lowercase, ASCII-fold, strip qualifiers, collapse punctuation to spaces."""
    out = strip_qualifiers(s)
    for a, b in (("Æ", "AE"), ("æ", "ae"), ("Ø", "O"), ("ø", "o"),
                 ("ß", "ss"), ("Œ", "OE"), ("œ", "oe"), ("&", " and ")):
        out = out.replace(a, b)
    out = unicodedata.normalize("NFKD", out)
    out = "".join(c for c in out if not unicodedata.combining(c))
    return _RX_NONALNUM.sub(" ", out.lower()).strip()


def primary_artist(s):
    """"A feat. B" -> "A"; "A; B" -> "A"; keeps "A & B" (band names)."""
    out = _RX_FEAT.sub("", str(s or ""))
    return out.split(";", 1)[0].strip()


def _levenshtein(a, b):
    if not a:
        return len(b)
    if not b:
        return len(a)
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[len(b)]


def similarity(a, b):
    """0…1 similarity over normalized token sets (order-insensitive)."""
    ta, tb = set(normalize(a).split()), set(normalize(b).split())
    if not ta and not tb:
        return 1.0
    if not ta or not tb:
        return 0.0
    inter = len(ta & tb)
    jaccard = inter / len(ta | tb)
    containment = inter / min(len(ta), len(tb))
    sa, sb = " ".join(sorted(ta)), " ".join(sorted(tb))
    lev = 1.0 - _levenshtein(sa, sb) / max(len(sa), len(sb), 1)
    # containment rewards superset titles without letting it dominate
    return max(lev, jaccard, 0.85 * containment)


def score_candidate(artist, album, cand_artist, cand_album):
    """50/50 artist/album, with the artist gated so a good album can't rescue it."""
    a = similarity(primary_artist(artist), primary_artist(cand_artist))
    b = similarity(album, cand_album)
    if a < 0.5:
        return 0.5 * a + 0.25 * b
    return 0.5 * a + 0.5 * b


# --------------------------------------------------------------------- MPD

def mpd_target():
    """(address, password) — env wins over rmpc's config.ron, else localhost."""
    host = os.environ.get("MPD_HOST", "")
    password = None
    if "@" in host and not host.startswith("/"):
        password, host = host.split("@", 1)
    if not host and RMPC_CONFIG.is_file():
        text = RMPC_CONFIG.read_text(encoding="utf-8", errors="replace")
        m = re.search(r'^\s*address\s*:\s*"([^"]+)"', text, re.M)
        if m:
            host = m.group(1)
        m = re.search(r'^\s*password\s*:\s*(?:Some\(\s*)?"([^"]+)"', text, re.M)
        if m:
            password = m.group(1)
    if not host:
        host = "127.0.0.1:6600"
    if not host.startswith(("/", "~")) and ":" not in host:
        host = f"{host}:{os.environ.get('MPD_PORT', '6600')}"
    return host, password


def mpd_quote(s):
    return '"' + str(s).replace("\\", "\\\\").replace('"', '\\"') + '"'


class MPDError(Exception):
    pass


class MPD:
    def __init__(self, address, password=None):
        self.address = address
        self.password = password
        self.sock = None
        self.buf = b""
        self.idling = False

    def connect(self):
        if self.address.startswith(("/", "~")):
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.sock.settimeout(10)
            self.sock.connect(os.path.expanduser(self.address))
        else:
            host, port = self.address.rsplit(":", 1)
            self.sock = socket.create_connection((host, int(port)), timeout=10)
            self.sock.settimeout(10)
        banner = self._line()
        if not banner.startswith("OK MPD"):
            raise MPDError(f"unexpected MPD banner: {banner!r}")
        if self.password:
            self.command(f"password {mpd_quote(self.password)}")
        return banner

    def close(self):
        try:
            if self.sock:
                self.sock.close()
        except OSError:
            pass
        self.sock = None
        self.buf = b""
        self.idling = False

    def _fill(self):
        chunk = self.sock.recv(65536)
        if not chunk:
            raise ConnectionError("MPD closed the connection")
        self.buf += chunk

    def _line(self):
        while b"\n" not in self.buf:
            self._fill()
        line, self.buf = self.buf.split(b"\n", 1)
        return line.decode("utf-8", "replace")

    def _read_response(self):
        pairs = []
        while True:
            line = self._line()
            if line == "OK":
                return pairs
            if line.startswith("ACK"):
                raise MPDError(line)
            if ": " in line:
                pairs.append(tuple(line.split(": ", 1)))

    def command(self, cmd):
        """Run one command, return response as a dict (repeated tags joined)."""
        self.sock.sendall(cmd.encode("utf-8") + b"\n")
        out = {}
        for key, value in self._read_response():
            if key in out and key in ("Artist", "AlbumArtist", "Genre", "Performer", "Composer"):
                out[key] += ", " + value
            else:
                out.setdefault(key, value)
        return out

    def _binary_chunk(self, cmd, offset):
        """One albumart/readpicture round trip -> (chunk, total, mime)."""
        self.sock.sendall(f"{cmd} {offset}\n".encode("utf-8"))
        total = mime = None
        chunk = b""
        while True:
            line = self._line()
            if line == "OK":
                return chunk, total, mime
            if line.startswith("ACK"):
                raise MPDError(line)
            if line.startswith("size: "):
                total = int(line[6:].strip() or 0)
            elif line.startswith("type: "):
                mime = line[6:].strip()
            elif line.startswith("binary: "):
                n = int(line[8:].strip() or 0)
                while len(self.buf) < n:
                    self._fill()
                chunk, self.buf = bytes(self.buf[:n]), self.buf[n:]
                # payload is followed by a bare newline, then OK

    def picture(self, uri):
        """Local cover for `uri`: embedded picture first, then folder art."""
        for cmd in ("readpicture", "albumart"):
            data = bytearray()
            total = None
            try:
                while True:
                    chunk, size, _ = self._binary_chunk(f"{cmd} {mpd_quote(uri)}", len(data))
                    if size:
                        total = size
                    if not chunk:
                        break
                    data += chunk
                    if (total and len(data) >= total) or len(data) > MAX_ART_BYTES:
                        break
            except MPDError:
                continue   # e.g. "No file exists" — try the next source
            if data:
                return bytes(data), cmd
        return None, None

    # -- idle protocol: block server-side until the player subsystem changes.
    def idle_enter(self):
        self.sock.sendall(b"idle player\n")
        self.idling = True

    def idle_collect(self):
        self._read_response()
        self.idling = False

    def idle_cancel(self):
        self.sock.sendall(b"noidle\n")
        self.idle_collect()


# ----------------------------------------------------------------- Discord

OP_HANDSHAKE, OP_FRAME, OP_CLOSE, OP_PING, OP_PONG = 0, 1, 2, 3, 4


def ipc_candidates():
    base = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    subdirs = [
        "",
        "app/com.discordapp.Discord",
        "app/dev.vencord.Vesktop",
        ".flatpak/dev.vencord.Vesktop/xdg-run",
        ".flatpak/com.discordapp.Discord/xdg-run",
        "snap.discord",
    ]
    for sub in subdirs:
        for i in range(10):
            path = os.path.join(base, sub, f"discord-ipc-{i}")
            if os.path.exists(path):
                yield path


class Discord:
    def __init__(self, client_id):
        self.client_id = client_id
        self.sock = None
        self.path = None
        self.expect_ack = True

    def connect(self):
        last_err = None
        for path in ipc_candidates():
            try:
                sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                sock.settimeout(5)
                sock.connect(path)
                self.sock = sock
                self.path = path
                self._send(OP_HANDSHAKE, {"v": 1, "client_id": self.client_id})
                deadline = time.time() + 5
                while time.time() < deadline:
                    op, obj = self._recv_frame(deadline - time.time())
                    if op == OP_FRAME and obj.get("evt") == "READY":
                        user = (obj.get("data") or {}).get("user") or {}
                        return path, user.get("username") or "unknown user"
                    if op == OP_CLOSE:
                        raise ConnectionError(f"handshake rejected: {obj}")
                raise TimeoutError("no READY within 5s")
            except OSError as e:
                last_err = e
                self.close(silent=True)
        raise last_err or ConnectionError("no Discord IPC socket found")

    def close(self, silent=False):
        if self.sock:
            if not silent:
                try:
                    self._send(OP_CLOSE, {})
                except OSError:
                    pass
            try:
                self.sock.close()
            except OSError:
                pass
        self.sock = None

    def _send(self, op, payload):
        data = json.dumps(payload).encode("utf-8")
        self.sock.sendall(struct.pack("<II", op, len(data)) + data)

    def _read_exact(self, n):
        buf = b""
        while len(buf) < n:
            chunk = self.sock.recv(n - len(buf))
            if not chunk:
                raise ConnectionError("Discord closed the connection")
            buf += chunk
        return buf

    def _recv_frame(self, timeout):
        self.sock.settimeout(max(0.1, timeout))
        op, length = struct.unpack("<II", self._read_exact(8))
        body = self._read_exact(length) if length else b"{}"
        try:
            return op, json.loads(body.decode("utf-8", "replace"))
        except ValueError:
            return op, {}

    def set_activity(self, activity):
        """Send SET_ACTIVITY; return an error dict from Discord, or None."""
        nonce = str(uuid.uuid4())
        self._send(OP_FRAME, {
            "cmd": "SET_ACTIVITY",
            "args": {"pid": os.getpid(), "activity": activity},
            "nonce": nonce,
        })
        if not self.expect_ack:
            return None
        deadline = time.time() + 6
        while time.time() < deadline:
            try:
                op, obj = self._recv_frame(deadline - time.time())
            except TimeoutError:
                break
            if op == OP_PING:
                self._send(OP_PONG, obj)
            elif op == OP_CLOSE:
                raise ConnectionError("Discord closed the connection")
            elif op == OP_FRAME and obj.get("nonce") == nonce:
                if obj.get("evt") == "ERROR":
                    return obj.get("data") or {"message": "unknown error"}
                return None
        # Some IPC bridges never ack; don't stall every update over it.
        self.expect_ack = False
        log("discord: no SET_ACTIVITY ack, continuing without waiting for acks")
        return None

    def pump(self):
        """Handle one unsolicited frame (ping / close) outside of a send."""
        op, obj = self._recv_frame(2)
        if op == OP_PING:
            self._send(OP_PONG, obj)
        elif op == OP_CLOSE:
            raise ConnectionError("Discord closed the connection")


# -------------------------------------------------------------- album art

MISSING = object()


class ArtCache:
    """key -> url ("" = known miss). Values may carry "|exp:<unix>" for TTLs."""

    def __init__(self, path):
        self.path = path
        self.map = {}
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            if isinstance(data, dict):
                self.map = {k: v for k, v in data.items() if isinstance(v, str)}
        except (OSError, ValueError):
            pass

    def get(self, key):
        """MISSING = not cached; None = cached miss; str = cached url."""
        value = self.map.get(key)
        if value is None:
            return MISSING
        if value == "":
            return None
        url, _, exp = value.partition("|exp:")
        if exp:
            try:
                if time.time() >= float(exp):
                    return MISSING
            except ValueError:
                return MISSING
        return url

    def put(self, key, url, ttl=None):
        value = url or ""
        if url and ttl:
            value = f"{url}|exp:{int(time.time() + ttl)}"
        self.map[key] = value
        if len(self.map) > 2000:
            self.map = dict(list(self.map.items())[-1000:])
        try:
            self.path.parent.mkdir(parents=True, exist_ok=True)
            self.path.write_text(json.dumps(self.map, indent=0, sort_keys=True),
                                 encoding="utf-8")
        except OSError:
            pass


def to_jpeg(data, max_px=ART_PX):
    """Downscale to a modest JPEG so uploads stay small and fast."""
    try:
        from PIL import Image
        im = Image.open(io.BytesIO(data))
        im.thumbnail((max_px, max_px), Image.LANCZOS)
        buf = io.BytesIO()
        im.convert("RGB").save(buf, "JPEG", quality=88, optimize=True)
        return buf.getvalue()
    except Exception as e:
        log(f"art: could not re-encode cover ({e}); uploading as-is")
        return data if len(data) <= 4 * 1024 * 1024 else None


def multipart(fields, jpeg, field="fileToUpload", filename="cover.jpg"):
    boundary = "----rmpc-discord-" + uuid.uuid4().hex
    out = bytearray()
    for key, value in fields:
        out += (f"--{boundary}\r\n"
                f'Content-Disposition: form-data; name="{key}"\r\n\r\n'
                f"{value}\r\n").encode("utf-8")
    out += (f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="{field}"; filename="{filename}"\r\n'
            f"Content-Type: image/jpeg\r\n\r\n").encode("utf-8")
    out += jpeg + f"\r\n--{boundary}--\r\n".encode("utf-8")
    return bytes(out), f"multipart/form-data; boundary={boundary}"


class ArtResolver:
    """Cover art URL for the current song. Local art first — always the right
    cover — with scored iTunes/Deezer lookups when a file carries none."""

    def __init__(self):
        self.cache = ArtCache(CACHE_FILE)
        self.last_request = {}

    # -- http helpers
    def _open(self, req, timeout=HTTP_TIMEOUT_S):
        return urllib.request.urlopen(req, timeout=timeout)

    def _get_json(self, base, params, host):
        self._throttle(host)
        url = base + "?" + urllib.parse.urlencode(params)
        req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
        with self._open(req) as resp:
            return json.loads(resp.read().decode("utf-8", "replace"))

    def _throttle(self, host):
        """Polite spacing between calls to the same provider (iTunes ~20/min)."""
        gap = 3.0 if host == "itunes" else 0.5
        wait = gap - (time.time() - self.last_request.get(host, 0.0))
        if wait > 0:
            time.sleep(wait)
        self.last_request[host] = time.time()

    # -- upload
    def upload(self, jpeg):
        """Return (url, ttl_seconds). catbox is permanent; litterbox expires."""
        if ART_UPLOAD == "none":
            return None, None
        targets = []
        if ART_UPLOAD != "litterbox":
            targets.append(("https://catbox.moe/user/api.php",
                            [("reqtype", "fileupload"), ("userhash", "")], None))
        targets.append(("https://litterbox.catbox.moe/resources/internals/api.php",
                        [("reqtype", "fileupload"), ("time", "72h")], 70 * 3600))
        for url, fields, ttl in targets:
            body, ctype = multipart(fields, jpeg)
            req = urllib.request.Request(url, data=body, headers={
                "User-Agent": USER_AGENT, "Content-Type": ctype})
            host = urllib.parse.urlsplit(url).hostname or url
            try:
                with self._open(req, UPLOAD_TIMEOUT_S) as resp:
                    out = resp.read().decode("utf-8", "replace").strip()
                if out.startswith("https://") and len(out) <= 256:
                    return out, ttl
                log(f"art: {host} returned an unexpected body: {out[:120]!r}")
            except OSError as e:
                log(f"art: upload to {host} failed ({e})")
        return None, None

    # -- providers
    def _itunes(self, artist, album, title):
        best = None
        for term, want in ((f"{artist} {strip_qualifiers(album)}".strip(), strip_qualifiers(album)),
                           (f"{artist} {strip_qualifiers(title)}".strip(), strip_qualifiers(title))):
            if not want:
                continue
            entity = "album" if want == strip_qualifiers(album) and album else "song"
            data = self._get_json("https://itunes.apple.com/search", {
                "term": term, "entity": entity, "media": "music", "limit": 5}, "itunes")
            for r in data.get("results") or []:
                art = r.get("artworkUrl100")
                cand_artist = r.get("artistName")
                if not art or not cand_artist:
                    continue
                cand_album = r.get("collectionName") or r.get("trackName") or ""
                s = score_candidate(artist, want, cand_artist, cand_album)
                if best is None or s > best[0]:
                    best = (s, art.replace("100x100bb", f"{ART_PX}x{ART_PX}bb"),
                            cand_artist, cand_album)
            if best and best[0] >= ACCEPT_SCORE:
                break
        return best

    def _deezer(self, artist, album, title):
        want = strip_qualifiers(album) or strip_qualifiers(title)
        if not want:
            return None
        if strip_qualifiers(album):
            endpoint = "https://api.deezer.com/search/album"
            query = f'artist:"{artist}" album:"{want}"'
        else:
            endpoint = "https://api.deezer.com/search"
            query = f'artist:"{artist}" track:"{want}"'
        data = self._get_json(endpoint, {"q": query, "limit": 5}, "deezer")
        if data.get("error"):
            return None
        best = None
        for r in data.get("data") or []:
            row = r.get("album") if "album" in r and isinstance(r.get("album"), dict) else r
            art = row.get("cover_xl") or row.get("cover_big")
            cand_artist = ((r.get("artist") or row.get("artist") or {}) or {}).get("name")
            if not art or not cand_artist or len(art) > 256:
                continue
            cand_album = row.get("title") or ""
            s = score_candidate(artist, want, cand_artist, cand_album)
            if best is None or s > best[0]:
                best = (s, art, cand_artist, cand_album)
        return best

    # -- entry point
    def url_for(self, mpd, song):
        if not song:
            return None
        file = song.get("file", "")
        artist = primary_artist(song.get("AlbumArtist") or song.get("Artist") or "")
        album = song.get("Album") or ""
        title = song.get("Title") or ""
        if not (artist or album or title):
            return None

        label = f"{artist or '?'} — {album or title}"

        # Local art is keyed by *file*, never by album: a playlist rip gives
        # every track the same album tag ("This Is The Browning") while each
        # file still carries its own real cover.
        if "local" in ART_PROVIDERS and not file.startswith(("http://", "https://")):
            url = self._local(mpd, file, label)
            if url:
                return url
            if url is False:
                return None   # art exists but the upload failed: retry later

        key = normalize(artist) + "|" + normalize(album or title)
        cached = self.cache.get(key)
        if cached is not MISSING:
            return cached

        for provider in ART_PROVIDERS:
            if provider in ("itunes", "deezer"):
                try:
                    best = (self._itunes(artist, album, title) if provider == "itunes"
                            else self._deezer(artist, album, title))
                except (OSError, ValueError) as e:
                    log(f"art: {provider} lookup failed for {label} ({e})")
                    return None   # transient — don't cache a miss
                if best and best[0] >= ACCEPT_SCORE:
                    log(f"art: {provider} matched '{best[2]} — {best[3]}' "
                        f"score {best[0]:.2f} for {label}")
                    self.cache.put(key, best[1])
                    return best[1]
                if best:
                    log(f"art: {provider} best for {label} was "
                        f"'{best[2]} — {best[3]}' score {best[0]:.2f} — rejected")

        log(f"art: no cover found for {label}")
        self.cache.put(key, None)
        return None

    def _local(self, mpd, file, label):
        """Local cover -> uploaded URL. False means 'found but upload failed'.

        Cached per file so repeat events (pause, seek, volume) never re-read
        the picture, and per image sha256 so a cover shared by a whole album
        is uploaded exactly once."""
        if ART_UPLOAD == "none":
            return None
        file_key = "file|" + file
        cached = self.cache.get(file_key)
        if cached is not MISSING:
            return cached or None   # cached miss falls through to the lookups

        try:
            raw, source = mpd.picture(file)
        except (OSError, MPDError) as e:
            log(f"art: reading local cover failed ({e})")
            return None
        if not raw:
            self.cache.put(file_key, None)
            return None

        jpeg = to_jpeg(raw)
        if not jpeg:
            return None
        digest = "sha256|" + hashlib.sha256(jpeg).hexdigest()
        known = self.cache.get(digest)
        if known is not MISSING and known:
            self.cache.put(file_key, known)
            log(f"art: reusing uploaded cover for {label}")
            return known

        url, ttl = self.upload(jpeg)
        if url:
            log(f"art: uploaded {source} cover for {label} "
                f"({len(jpeg) // 1024} KiB) -> {url}")
            self.cache.put(file_key, url, ttl)
            self.cache.put(digest, url, ttl)
            return url
        return False


# ---------------------------------------------------------------- activity

STATUS_DISPLAY_OK = True  # cleared if the client rejects status_display_type


def build_activity(status, song, art_url):
    state = status.get("state")
    if state not in ("play", "pause") or not song:
        return None
    if state == "pause" and PAUSED != "show":
        return None

    title = song.get("Title") or os.path.splitext(os.path.basename(song.get("file", "")))[0] or "Unknown"
    artist = song.get("Artist") or song.get("AlbumArtist") or song.get("Name") or ""
    album = song.get("Album") or ""

    activity = {
        "type": 2,  # "Listening to …"
        "details": clamp(("" if state == "play" else "⏸ ") + title),
    }
    if artist:
        activity["state"] = clamp(artist)
    if STATUS_DISPLAY_OK:
        display = {"name": 0, "artist": 1, "title": 2}.get(DISPLAY, 1)
        if display == 1 and not artist:
            display = 0
        activity["status_display_type"] = display

    assets = {}
    image = art_url or FALLBACK_ART
    if image:
        assets["large_image"] = image
        hover = album + (f" ({song['Date'][:4]})" if song.get("Date") else "")
        if art_url and hover.strip():
            assets["large_text"] = clamp(hover)
    if assets:
        activity["assets"] = assets

    if state == "play":
        def as_float(v):
            try:
                return float(v)
            except (TypeError, ValueError):
                return 0.0
        elapsed = as_float(status.get("elapsed"))
        duration = as_float(status.get("duration"))
        start = time.time() - elapsed
        timestamps = {"start": int(start * 1000)}
        if duration > 0:
            timestamps["end"] = int((start + duration) * 1000)
        activity["timestamps"] = timestamps

    return activity


def describe(activity):
    if activity is None:
        return "cleared (stopped)"
    icon = "⏸" if activity["details"].startswith("⏸") else "▶"
    title = activity["details"].lstrip("⏸ ")
    artist = activity.get("state")
    return f"{icon} {title}" + (f" — {artist}" if artist else "")


# -------------------------------------------------------------------- main

def push(dc, activity):
    """SET_ACTIVITY with a one-shot retry if status_display_type is rejected."""
    global STATUS_DISPLAY_OK
    err = dc.set_activity(activity)
    if err and activity and "status_display_type" in activity \
            and "status_display_type" in str(err.get("message", "")):
        STATUS_DISPLAY_OK = False
        activity.pop("status_display_type")
        log("discord: client rejected status_display_type, retrying without it")
        err = dc.set_activity(activity)
    if err:
        log(f"discord: SET_ACTIVITY error: {err}")


def main():
    address, password = mpd_target()
    log(f"rmpc-discord-presence: mpd={address} client_id={CLIENT_ID} "
        f"art={','.join(ART_PROVIDERS)} upload={ART_UPLOAD}")

    signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))

    art = ArtResolver()
    mpd = None
    dc = None
    next_discord_try = 0.0
    mpd_failures = 0
    last_desc = object()

    try:
        while True:
            # -- ensure MPD ------------------------------------------------
            if mpd is None:
                try:
                    mpd = MPD(address, password)
                    banner = mpd.connect()
                    mpd_failures = 0
                    log(f"mpd: connected ({banner})")
                except (OSError, MPDError) as e:
                    if mpd:
                        mpd.close()
                    mpd = None
                    if mpd_failures == 0:
                        log(f"mpd: unavailable ({e}); presence cleared, retrying")
                        if dc:
                            try:
                                push(dc, None)
                            except OSError:
                                dc.close(silent=True)
                                dc = None
                    mpd_failures += 1
                    time.sleep(min(30, 5 * mpd_failures))
                    continue

            # -- ensure Discord --------------------------------------------
            if dc is None and time.time() >= next_discord_try:
                next_discord_try = time.time() + DISCORD_RETRY_S
                try:
                    dc = Discord(CLIENT_ID)
                    path, who = dc.connect()
                    log(f"discord: connected as {who} via {path}")
                except OSError as e:
                    if dc:
                        dc.close(silent=True)
                    dc = None
                    log(f"discord: not available ({e}); retrying every {DISCORD_RETRY_S:.0f}s")

            # -- read state, push presence ---------------------------------
            try:
                status = mpd.command("status")
                song = mpd.command("currentsong")
                art_url = art.url_for(mpd, song) if dc else None
            except (OSError, MPDError) as e:
                log(f"mpd: lost connection ({e})")
                mpd.close()
                mpd = None
                continue

            if dc:
                try:
                    activity = build_activity(status, song, art_url)
                    push(dc, activity)
                    desc = describe(activity)
                    if desc != last_desc:
                        log(f"presence: {desc}")
                        last_desc = desc
                except OSError as e:
                    log(f"discord: lost connection ({e})")
                    dc.close(silent=True)
                    dc = None

            # -- wait for the next player event ----------------------------
            try:
                mpd.idle_enter()
                watch = [mpd.sock] + ([dc.sock] if dc else [])
                timeout = None if dc else DISCORD_RETRY_S
                readable, _, _ = select.select(watch, [], [], timeout)
                if dc and dc.sock in readable:
                    try:
                        dc.pump()
                    except OSError as e:
                        log(f"discord: lost connection ({e})")
                        dc.close(silent=True)
                        dc = None
                if mpd.sock in readable:
                    mpd.idle_collect()
                else:
                    mpd.idle_cancel()
            except (OSError, MPDError) as e:
                log(f"mpd: lost connection ({e})")
                mpd.close()
                mpd = None
    finally:
        if dc:
            try:
                dc.set_activity(None)
            except OSError:
                pass
            dc.close()
        if mpd:
            mpd.close()
        log("rmpc-discord-presence: stopped")


if __name__ == "__main__":
    main()