aboutsummaryrefslogtreecommitdiffstats
path: root/deckit
diff options
context:
space:
mode:
Diffstat (limited to 'deckit')
-rw-r--r--deckit/modules/music.py53
1 files changed, 50 insertions, 3 deletions
diff --git a/deckit/modules/music.py b/deckit/modules/music.py
index f590cc0..218d2c4 100644
--- a/deckit/modules/music.py
+++ b/deckit/modules/music.py
@@ -16,7 +16,12 @@
"""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
@@ -41,24 +46,66 @@ 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/<key>: 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}}"])
+ "{{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 = (out.split(SEP) + [""] * 8)[:8]
+ 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,
@@ -80,4 +127,4 @@ def make(cfg: dict) -> Module:
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)
+ return Module(name="music", title="Music", state=state, actions=actions, image=image)