# deck-it - music module # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Now playing and volume, via playerctl and wpctl.""" import base64 import hashlib import mimetypes import subprocess from pathlib import Path from urllib.parse import unquote, urlsplit from ..module import Module, ModuleError SEP = "\x1f" BASE_ACTIONS = { "mute": ["wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", "toggle"], "prev": ["playerctl", "previous"], "play": ["playerctl", "play-pause"], "next": ["playerctl", "next"], } def _run(cmd, timeout=2): try: return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip() except (OSError, subprocess.TimeoutExpired): return "" def _popen(cmd): subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def _frame(path): """A JPEG frame from a video, for players that give videos no cover.""" try: return subprocess.run( ["ffmpeg", "-v", "error", "-i", path, "-vf", "thumbnail,scale=480:-2", "-frames:v", "1", "-f", "image2pipe", "-c:v", "mjpeg", "-"], capture_output=True, timeout=10).stdout except (OSError, subprocess.TimeoutExpired): return b"" def make(cfg: dict) -> Module: run = cfg.get("run", _run) popen = cfg.get("popen", _popen) frame = cfg.get("frame", _frame) # The cover served at /api/music/image/: only the current track's, # so the tablet names a key, never a path. cur = {"key": None, "src": None, "image": None} def serve(src): key = hashlib.sha1(src.encode()).hexdigest()[:16] if key != cur["key"]: cur.update(key=key, src=src, image=None) return f"/api/music/image/{key}" def image(key): if key != cur["key"]: return None if cur["image"] is None: src = cur["src"] if src.startswith("data:"): head, _, data = src.partition(",") try: cur["image"] = (base64.b64decode(data), head[5:].split(";")[0]) except ValueError: cur["image"] = () else: out = frame(unquote(urlsplit(src).path)) cur["image"] = (out, "image/jpeg") if out else () return cur["image"] or None def state(): fmt = SEP.join(["{{status}}", "{{title}}", "{{artist}}", "{{album}}", "{{mpris:length}}", "{{position}}", "{{mpris:artUrl}}", "{{playerName}}", "{{xesam:url}}"]) out = run(["playerctl", "metadata", "--format", fmt]) vol = run(["wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@"]) volume = {"level": round(float(vol.split()[1]) * 100) if len(vol.split()) > 1 else 0, "muted": "MUTED" in vol} if not out: return {"status": "Stopped", "volume": volume} status, title, artist, album, length, pos, art, name, url = (out.split(SEP) + [""] * 9)[:9] if art.startswith(("http://", "https://")): art_src = art elif art.startswith("file://"): art_src = "/api/art?v=" + str(abs(hash(art))) elif art.startswith("data:image/"): art_src = serve(art) elif (not art and url.startswith("file://") and (mimetypes.guess_type(Path(unquote(urlsplit(url).path)).name)[0] or "").startswith("video/")): art_src = serve(url) else: art_src = None return {"status": status, "title": title, "artist": artist, "album": album, "length": float(length or 0) / 1e6, "position": float(pos or 0) / 1e6, "art": art_src, "player": name.split(".")[0], "volume": volume} def seek(body): pos = body.get("position") if not isinstance(pos, (int, float)) or pos < 0: raise ModuleError("position must be a number") popen(["playerctl", "position", str(round(float(pos), 1))]) def volume(body): level = body.get("level") if isinstance(level, bool) or not isinstance(level, (int, float)) or not 0 <= level <= 100: raise ModuleError("level must be 0-100") popen(["wpctl", "set-volume", "@DEFAULT_AUDIO_SINK@", f"{level / 100:.2f}"]) actions = {name: (lambda cmd: (lambda body: popen(cmd)))(cmd) for name, cmd in BASE_ACTIONS.items()} actions["seek"] = seek actions["volume"] = volume return Module(name="music", title="Music", state=state, actions=actions, image=image)