aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/music.py
blob: 218d2c4949ab9e22756faaebb8d1dfe525a6c053 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# deck-it - music module
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# 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/<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}}", "{{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)