Initial commit: MediaDeck web remote for a Linux media PC

Python bridge (aiohttp, single asyncio loop) between a tablet browser and
a Linux media PC: MPRIS players, PipeWire audio (pactl), virtual keyboard
and touchpad (uinput), power and session control (logind).

- Tablet UI with player, audio, touchpad, launchers and system tabs (fr/en)
- Launchers stored in SQLite and managed from /admin; raw commands are
  opt-in (admin.allow_custom_command)
- Optional text entry, translated to key presses from the PC's real
  keyboard layout with libxkbcommon and never through the clipboard
  (features.text_input, off by default)
- Local HTTPS with a private CA restricted by name constraints (make cert)
- Token-protected WebSocket and REST API, strict CSP, no JS dependencies

Checked: pyright 0 errors, 87 unit tests, browser tests in headless
Chromium. Not yet exercised on the real tablet, nor with real uinput key
presses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Denis
2026-10-23 23:33:10 +02:00
commit e823b2d470
43 changed files with 7717 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
# Make impose les tabulations dans les recettes
[Makefile]
indent_style = tab
+19
View File
@@ -0,0 +1,19 @@
# Fins de ligne normalisées en LF
* text=auto eol=lf
*.py text diff=python
*.js text
*.css text diff=css
*.html text diff=html
*.toml text
*.json text
*.md text diff=markdown
*.webmanifest text
*.rules text
*.in text
Makefile text
*.svg text
*.png binary
*.jpg binary
*.ico binary
+55
View File
@@ -0,0 +1,55 @@
# Python
__pycache__/
*.py[cod]
*.egg-info/
build/
dist/
.venv/
venv/
.pyright/
.pytest_cache/
.coverage
htmlcov/
# Configuration locale : contient le jeton d'accès
config.toml
!config.example.toml
*.local.toml
# Secrets et données personnelles
.env
.env.*
*.secret
*secret*
*password*
*passwd*
*credentials*
*.token
token.txt
*.pem
*.key
*.crt
*.p12
*.pfx
id_rsa*
id_ed25519*
*.kdbx
.netrc
*.db
*.sqlite
*.sqlite3
*.mbox
*.eml
contacts*.vcf
# Éditeurs / OS
.vscode/
!.vscode/extensions.json
.idea/
*.swp
*~
.DS_Store
# Service généré par make service-install
systemd/*.service
!systemd/*.service.in
+177
View File
@@ -0,0 +1,177 @@
# CLAUDE.md — MediaDeck
Contexte pour reprendre le projet avec Claude Code (VSCodium). À lire avant toute modification.
## Objectif
Télécommande web pour un **PC multimédia Linux** (Debian / LMDE, KDE Plasma), utilisée depuis une
**tablette Android** posée à côté. Le PC exécute un pont Python ; la tablette n'a besoin que d'un
navigateur en plein écran. KDE Connect a été écarté : MPRIS, PipeWire, uinput et logind sont pilotés
directement, ce qui donne plus de contrôle et une interface libre.
## Conventions (obligatoires)
- Code, identifiants et messages de log/erreur en **anglais** ; commentaires et docstrings en **français**.
- Indentation **4 espaces** partout (Python, JS, CSS, HTML, JSON, TOML). Seule exception : les recettes du Makefile (tabulations).
- JavaScript : **classes** ES, modules natifs, aucune dépendance ni étape de build.
- Python ≥ 3.11, typé ; **pyright** doit rester à 0 erreur (`make lint`).
- Documentation double : `README.md` (fr) et `README-EN.md` (en), à garder synchronisés.
- Toutes les opérations système passent par le **Makefile**.
- `.gitignore` doit exclure tout secret ; `config.toml` contient le jeton et ne doit jamais être commité.
- Fins de ligne LF (`.gitattributes`, `.editorconfig`).
## Commandes
```bash
make install # .venv + dépendances (+ pyright)
make config # ~/.config/mediadeck/config.toml (mode 600) + jeton aléatoire
make dev # serveur au premier plan, logs debug
make lint test # pyright + unittest
make url # URL tablette + QR code
make uinput # règle udev uaccess (sudo)
make service-install / status / logs
```
## Architecture
```
mediadeck/
├── __main__.py CLI : --config, --check, --url, -v ; lance web.run_app
├── config.py TOML → dataclasses gelées ; validation stricte ; refuse un fichier lisible par group/other
├── server.py aiohttp : /, /static/*, /ws (jeton), /art (jeton) ; diffusion d'état anti-rebond 100 ms + toutes les 10 s
├── mpris.py MprisManager : découverte via NameOwnerChanged, PropertiesChanged + Seeked ; Player.execute()
├── audio.py AudioManager : `pactl -f json list sinks`, `pactl subscribe` (relancé si mort), set-sink-*
├── input.py VirtualInput : 2 périphériques uinput (clavier + pointeur), touches en liste blanche + TYPING_KEYS (saisie)
├── keymap.py disposition réelle (kxkbrc / setxkbmap / D-Bus KDE) -> table keysym -> frappes (libxkbcommon via ctypes)
├── text.py TextTyper : texte -> frappes uinput, verrou, relâchement garanti, 500 caractères max
├── system.py SystemControl : logind (suspend/reboot/poweroff), ScreenSaver.Lock, lancement des lanceurs
├── launchers.py LauncherStore (SQLite), validation, build_argv(), applications .desktop, navigateurs
├── admin.py API REST /api/* des lanceurs (jeton en en-tête Authorization: Bearer)
├── tls.py HTTPS local : CA privée + certificat serveur (CLI openssl), contexte SSL, enable_tls()
└── web/
├── index.html sprite SVG + 4 panneaux (player, audio, remote, system)
├── admin.html page /admin : liste + dialogue d'édition des lanceurs
└── static/common.js Storage, I18n(messages), $ : partagés par app.js et admin.js
static/admin.js Api, LauncherList, LauncherForm, AdminPage ; static/admin.css
static/app.js Throttle, Connection, PlayerPanel, AudioPanel,
Touchpad, RemotePanel, HoldButton, LauncherPanel, SystemPanel, Toast, Tabs, ScreenKeeper, App
```
Tout tourne dans **une seule boucle asyncio**. Le service doit s'exécuter **dans la session graphique**
(service `systemd --user`, `WantedBy=graphical-session.target`) pour accéder au bus D-Bus de session et à PipeWire.
## Protocole WebSocket
Connexion : `ws://host:port/ws?token=…` (HTTP 401 sinon). Messages JSON ≤ 4 Ko.
Client → serveur :
```json
{"domain": "player", "action": "play_pause|play|pause|stop|next|previous|seek|set_position|set_volume|shuffle|loop|raise", "player": "<bus name>", "value": …}
{"domain": "audio", "action": "set_volume|toggle_mute|set_default", "sink": "<name|null=défaut>", "value": 0.0-max_volume}
{"domain": "input", "action": "key", "key": "<nom de KEY_NAMES>"}
{"domain": "input", "action": "move|scroll", "dx": int, "dy": int}
{"domain": "input", "action": "click", "button": "left|right|middle"}
{"domain": "input", "action": "text", "text": "<1 à 500 caractères>"} // features.text_input ; erreur renvoyée pour les caractères impossibles
{"domain": "system", "action": "power", "kind": "suspend|reboot|poweroff"}
{"domain": "system", "action": "lock|launch", "id": "<launcher id>"}
```
- `seek` est relatif, en µs. Le client l'utilise de préférence à `set_position`, qui exige un trackid valide.
- Volumes en flottants 0..1. Positions et durées MPRIS en **microsecondes**.
Serveur → client :
- `{"type":"state", "mpris":{players, active, available}, "audio":{…}, "input":{available, reason, keys, text:{available, reason}}, "system":{…}}`
- `{"type":"error","message":"…"}`
### API REST des lanceurs (`admin.enabled`)
`Authorization: Bearer <jeton>` obligatoire (401 sinon) ; le jeton en paramètre d'URL est refusé. Corps JSON ≤ 16 Ko, erreurs `{"error": "…"}`.
```
GET /api/launchers {launchers:[{id,label,icon,kind,spec}], icons, kinds, browsers:[{id,name,installed,fullscreen}], allow_command}
POST /api/launchers {label, icon, kind, spec} → 201 (id généré à partir du nom)
PUT /api/launchers/{id} idem → 200 ; 404 si inconnu
DELETE /api/launchers/{id} → 204
POST /api/launchers/reorder {ids:[…]} (tous les ids exactement une fois) → 204
GET /api/apps [{id: "x.desktop", name}]
GET /admin page HTML (publique comme /, l'API exige le jeton)
```
`kind`/`spec` : `web` → `{url, browser, fullscreen}` ; `app` → `{desktop_id}` ; `command` → `{argv:[…]}`.
403 pour une commande brute si `admin.allow_custom_command` est faux (sauf commande existante inchangée : renommage OK).
Chaque modification déclenche `notify()` : les tablettes reçoivent la nouvelle liste (`system.launchers`, `system.admin`) sans recharger.
La pochette locale (`file://`) n'est jamais transmise : elle est remplacée par `/art?player=…&v=<hash>`, auquel le client ajoute le jeton.
## Décisions et raisons
- **aiohttp plutôt que Django** : un seul processus, pas de base de données ; Channels serait surdimensionné.
- **pactl plutôt que wpctl** : sortie JSON stable et `subscribe` pour les événements ; compatible pipewire-pulse.
- **uinput plutôt que xdotool/ydotool** : fonctionne sous Wayland. Deux périphériques distincts pour une bonne classification par libinput.
- **Règle udev `TAG+="uaccess"`** plutôt que le groupe `input`, qui permettrait de lire tous les claviers.
- **Saisie de texte par traduction de la disposition** (remplace l'ancien « pas de saisie de texte » : le piège était la disposition, pas la saisie).
Chaque caractère devient la/les touches que produirait la disposition réelle du PC : lecture de `kxkbrc` (sinon `setxkbmap -query`), index actif via `org.kde.keyboard`,
compilation par libxkbcommon (`ctypes`), table keysym -> (touche, Maj, AltGr), touches mortes par décomposition NFD (ê = `dead_circumflex` + e), accents isolés = touche morte + espace.
**Pas de presse-papiers** (Ctrl+V) : Klipper garde un historique en clair, mots de passe compris, et seul le Ctrl+V fonctionne (pas dans un terminal).
Touches autorisées pour la saisie : `TYPING_KEYS` (bloc principal + `<>` + AltGr), contrôlées dans `VirtualInput.write_keys` ; le client ne choisit jamais un code, seulement du texte.
- **`features.text_input` désactivé par défaut** : un clavier complet donne le contrôle total du PC à qui a le jeton (Super + saisie = terminal), même logique que `allow_custom_command`.
Limite de 500 caractères : une trame WebSocket est limitée à 4 Ko et 500 × 4 octets (emoji) = 2 Ko ; au-delà aiohttp coupe la connexion.
- Fenêtre de saisie **non modale** (`dialog.show()`) : le pavé reste utilisable, et un `showModal()` assombrirait les toasts (hors couche supérieure).
- **Imports dbus-next par sous-modules** (`dbus_next.signature`, `dbus_next.aio.message_bus`, `dbus_next.constants`) : sinon pyright signale `reportPrivateImportUsage`.
- Les proxies dbus-next sont typés `Any`, car leurs méthodes `call_*` / `on_*` sont générées dynamiquement.
- **HTTPS par CA privée + `openssl`** plutôt que mkcert : aucune dépendance à installer, et la CA reçoit des `nameConstraints` (réseaux privés, `localhost`, `*.local`, `*.lan`, nom de la machine). La tablette fait confiance à cette CA : si sa clé fuitait, elle ne pourrait pas usurper un site public. Clés EC P-256, CA 10 ans, certificat serveur 825 jours (réémis sans toucher à la CA).
- La CA publique est servie sur `/ca.crt` par le serveur lui-même (route publique, uniquement si `tls_ca` est défini) : la tablette l'installe après avoir accepté l'avertissement une fois, sans second port ni pare-feu à ouvrir.
- **CSP stricte** (`script-src 'self'`, `style-src 'self'`) : aucun attribut `style=""` ni script inline dans le HTML. En JS, utiliser `el.style.setProperty()`, qui est autorisé.
- Lanceurs : uniquement des listes argv, jamais de shell, avec `start_new_session=True`.
- **Lanceurs en base SQLite** (`~/.local/share/mediadeck/launchers.db`, mode 600, module standard `sqlite3`, aucune dépendance) plutôt qu'en TOML : modifiables à chaud depuis `/admin` sans redémarrer ni éditer un fichier. Les `[[launchers]]` de `config.toml` ne servent qu'à un **import unique** (drapeau `meta.seeded`), puis sont ignorés.
- **Sécurité de l'administration** : un lanceur « commande » = exécution de code avec les droits de l'utilisateur pour quiconque a le jeton. Donc trois types : `web` (URL http(s) + navigateur d'une liste fermée) et `app` (fichier `.desktop` choisi dans une liste, lancé par `gio launch <chemin résolu côté serveur>`) n'acceptent aucune commande du client ; `command` exige `[admin] allow_custom_command = true` dans `config.toml`, fichier que le client ne peut pas modifier. La commande est reconstruite au lancement depuis la base (`build_argv`), jamais fournie par le message WebSocket.
- API REST avec jeton en **en-tête** `Authorization` (pas dans l'URL : journaux, historique) ; un en-tête personnalisé n'est pas ajoutable par un site tiers sans CORS, donc pas de CSRF.
- **Onglet Lanceurs distinct de l'onglet Système** : les lanceurs (usage fréquent, sans risque) ne côtoient plus verrouillage/veille/redémarrage/extinction (rares, destructifs, appui long), pour éviter un mauvais appui. Pur changement d'UI : le protocole WebSocket est inchangé (`system.launchers` / `system.admin` dans l'état, action `system` + `launch`). `LauncherPanel` et `SystemPanel` sont deux classes ; `tabbar` en `grid-auto-flow: column` (nombre d'onglets libre).
- `common.js` : `Storage`/`I18n`/`$` extraits d'`app.js` pour être partagés avec `admin.js` (l'`I18n` prend les messages en paramètre ; la langue choisie est commune aux pages).
- Actions d'alimentation : appui long de 1 s côté UI (`HoldButton`).
## État (2026-10-23)
Vérifié :
- Saisie de texte : 87 tests (dont rejeu des frappes dans un état xkb avec composition : ASCII sur us/fr/de, texte français, accents par touches mortes) ; dans Chromium, 19 vérifications (fenêtre non modale, Envoyer / Envoyer ↵, touches rapides, masquage, caractère impossible, téléphone sans débordement) et rejeu des touches enregistrées : `Bonjour, ça va ? @ 12 € ñ` redonne exactement ce texte sur AZERTY latin9. Frappes réelles via uinput non essayées (elles iraient dans le vrai bureau).
- pyright : 0 erreur ; 59 tests unitaires OK (dont une vraie poignée de main TLS avec la CA locale, le stockage SQLite, la validation, l'API REST via `aiohttp.test_utils`).
- **UI dans un vrai Chromium** (headless, piloté par le protocole DevTools, serveur isolé) : télécommande + `/admin`, 28 vérifications : barre de 5 onglets (aussi à 360 px, sans débordement), onglet Système réduit aux opérations de session, création web/app, édition d'une commande importée (zone verrouillée), réordonnancement, suppression, bascule de langue, jeton absent/refusé, mise à jour en direct de la grille par WebSocket, et **lancements réels** des trois types (navigateur factice, `.desktop` via `gio`, commande). Aucune erreur JavaScript.
- HTTPS de bout en bout avec le vrai serveur (config isolée) : `/` avec la CA, rejet sans CA (curl 60), `/ca.crt`, `/ws` 401 sans jeton, WebSocket `wss://` avec jeton.
- Intégration avec `dbus-run-session` et un faux lecteur MPRIS (dbus-next ServiceInterface) : état, métadonnées, `/art` avec et sans jeton, play_pause, set_volume, seek, erreurs, refus 401, disparition du lecteur.
**Non vérifié sur une vraie machine :**
- rendu de l'UI dans un navigateur ;
- installation de la CA sur Android et chargement de la page en HTTPS sur la tablette ;
- pactl, uinput, logind et ScreenSaver.Lock ;
- service systemd et règle udev.
## Prochaines étapes envisagées
1. Test réel sur le PC multimédia et la tablette ; ajuster les gestes du pavé (gain, seuils dans `Touchpad`).
2. ~~HTTPS avec un certificat local~~ — fait (`make cert`, voir `tls.py`) ; reste à tester sur la tablette (installation de la CA, Wake Lock, PWA).
3. Essayer la saisie de texte sur la tablette réelle et dans les applications visées (champ de recherche du navigateur, connexion à un service), puis sous Wayland.
4. Test d'intégration versionné : déplacer le scénario `dbus-run-session` + faux lecteur dans `tests/` (cible `make test-integration`).
5. Versionner le test d'interface dans `tests/` (cible `make test-ui`) : pilote DevTools (Node, WebSocket natif) + Chromium headless + serveur isolé (`XDG_CONFIG_HOME`, `XDG_DATA_HOME`, faux `chromium` dans le `PATH`, faux `.desktop`), aujourd'hui seulement joué à la main.
6. Liste de lecture / file d'attente (`org.mpris.MediaPlayer2.TrackList`, si exposée par le lecteur).
7. Raccourcis KDE via D-Bus (`org.kde.kglobalaccel`) ou `kscreen-doctor` pour la sortie vidéo.
8. Éventuellement : documentation mkdocs fr/en si le projet grossit.
## Pièges
- Un VPN actif sur l'appareil client (Proton VPN sur le Pixel 8a de l'utilisateur) bloque le LAN : la page expire (ERR_CONNECTION_TIMED_OUT) alors que le serveur répond correctement depuis le PC. Réglage Proton : Paramètres → Connexion → Paramètres avancés → Connexions LAN ; vérifier aussi « Bloquer les connexions sans VPN » dans les réglages VPN d'Android.
- Android : les apps visant l'API 24+ (WebView système, donc probablement DuckDuckGo) ignorent les CA utilisateur sauf opt-in ; les navigateurs Chromium autonomes (Chrome, Brave, Vanadium) les respectent, Firefox demande un réglage caché. Non vérifié sur la tablette de l'utilisateur (DuckDuckGo a de plus traité `https://192.168.1.104:8765/ca.crt` saisi à la main comme une recherche).
- Passer en HTTPS change l'origine : le jeton mémorisé (localStorage) et une PWA installée en `http://` ne servent plus, la tablette doit rescanner le QR code. Le port ne répond plus qu'en TLS.
- Si `tls_cert` pointe vers un fichier absent, `--check` et le démarrage échouent (`make cert` le recrée : il passe avant la validation TLS). Après un changement de nom de machine, le garde-fou `openssl verify` de `make cert` signale que la CA existante ne couvre plus ce nom : supprimer `~/.config/mediadeck/tls/`.
- Les lanceurs vivent dans la base : modifier `[[launchers]]` dans `config.toml` après le premier démarrage n'a aucun effet (le journal l'indique). Pour réimporter : supprimer `~/.local/share/mediadeck/launchers.db`. Avec `admin.enabled = false`, seule la base (`sqlite3`) permet encore de les modifier.
- Les lanceurs importés sont de type `command` : ils restent renommables sans `allow_custom_command`, mais leur commande n'est modifiable qu'avec lui. Pour s'en passer, les recréer en `web`/`app` depuis `/admin`.
- Les applications installées sont lancées par `gio launch` (paquet `libglib2.0-bin`, ajouté à `make deps`) ; la liste vient des `.desktop` de `XDG_DATA_DIRS` + exports Flatpak : un service systemd utilisateur sans `XDG_DATA_DIRS` retombe sur `/usr/local/share:/usr/share`.
- Saisie de texte : Verr. Maj du PC non détecté (majuscules inversées s'il est actif) ; un moteur de saisie (fcitx/ibus) peut altérer le résultat ; la composition des touches mortes dépend de l'application (vérifiée par simulation xkb avec la table de composition `en_US.UTF-8`, pas dans chaque application). Testé en session X11 ; Wayland utilise les mêmes sources (kxkbrc) mais n'a pas été essayé.
- Chromium déjà ouvert : un lanceur `web` peut s'ouvrir dans la fenêtre existante (le plein écran n'est alors pas garanti).
- `make url` détecte l'IP via la route par défaut : avec un VPN actif (WireGuard), il annonce l'IP du VPN. Renseigner `server.advertise_host` dans `config.toml` pour forcer l'adresse du QR code.
- `firefox --kiosk` (et `chromium --kiosk`) ignore F11 : impossible de quitter le plein écran depuis la télécommande. Le lanceur YouTube TV utilise `chromium --start-fullscreen`, que F11 permet de quitter.
- Lancé hors session graphique (ssh, cron), il n'y a pas de bus de session : MPRIS et système sont désactivés (log d'erreur) mais le serveur démarre quand même.
- `/dev/uinput` nécessite `modprobe uinput` et une reconnexion de session après `make uinput` ; vérifier avec `getfacl /dev/uinput`.
- Les navigateurs exposent souvent MPRIS sans `Volume` / `Shuffle` / `LoopStatus` : l'UI masque ces contrôles quand la valeur est `null`.
- La position MPRIS n'est pas signalée par `PropertiesChanged` : elle est relue explicitement (`refresh_position`).
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Denis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+118
View File
@@ -0,0 +1,118 @@
# MediaDeck : opérations d'installation et d'exploitation (Debian / LMDE)
# Note : les recettes make exigent des tabulations (exception à la règle des 4 espaces).
SHELL := /bin/bash
PROJECT_DIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
VENV := $(PROJECT_DIR)/.venv
PYTHON := $(VENV)/bin/python
CONFIG_DIR := $(or $(XDG_CONFIG_HOME),$(HOME)/.config)/mediadeck
CONFIG := $(CONFIG_DIR)/config.toml
UNIT_DIR := $(or $(XDG_CONFIG_HOME),$(HOME)/.config)/systemd/user
UNIT := $(UNIT_DIR)/mediadeck.service
UDEV_RULE := /etc/udev/rules.d/60-mediadeck-uinput.rules
PORT ?= 8765
.DEFAULT_GOAL := help
.PHONY: help deps install config token url cert check run dev lint test uinput uinput-remove \
service-install service-uninstall status logs firewall clean distclean
help: ## Affiche cette aide
@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | \
awk 'BEGIN {FS = ":.*?## "}; {printf " \033[33m%-18s\033[0m %s\n", $$1, $$2}'
deps: ## Installe les paquets système (sudo)
sudo apt-get update
sudo apt-get install -y python3-venv python3-dev gcc linux-libc-dev \
pulseaudio-utils qrencode libglib2.0-bin libxkbcommon0 xkb-data
$(PYTHON):
python3 -m venv $(VENV)
$(PYTHON) -m pip install --upgrade pip
install: $(PYTHON) ## Crée le venv et installe le projet (+ outils de dev)
$(PYTHON) -m pip install -e '.[dev]'
config: ## Crée ~/.config/mediadeck/config.toml avec un jeton aléatoire (sans écraser)
@mkdir -p $(CONFIG_DIR) && chmod 700 $(CONFIG_DIR)
@if [ -e $(CONFIG) ]; then \
echo "$(CONFIG) existe déjà (make token pour changer le jeton)"; \
else \
umask 077 && cp config.example.toml $(CONFIG) && $(MAKE) --no-print-directory token; \
echo "Configuration créée : $(CONFIG)"; \
fi
token: ## Régénère le jeton d'accès (les tablettes devront rescanner le QR)
@umask 077 && python3 -c 'import re, secrets, pathlib; \
p = pathlib.Path("$(CONFIG)"); \
t = p.read_text(); \
n = re.sub(r"(?m)^token\s*=.*$$", "token = \"" + secrets.token_urlsafe(32) + "\"", t, count=1); \
p.write_text(n); p.chmod(0o600)'
@echo "Nouveau jeton écrit dans $(CONFIG)"
url: $(PYTHON) ## Affiche l'URL tablette et son QR code
@$(PYTHON) -m mediadeck --url
cert: $(PYTHON) ## Crée la CA locale + le certificat HTTPS et active HTTPS (openssl)
@$(PYTHON) -m mediadeck --make-cert
check: $(PYTHON) ## Valide la configuration
$(PYTHON) -m mediadeck --check
run: $(PYTHON) ## Lance le serveur au premier plan
$(PYTHON) -m mediadeck
dev: $(PYTHON) ## Lance le serveur en mode verbeux
$(PYTHON) -m mediadeck -v
lint: $(PYTHON) ## Vérification de types (pyright)
$(VENV)/bin/pyright
test: $(PYTHON) ## Tests unitaires
$(PYTHON) -m unittest discover -s tests -v
uinput: ## Autorise /dev/uinput pour la session active (sudo, règle udev uaccess)
sudo install -m 644 udev/60-mediadeck-uinput.rules $(UDEV_RULE)
sudo modprobe uinput
echo uinput | sudo tee /etc/modules-load.d/mediadeck-uinput.conf > /dev/null
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=uinput
@getfacl /dev/uinput 2>/dev/null | grep -q "user:$(USER)" && echo "OK : accès uinput accordé" \
|| echo "Vérifier : getfacl /dev/uinput (une reconnexion de session peut être nécessaire)"
uinput-remove: ## Retire la règle udev uinput (sudo)
sudo rm -f $(UDEV_RULE) /etc/modules-load.d/mediadeck-uinput.conf
sudo udevadm control --reload-rules
service-install: install ## Installe et démarre le service utilisateur systemd
@mkdir -p $(UNIT_DIR)
sed 's|@PROJECT_DIR@|$(PROJECT_DIR)|g' systemd/mediadeck.service.in > $(UNIT)
systemctl --user daemon-reload
systemctl --user enable --now mediadeck.service
@systemctl --user --no-pager status mediadeck.service | head -n 5
service-uninstall: ## Arrête et supprime le service utilisateur
-systemctl --user disable --now mediadeck.service
rm -f $(UNIT)
systemctl --user daemon-reload
status: ## État du service
systemctl --user --no-pager status mediadeck.service
logs: ## Journal du service (suivi)
journalctl --user -u mediadeck.service -f
firewall: ## Ouvre le port aux réseaux privés si ufw est actif (sudo)
@if command -v ufw > /dev/null; then \
for net in 192.168.0.0/16 10.0.0.0/8 172.16.0.0/12; do \
sudo ufw allow from $$net to any port $(PORT) proto tcp comment mediadeck; \
done; \
else \
echo "ufw absent : ouvrir le port $(PORT)/tcp pour le LAN uniquement"; \
fi
clean: ## Supprime les caches
find . -type d -name __pycache__ -prune -exec rm -rf {} +
rm -rf build dist *.egg-info .pyright
distclean: clean ## Supprime aussi le venv
rm -rf $(VENV)
+198
View File
@@ -0,0 +1,198 @@
# MediaDeck
Web remote for a Linux media PC, designed for an Android tablet sitting next to it.
The PC runs a small Python bridge; the tablet only needs a browser.
*Version française : [README.md](README.md)*
## Features
| Tab | Content | PC side |
|---|---|---|
| **Playing** | Cover art, title, progress, play/pause, next/previous, shuffle, repeat, player volume, player selection | MPRIS (session D-Bus): Elisa, VLC, mpv, Firefox, Chromium, Spotify, Kodi… |
| **Sound** | Master volume, mute, output selection (HDMI, Bluetooth…) and per-output volume | `pactl` (PipeWire or PulseAudio) |
| **Touchpad** | Touchpad (click, right click, 2-finger scroll), D-pad, Esc, Space, F, F11…, text entry with the tablet's keyboard | `/dev/uinput`: works on X11 **and** Wayland |
| **Launchers** | Configurable buttons: websites and installed applications (`/admin` page) | browser, `gio launch` |
| **System** | Lock, sleep, restart, shut down (1 s long press): sensitive operations, kept apart from launchers | logind, `org.freedesktop.ScreenSaver` |
State is pushed in real time over WebSocket (`PropertiesChanged`, `Seeked`, `pactl subscribe`); the playback position is interpolated on the tablet.
## Architecture
```
Tablet (fullscreen browser)
│ HTTP + WebSocket, access token
▼
mediadeck (aiohttp, systemd --user service)
├─ mpris.py → org.mpris.MediaPlayer2.* (session bus)
├─ audio.py → pactl list/set-sink-*, subscribe
├─ input.py → python-evdev / uinput (virtual keyboard + pointer)
├─ keymap.py / text.py → text entry following the PC's real keyboard layout (libxkbcommon)
└─ system.py → org.freedesktop.login1, ScreenSaver, launchers (SQLite database, /admin page)
```
KDE Connect is not required; it can stay installed for its other features.
## Installation (Debian / LMDE)
```bash
make deps # system packages (sudo): venv, gcc, pactl, qrencode
make install # .venv + Python dependencies
make config # ~/.config/mediadeck/config.toml (mode 600) with a random token
make uinput # "uaccess" udev rule for /dev/uinput (sudo)
make service-install # systemd user service, started with the graphical session
make url # URL + QR code to scan with the tablet
```
On the tablet: scan the QR code, then browser menu → "Add to Home screen".
The token is stored, then removed from the address bar.
The service must run **inside the graphical session**: it needs the user's session D-Bus and audio server.
## Configuration
`~/.config/mediadeck/config.toml` (see [config.example.toml](config.example.toml)):
```toml
[server]
host = "0.0.0.0"
port = 8765
token = "…" # make token to regenerate it
advertise_host = "192.168.1.104" # optional: address used in the QR code (auto-detected otherwise)
tls_cert = "~/.config/mediadeck/tls/server.pem" # written by `make cert` (HTTPS)
tls_key = "~/.config/mediadeck/tls/server.key"
tls_ca = "~/.config/mediadeck/tls/mediadeck-ca.crt" # served on /ca.crt for the tablet
[audio]
max_volume = 1.0 # cap applied to the tablet
[features]
input = true
power = true
text_input = false # virtual keyboard: read "Text entry" before enabling
[admin]
enabled = true # /admin page and launcher API
allow_custom_command = false # true: allow raw commands from /admin
# Imported once into the database at first start, then managed on /admin
[[launchers]]
id = "youtube"
label = "YouTube TV"
icon = "tv" # app, tv, film, globe, music, screen-off, speaker, lock, window
command = ["chromium", "--start-fullscreen", "https://www.youtube.com/tv"]
```
Launcher commands are argv lists and are never passed to a shell.
## Launchers
The buttons of the **Launchers** tab are stored in a SQLite database (`~/.local/share/mediadeck/launchers.db`,
mode 600). The tab's **Manage** button opens the `/admin` page: add, edit, delete and reorder launchers.
Changes show up on the tablet immediately.
| Type | Definition | What the client can write |
|---|---|---|
| **Website** | http(s) URL, browser (Chromium, Chrome, Brave, Firefox), fullscreen | a URL |
| **Installed application** | picked from the list of `.desktop` files, started with `gio launch` | nothing (pick from a list) |
| **Command** | raw argument list | anything: disabled by default |
- **Security**: the API requires the token in the `Authorization: Bearer` header (never in the URL). A command
runs with your rights: unless `allow_custom_command = true` is set in the `[admin]` section of `config.toml`,
creating or changing a command is refused (403). An existing command can still be renamed.
- **Migration**: at first start, the `[[launchers]]` of `config.toml` are imported once (command type). They are
ignored afterwards and can be removed from the file. To import them again, delete the database.
- `enabled = false` turns off the page and the API; existing launchers keep working.
- There is no automatic fullscreen with Firefox, whose kiosk mode ignores F11.
- `gio` (package `libglib2.0-bin`, installed by `make deps`) starts installed applications.
## Text entry
The **Keyboard** button of the Touchpad tab opens an entry window. You type with the tablet's own keyboard (accents,
correction, voice dictation), then **Send** or **Send ↵** types the text into the PC's active window. Tab, Backspace
and Enter sit next to the field. The window is not modal: the touchpad stays usable (click into a field on the PC,
then type). **Hide text** shows dots, for a password.
Each character is translated into key presses following the PC keyboard's **real** layout (AZERTY, QWERTY…), read from
KDE's configuration (`~/.config/kxkbrc`, otherwise `setxkbmap -query`, the active layout coming from D-Bus), using
libxkbcommon. Shift, AltGr and dead keys (ê, ñ…) are handled; keys go through uinput like a real keyboard's.
**The clipboard is not used**: nothing stays in Klipper's history, passwords included.
- **Off by default**: set `[features] text_input = true` to enable it. It is a full keyboard: with the token, someone
can open a terminal (Super key) and type commands. Enable it only if that is acceptable.
- 500 characters per send (WebSocket message size limit).
- A character missing from the layout (→, emoji…) is skipped, the rest is typed and an error reports it. Typographic
apostrophes, quotes, "…" and dashes are replaced by their ASCII equivalent.
- The PC's Caps Lock state is not detected: if it is on, capitals are inverted.
- Accented letters made with dead keys rely on the application's compose handling (checked with an xkb simulation, not
in every application). An input method running on the PC (fcitx, ibus) may change the result.
- Needs libxkbcommon and the xkb data (packages `libxkbcommon0` and `xkb-data`, installed by `make deps`).
## Local HTTPS
Some mobile browsers require HTTPS, and so do the Wake Lock API and a proper PWA install.
MediaDeck creates its own local certificate authority (CA) with `openssl`:
```bash
make cert # CA + server certificate, enables HTTPS in config.toml
systemctl --user restart mediadeck # or rerun `make dev`
```
On the tablet, **once**:
1. Open `https://<ip>:8765/ca.crt` (address and QR code printed by `make cert`) and accept the certificate
warning: the file `mediadeck-ca.crt` is downloaded.
2. Settings → Security → Encryption & credentials → Install a certificate → **CA certificate**, then pick that
file (the exact path depends on the Android version).
3. Rescan the QR code from `make url`: the address now starts with `https://`, so the token remembered for the
old `http://` address is no longer used.
Notes:
- The port now speaks HTTPS only: a plain `http://` request to it fails.
- The CA can only sign private addresses (10/8, 172.16/12, 192.168/16, 127/8) and the names `localhost`,
`*.local`, `*.lan` and the machine's own name (`nameConstraints`). Its key `ca.key` stays on the PC (mode 600):
never copy it.
- The server certificate is valid for 825 days. `make cert` reissues it without changing the CA, so nothing
needs redoing on the tablet. If the PC's address changes, fix `advertise_host` and rerun `make cert`.
- Tablet browser: use a standalone Chromium browser (Chrome, Brave, Vivaldi, Vanadium…), which trusts
user-installed CAs. Browsers built on the system WebView (DuckDuckGo…) may ignore them, and Firefox for Android
needs a hidden setting: not verified for this project. Only installing the CA is system-wide; `/ca.crt` can be
downloaded from any browser.
- To start over (new CA, to be reinstalled on the tablet): delete `~/.config/mediadeck/tls/` and the three
`tls_*` lines from `config.toml`, then run `make cert`.
## Make targets
| Target | Purpose |
|---|---|
| `make run` / `make dev` | run in the foreground (normal / verbose) |
| `make check` | validate the configuration |
| `make token` | regenerate the token (tablets must rescan) |
| `make cert` | create the local CA and HTTPS certificate, enable HTTPS |
| `make status` / `make logs` | service status and journal |
| `make firewall` | open the port to private networks with ufw |
| `make lint` / `make test` | pyright / unit tests |
| `make service-uninstall`, `make uinput-remove`, `make distclean` | uninstall |
## Security
- `/ws` and `/art` require the token (constant-time comparison); only the HTML page is public.
- The config file is rejected if it is readable by group or others.
- `/art` only serves the `file://` cover of the requested player, and only images under 10 MB.
- The launcher API `/api/*` requires the token in the `Authorization` header (no CSRF possible from another site); raw commands are refused there unless `allow_custom_command = true` is set in the config file.
- WebSocket messages are capped at 4 KB; mouse moves and scrolls are bounded.
- uinput access is granted through a logind ACL (`uaccess`) to the active session user, not through the `input` group, which would allow reading every keyboard.
- Without `make cert`, traffic is plain HTTP and meant for the LAN only. With HTTPS it is encrypted, but the port must still not be exposed outside the LAN: for remote access, go through WireGuard.
## Known limitations
- **Screen always on**: the Wake Lock API requires HTTPS (see "Local HTTPS"). Over HTTP, adjust the tablet's sleep setting or use a kiosk browser (Fully Kiosk Browser…).
- **VPN on the tablet**: an active VPN on the client device cuts off the local network, and the page times out ("site can't be reached, took too long to respond"). Allow LAN connections in the VPN app (Proton VPN: Settings → Connection → Advanced settings → LAN connections), turn off Android's lockdown / kill switch, or disconnect the VPN.
- **Text entry**: see its section; off by default, and limited to the characters the PC keyboard layout can produce.
- **Lock / power**: depend on polkit rules. An active local session is allowed by default on Debian.
- Some players (browsers especially) expose no volume, shuffle or repeat: the matching controls are then hidden.
## License
MIT
+198
View File
@@ -0,0 +1,198 @@
# MediaDeck
Télécommande web pour un PC multimédia Linux, pensée pour une tablette Android posée à côté.
Le PC exécute un petit pont Python ; la tablette n'a besoin que d'un navigateur.
*English version: [README-EN.md](README-EN.md)*
## Fonctions
| Onglet | Contenu | Côté PC |
|---|---|---|
| **Lecture** | Pochette, titre, progression, lecture/pause, suivant/précédent, aléatoire, répétition, volume du lecteur, choix du lecteur | MPRIS (D-Bus de session) : Elisa, VLC, mpv, Firefox, Chromium, Spotify, Kodi… |
| **Son** | Volume principal, sourdine, choix de la sortie (HDMI, Bluetooth…) et volume par sortie | `pactl` (PipeWire ou PulseAudio) |
| **Pavé** | Pavé tactile (clic, clic droit, défilement 2 doigts), croix directionnelle, Échap, Espace, F, F11…, saisie de texte avec le clavier de la tablette | `/dev/uinput` : fonctionne sous X11 **et** Wayland |
| **Lanceurs** | Boutons configurables : sites web et applications installées (page `/admin`) | navigateur, `gio launch` |
| **Système** | Verrouillage, veille, redémarrage, extinction (appui long 1 s) : opérations délicates, séparées des lanceurs | logind, `org.freedesktop.ScreenSaver` |
L'état est poussé en temps réel par WebSocket (signaux `PropertiesChanged`, `Seeked`, `pactl subscribe`) ; la position de lecture est interpolée côté tablette.
## Architecture
```
Tablette (navigateur plein écran)
│ HTTP + WebSocket, jeton d'accès
▼
mediadeck (aiohttp, service systemd --user)
├─ mpris.py → org.mpris.MediaPlayer2.* (bus de session)
├─ audio.py → pactl list/set-sink-*, subscribe
├─ input.py → python-evdev / uinput (clavier + pointeur virtuels)
├─ keymap.py / text.py → saisie de texte selon la disposition réelle du clavier (libxkbcommon)
└─ system.py → org.freedesktop.login1, ScreenSaver, lanceurs (base SQLite, page /admin)
```
KDE Connect n'est pas nécessaire : il peut rester installé pour ses autres fonctions.
## Installation (Debian / LMDE)
```bash
make deps # paquets système (sudo) : venv, gcc, pactl, qrencode
make install # .venv + dépendances Python
make config # ~/.config/mediadeck/config.toml (mode 600) avec un jeton aléatoire
make uinput # règle udev « uaccess » pour /dev/uinput (sudo)
make service-install # service systemd utilisateur, démarré avec la session graphique
make url # URL + QR code à scanner avec la tablette
```
Sur la tablette : scanner le QR code, puis menu du navigateur → « Ajouter à l'écran d'accueil ».
Le jeton est mémorisé puis retiré de la barre d'adresse.
Le service doit tourner **dans la session graphique** : il a besoin du bus D-Bus de session et du serveur audio de l'utilisateur.
## Configuration
`~/.config/mediadeck/config.toml` (voir [config.example.toml](config.example.toml)) :
```toml
[server]
host = "0.0.0.0"
port = 8765
token = "…" # make token pour le régénérer
advertise_host = "192.168.1.104" # optionnel : adresse du QR code (sinon détection automatique)
tls_cert = "~/.config/mediadeck/tls/server.pem" # écrits par `make cert` (HTTPS)
tls_key = "~/.config/mediadeck/tls/server.key"
tls_ca = "~/.config/mediadeck/tls/mediadeck-ca.crt" # servi sur /ca.crt pour la tablette
[audio]
max_volume = 1.0 # plafond depuis la tablette
[features]
input = true
power = true
text_input = false # clavier virtuel : voir « Saisie de texte » avant d'activer
[admin]
enabled = true # page /admin et API des lanceurs
allow_custom_command = false # true : autoriser les commandes brutes depuis /admin
# Importés une seule fois dans la base au premier démarrage, puis gérés sur /admin
[[launchers]]
id = "youtube"
label = "YouTube TV"
icon = "tv" # app, tv, film, globe, music, screen-off, speaker, lock, window
command = ["chromium", "--start-fullscreen", "https://www.youtube.com/tv"]
```
Les commandes des lanceurs sont des listes argv, jamais passées à un shell.
## Lanceurs
Les boutons de l'onglet **Lanceurs** sont stockés dans une base SQLite (`~/.local/share/mediadeck/launchers.db`,
mode 600). Le bouton **Gérer** de l'onglet ouvre la page `/admin` : ajouter, modifier, supprimer et réordonner
les lanceurs. Les changements apparaissent aussitôt sur la tablette.
| Type | Définition | Ce que le client peut écrire |
|---|---|---|
| **Site web** | URL http(s), navigateur (Chromium, Chrome, Brave, Firefox), plein écran | une URL |
| **Application installée** | choisie dans la liste des fichiers `.desktop`, lancée avec `gio launch` | rien (choix dans une liste) |
| **Commande** | liste d'arguments brute | tout : désactivé par défaut |
- **Sécurité** : l'API exige le jeton dans l'en-tête `Authorization: Bearer` (jamais dans l'URL). Une commande
s'exécute avec vos droits : tant que `allow_custom_command = true` n'est pas dans la section `[admin]` de
`config.toml`, créer ou modifier une commande est refusé (403). Une commande existante reste renommable.
- **Migration** : au premier démarrage, les `[[launchers]]` de `config.toml` sont importés une seule fois (type
commande). Ils sont ensuite ignorés et peuvent être supprimés du fichier. Pour tout réimporter, supprimer la base.
- `enabled = false` désactive la page et l'API ; les lanceurs existants continuent de fonctionner.
- Le plein écran automatique n'existe pas avec Firefox, dont le mode kiosque ignore F11.
- `gio` (paquet `libglib2.0-bin`, installé par `make deps`) lance les applications installées.
## Saisie de texte
Le bouton **Clavier** de l'onglet Pavé ouvre une fenêtre de saisie. On tape avec le clavier de la tablette
(accents, correction, dictée vocale), puis **Envoyer** ou **Envoyer ↵** tape le texte dans la fenêtre active du PC.
Tab, Effacer et Entrée sont à côté du champ. La fenêtre n'est pas modale : le pavé tactile reste utilisable (cliquer
dans un champ du PC, puis taper). **Masquer le texte** affiche des points, pour un mot de passe.
Chaque caractère est traduit en touches selon la disposition **réelle** du clavier du PC (AZERTY, QWERTY…), lue dans
la configuration de KDE (`~/.config/kxkbrc`, sinon `setxkbmap -query`, la disposition active venant de D-Bus), avec
libxkbcommon. Maj, AltGr et touches mortes (ê, ñ…) sont gérés ; les touches partent par uinput comme celles d'un vrai
clavier. **Le presse-papiers n'est pas utilisé** : rien ne reste dans l'historique de Klipper, mots de passe compris.
- **Désactivée par défaut** : `[features] text_input = true` pour l'activer. C'est un clavier complet : avec le jeton,
on peut ouvrir un terminal (touche Super) et y taper des commandes. Ne l'activez que si cela vous convient.
- 500 caractères par envoi (limite de taille d'un message WebSocket).
- Un caractère absent de la disposition (→, emoji…) est ignoré, le reste est tapé et une erreur le signale. Les
apostrophes, guillemets, « … » et tirets typographiques sont remplacés par leur équivalent ASCII.
- L'état de Verr. Maj du PC n'est pas détecté : s'il est actif, les majuscules sont inversées.
- Les lettres accentuées par touche morte dépendent de la composition gérée par l'application (vérifié en simulation
xkb, pas dans chaque application). Un moteur de saisie actif sur le PC (fcitx, ibus) peut modifier le résultat.
- Dépend de libxkbcommon et des données xkb (paquets `libxkbcommon0` et `xkb-data`, installés par `make deps`).
## HTTPS local
Certains navigateurs mobiles exigent HTTPS, de même que l'API Wake Lock et l'installation propre en PWA.
MediaDeck crée sa propre autorité de certification (CA) locale avec `openssl` :
```bash
make cert # CA + certificat serveur, active HTTPS dans config.toml
systemctl --user restart mediadeck # ou relancer `make dev`
```
Sur la tablette, **une seule fois** :
1. Ouvrir `https://<ip>:8765/ca.crt` (adresse et QR code affichés par `make cert`) et accepter l'avertissement
de certificat : le fichier `mediadeck-ca.crt` est téléchargé.
2. Réglages → Sécurité → Chiffrement et identifiants → Installer un certificat → **Certificat d'autorité**,
puis choisir ce fichier (le chemin exact varie selon la version d'Android).
3. Rescanner le QR code de `make url` : l'adresse est maintenant en `https://`, donc le jeton mémorisé pour
l'ancienne adresse `http://` ne sert plus.
Notes :
- Le port ne parle plus que HTTPS : une requête `http://` sur ce port échoue.
- La CA ne peut signer que des adresses privées (10/8, 172.16/12, 192.168/16, 127/8) et les noms `localhost`,
`*.local`, `*.lan` et celui de la machine (`nameConstraints`). Sa clé `ca.key` reste sur le PC (mode 600) :
ne pas la copier.
- Le certificat serveur est valable 825 jours. `make cert` le réémet sans changer la CA : rien à refaire sur
la tablette. Si l'adresse du PC change, corriger `advertise_host` puis relancer `make cert`.
- Navigateur de la tablette : prendre un navigateur Chromium autonome (Chrome, Brave, Vivaldi, Vanadium…), qui fait
confiance aux CA installées par l'utilisateur. Les navigateurs fondés sur le WebView système (DuckDuckGo…) peuvent
les ignorer, et Firefox pour Android exige un réglage caché : non vérifié sur ce projet. Seule l'installation de
la CA est globale ; le téléchargement de `/ca.crt` peut se faire depuis n'importe quel navigateur.
- Pour tout recommencer (nouvelle CA, à réinstaller sur la tablette) : supprimer `~/.config/mediadeck/tls/` et les
trois lignes `tls_*` de `config.toml`, puis `make cert`.
## Commandes make
| Cible | Rôle |
|---|---|
| `make run` / `make dev` | lancer au premier plan (normal / verbeux) |
| `make check` | valider la configuration |
| `make token` | régénérer le jeton (les tablettes devront rescanner) |
| `make cert` | créer la CA locale et le certificat HTTPS, activer HTTPS |
| `make status` / `make logs` | état et journal du service |
| `make firewall` | ouvrir le port aux réseaux privés avec ufw |
| `make lint` / `make test` | pyright / tests unitaires |
| `make service-uninstall`, `make uinput-remove`, `make distclean` | désinstallation |
## Sécurité
- `/ws` et `/art` exigent le jeton (comparaison à temps constant) ; la page HTML seule est publique.
- Le fichier de configuration est refusé s'il est lisible par le groupe ou les autres.
- `/art` ne sert que la pochette `file://` du lecteur demandé, et uniquement des images de moins de 10 Mo.
- L'API `/api/*` des lanceurs exige le jeton en en-tête `Authorization` (pas de CSRF possible depuis un autre site) ; les commandes brutes y sont interdites sauf `allow_custom_command = true` dans le fichier de configuration.
- Les messages WebSocket sont limités à 4 Ko ; les déplacements souris et défilements sont bornés.
- uinput est autorisé par ACL logind (`uaccess`) pour l'utilisateur de la session active, et non par le groupe `input`, qui donnerait accès en lecture à tous les claviers.
- Sans `make cert`, le trafic est en HTTP clair : réservé au LAN. Avec HTTPS, il est chiffré, mais le port ne doit toujours pas être exposé hors du LAN : pour un accès distant, passer par WireGuard.
## Limites connues
- **Écran toujours allumé** : l'API Wake Lock exige HTTPS (voir « HTTPS local »). En HTTP, régler la mise en veille de la tablette, ou utiliser un navigateur kiosque (Fully Kiosk Browser…).
- **VPN sur la tablette** : un VPN actif sur l'appareil client coupe l'accès au réseau local, et la page expire (« site inaccessible, trop de temps à répondre »). Autoriser les connexions LAN dans l'application VPN (Proton VPN : Paramètres → Connexion → Paramètres avancés → Connexions LAN), désactiver le « verrouillage » / kill switch d'Android, ou couper le VPN.
- **Saisie de texte** : voir la section dédiée ; désactivée par défaut, et limitée aux caractères que la disposition du clavier du PC permet de produire.
- **Verrouillage / extinction** : dépendent des règles polkit. Une session locale active est autorisée par défaut sur Debian.
- Certains lecteurs (navigateurs notamment) n'exposent ni volume, ni aléatoire, ni répétition : les contrôles correspondants sont alors masqués.
## Licence
MIT
+68
View File
@@ -0,0 +1,68 @@
# Configuration MediaDeck : copiée vers ~/.config/mediadeck/config.toml par `make config`.
# Ce fichier contient le jeton d'accès : il doit rester en mode 600.
[server]
# 0.0.0.0 = toutes les interfaces ; préférer l'IP LAN du PC si possible
host = "0.0.0.0"
port = 8765
# Adresse affichée dans l'URL et le QR code (`make url`) ; à renseigner si la détection
# automatique choisit une mauvaise interface (VPN, Docker…). Nom d'hôte ou IPv4.
# advertise_host = "192.168.1.104"
# HTTPS : `make cert` crée une CA locale + un certificat et renseigne ces trois lignes.
# La tablette doit installer la CA une fois (https://<ip>:<port>/ca.crt).
# tls_cert = "~/.config/mediadeck/tls/server.pem"
# tls_key = "~/.config/mediadeck/tls/server.key"
# tls_ca = "~/.config/mediadeck/tls/mediadeck-ca.crt"
# Généré par `make config` / `make token` (32 octets aléatoires, URL-safe)
token = "CHANGE_ME"
[audio]
# Volume maximal autorisé depuis la tablette (1.0 = 100 %, jusqu'à 1.5)
max_volume = 1.0
[features]
# Clavier/souris virtuels via /dev/uinput (nécessite `make uinput`)
input = true
# Veille / redémarrage / extinction via logind
power = true
# Saisie de texte depuis la tablette (clavier virtuel, `make uinput` requis). Désactivée par défaut : c'est un
# clavier complet, donc un contrôle total du PC pour quiconque possède le jeton (ouvrir un terminal, taper...).
text_input = false
[admin]
# Page /admin (bouton « Gérer » de l'onglet Lanceurs) et API REST des lanceurs
enabled = true
# Autorise la création/modification de commandes brutes depuis /admin. Une commande s'exécute avec vos
# droits : tant que c'est false, /admin ne propose que des sites web et des applications installées.
allow_custom_command = false
# Lanceurs : IMPORTÉS UNE SEULE FOIS dans la base (~/.local/share/mediadeck/launchers.db) au premier
# démarrage, puis gérés sur /admin ; cette section est ensuite ignorée et peut être supprimée.
# Commande en liste argv, jamais interprétée par un shell.
# Icônes disponibles : app, tv, film, globe, music, screen-off, speaker, lock, window
# Plein écran sans verrou : F11 (bouton de la télécommande) en sort. `firefox --kiosk` est à éviter,
# car le mode kiosque ignore F11.
[[launchers]]
id = "youtube"
label = "YouTube TV"
icon = "tv"
command = ["chromium", "--start-fullscreen", "https://www.youtube.com/tv"]
[[launchers]]
id = "vlc"
label = "VLC"
icon = "film"
command = ["vlc"]
[[launchers]]
id = "elisa"
label = "Elisa"
icon = "music"
command = ["elisa"]
[[launchers]]
id = "screen-off"
label = "Écran off"
icon = "screen-off"
command = ["kscreen-doctor", "--dpms", "off"]
+3
View File
@@ -0,0 +1,3 @@
"""MediaDeck : télécommande web pour PC multimédia Linux (MPRIS, PipeWire, uinput, logind)."""
__version__ = "0.1.0"
+119
View File
@@ -0,0 +1,119 @@
"""Point d'entrée : python -m mediadeck [--config PATH] [--check | --url | --make-cert]."""
from __future__ import annotations
import argparse
import logging
import shutil
import socket
import subprocess
import sys
from pathlib import Path
from aiohttp import web
from .config import CONFIG_PATH, Config, ConfigError, load_config
from .tls import TLS_DIR, build_ssl_context, default_hosts, enable_tls, generate_certificates
def lan_address() -> str:
"""Adresse IP locale utilisée pour sortir (aucun paquet n'est émis en UDP connect)."""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
try:
sock.connect(("192.0.2.1", 9))
return sock.getsockname()[0]
except OSError:
return "127.0.0.1"
def advertised_host(config: Config) -> str:
# advertise_host prime : la route par défaut peut passer par un VPN (wg0…) et non par le LAN
return config.advertise_host or (lan_address() if config.host in ("0.0.0.0", "") else config.host)
def base_url(config: Config) -> str:
scheme = "https" if config.tls_enabled else "http"
return f"{scheme}://{advertised_host(config)}:{config.port}"
def client_url(config: Config) -> str:
return f"{base_url(config)}/?token={config.token}"
def print_qr(url: str) -> None:
# flush : qrencode écrit directement sur la même sortie, l'ordre doit rester URL puis QR code
print(url, flush=True)
# QR code dans le terminal si qrencode est installé
qrencode = shutil.which("qrencode")
if qrencode:
subprocess.run([qrencode, "-t", "ansiutf8", url], check=False)
else:
print("(apt install qrencode to display a QR code)", file=sys.stderr)
def print_url(config: Config) -> None:
print_qr(client_url(config))
if config.tls_ca is not None:
print(f"CA certificate to install on the tablet (once): {base_url(config)}/ca.crt", file=sys.stderr)
def make_cert(config: Config, config_path: Path) -> None:
"""Génère la CA locale et le certificat serveur, puis active HTTPS dans la configuration."""
ca, cert, key = generate_certificates(TLS_DIR, default_hosts(advertised_host(config)))
print(f"CA certificate: {ca}\nserver certificate: {cert}")
if enable_tls(config_path, cert, key, ca):
print(f"HTTPS enabled in {config_path}; restart the service (systemctl --user restart mediadeck)")
else:
print(f"{config_path} already sets tls_cert; restart the service to use the new certificate")
ca_url = f"https://{advertised_host(config)}:{config.port}/ca.crt"
print("\nOn the tablet, open this address, accept the warning once, and install the downloaded CA:")
print_qr(ca_url)
def main() -> int:
parser = argparse.ArgumentParser(prog="mediadeck", description="Web remote for a Linux media PC")
parser.add_argument("--config", type=Path, default=CONFIG_PATH, help="TOML config file")
parser.add_argument("--check", action="store_true", help="validate the config and exit")
parser.add_argument("--url", action="store_true", help="print the tablet URL (and QR code) and exit")
parser.add_argument("--make-cert", action="store_true", help="create the local CA and HTTPS certificate, then exit")
parser.add_argument("-v", "--verbose", action="store_true", help="debug logging")
args = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
try:
config = load_config(args.config)
except ConfigError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
try:
if args.make_cert:
make_cert(config, args.config)
return 0
ssl_context = build_ssl_context(config)
except ConfigError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
if args.check:
print(f"config OK: {args.config}" + (" (HTTPS)" if ssl_context else ""))
return 0
if args.url:
print_url(config)
return 0
# Import tardif : --check/--url ne nécessitent ni D-Bus ni evdev
from .server import MediaDeckServer
server = MediaDeckServer(config)
logging.getLogger(__name__).info("tablet URL: %s", client_url(config).split("?")[0])
web.run_app(server.build_app(), host=config.host, port=config.port, ssl_context=ssl_context, print=None)
return 0
if __name__ == "__main__":
sys.exit(main())
+160
View File
@@ -0,0 +1,160 @@
"""API REST d'administration des lanceurs (page /admin).
Authentification par ``Authorization: Bearer <jeton>`` : contrairement à un paramètre d'URL, un en-tête
personnalisé ne peut pas être ajouté par un site tiers (pas de CORS), ce qui exclut le CSRF.
"""
from __future__ import annotations
import hmac
import json
import logging
from collections.abc import Awaitable, Callable
from typing import Any
from aiohttp import web
from .config import Config
from .launchers import (
BROWSERS,
ICONS,
KINDS,
CommandNotAllowed,
LauncherError,
LauncherNotFound,
LauncherStore,
list_desktop_apps,
validate,
)
log = logging.getLogger(__name__)
MAX_BODY_BYTES = 16 * 1024
Handler = Callable[["AdminApi", web.Request], Awaitable[web.StreamResponse]]
def _json(data: Any, status: int = 200) -> web.Response:
return web.json_response(data, status=status, headers={"Cache-Control": "no-store"})
def _error(status: int, message: str) -> web.Response:
return _json({"error": message}, status)
def _api(handler: Handler) -> Callable[["AdminApi", web.Request], Awaitable[web.StreamResponse]]:
"""Décorateur : authentification puis traduction des erreurs métier en réponses JSON."""
async def wrapper(self: AdminApi, request: web.Request) -> web.StreamResponse:
if not self.authorized(request):
return _error(401, "invalid or missing token")
try:
return await handler(self, request)
except CommandNotAllowed as exc:
return _error(403, str(exc))
except LauncherNotFound as exc:
return _error(404, str(exc))
except LauncherError as exc:
return _error(400, str(exc))
return wrapper
class AdminApi:
def __init__(self, config: Config, store: LauncherStore, on_change: Callable[[], None]) -> None:
self._config = config
self._store = store
self._on_change = on_change
def add_routes(self, app: web.Application) -> None:
app.router.add_get("/api/launchers", self.list_launchers)
app.router.add_post("/api/launchers", self.create)
app.router.add_post("/api/launchers/reorder", self.reorder)
app.router.add_put("/api/launchers/{id}", self.update)
app.router.add_delete("/api/launchers/{id}", self.delete)
app.router.add_get("/api/apps", self.apps)
def authorized(self, request: web.Request) -> bool:
header = request.headers.get("Authorization", "")
scheme, _, token = header.partition(" ")
if scheme.lower() != "bearer":
return False
return hmac.compare_digest(token.strip().encode(), self._config.token.encode())
@staticmethod
async def _body(request: web.Request) -> Any:
raw = await request.content.read(MAX_BODY_BYTES + 1)
if len(raw) > MAX_BODY_BYTES:
raise LauncherError("request body too large")
try:
return json.loads(raw)
except ValueError as exc:
raise LauncherError("invalid JSON") from exc
def _changed(self) -> None:
self._on_change()
@_api
async def list_launchers(self, _request: web.Request) -> web.StreamResponse:
return _json(
{
"launchers": [entry.to_dict() for entry in self._store.list()],
"icons": list(ICONS),
"kinds": list(KINDS),
"browsers": [
{
"id": browser.id,
"name": browser.name,
"installed": browser.installed,
"fullscreen": browser.fullscreen_args is not None,
}
for browser in BROWSERS
],
"allow_command": self._config.allow_custom_command,
}
)
@_api
async def apps(self, _request: web.Request) -> web.StreamResponse:
return _json([{"id": app.id, "name": app.name} for app in list_desktop_apps()])
@_api
async def create(self, request: web.Request) -> web.StreamResponse:
label, icon, kind, spec = validate(
await self._body(request), allow_command=self._config.allow_custom_command
)
entry = self._store.create(label, icon, kind, spec)
log.info("launcher created: %s (%s)", entry.id, entry.kind)
self._changed()
return _json(entry.to_dict(), 201)
@_api
async def update(self, request: web.Request) -> web.StreamResponse:
current = self._store.get(request.match_info["id"])
if current is None:
raise LauncherNotFound("unknown launcher")
label, icon, kind, spec = validate(
await self._body(request), allow_command=self._config.allow_custom_command, current=current
)
entry = self._store.update(current.id, label, icon, kind, spec)
log.info("launcher updated: %s (%s)", entry.id, entry.kind)
self._changed()
return _json(entry.to_dict())
@_api
async def delete(self, request: web.Request) -> web.StreamResponse:
launcher_id = request.match_info["id"]
self._store.delete(launcher_id)
log.info("launcher deleted: %s", launcher_id)
self._changed()
return web.Response(status=204, headers={"Cache-Control": "no-store"})
@_api
async def reorder(self, request: web.Request) -> web.StreamResponse:
body = await self._body(request)
ids = body.get("ids") if isinstance(body, dict) else None
if not isinstance(ids, list) or not all(isinstance(item, str) for item in ids):
raise LauncherError("ids must be a list of launcher ids")
self._store.reorder(ids)
self._changed()
return web.Response(status=204, headers={"Cache-Control": "no-store"})
+150
View File
@@ -0,0 +1,150 @@
"""Volume et sorties audio via pactl (compatible PipeWire / pipewire-pulse)."""
from __future__ import annotations
import asyncio
import json
import logging
import shutil
from collections.abc import Callable
from typing import Any
log = logging.getLogger(__name__)
def parse_sinks(raw_json: str) -> list[dict[str, Any]]:
"""Extrait nom, description, volume moyen (0..1+) et mute de `pactl -f json list sinks`."""
sinks: list[dict[str, Any]] = []
for sink in json.loads(raw_json):
channels = sink.get("volume", {})
percents: list[float] = []
for channel in channels.values():
text = str(channel.get("value_percent", "0%")).rstrip("%").strip()
try:
percents.append(float(text))
except ValueError:
continue
volume = (sum(percents) / len(percents) / 100.0) if percents else 0.0
sinks.append(
{
"name": sink.get("name", ""),
"description": sink.get("description") or sink.get("name", ""),
"volume": round(volume, 3),
"muted": bool(sink.get("mute", False)),
}
)
return sinks
class AudioManager:
"""Suit les sorties via `pactl subscribe` et applique les commandes."""
def __init__(self, max_volume: float, on_change: Callable[[], None]) -> None:
self._max_volume = max_volume
self._on_change = on_change
self._pactl = shutil.which("pactl")
self._sinks: list[dict[str, Any]] = []
self._default = ""
self._tasks: list[asyncio.Task[None]] = []
self._refresh_task: asyncio.Task[None] | None = None
@property
def available(self) -> bool:
return self._pactl is not None
async def start(self) -> None:
if not self.available:
log.warning("pactl not found: audio control disabled (apt install pulseaudio-utils)")
return
await self.refresh()
self._tasks.append(asyncio.create_task(self._watch()))
async def stop(self) -> None:
for task in self._tasks:
task.cancel()
async def _run(self, *args: str) -> str:
assert self._pactl is not None
process = await asyncio.create_subprocess_exec(
self._pactl,
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
raise RuntimeError(stderr.decode(errors="replace").strip() or f"pactl {args[0]} failed")
return stdout.decode()
async def refresh(self) -> None:
try:
self._sinks = parse_sinks(await self._run("-f", "json", "list", "sinks"))
self._default = (await self._run("get-default-sink")).strip()
except (RuntimeError, json.JSONDecodeError) as exc:
log.warning("audio refresh failed: %s", exc)
return
self._on_change()
def _schedule_refresh(self) -> None:
# Anti-rebond : pactl subscribe émet des rafales d'événements
if self._refresh_task is not None and not self._refresh_task.done():
return
async def delayed() -> None:
await asyncio.sleep(0.1)
await self.refresh()
self._refresh_task = asyncio.create_task(delayed())
async def _watch(self) -> None:
"""Relance `pactl subscribe` si le serveur audio redémarre."""
assert self._pactl is not None
while True:
process = await asyncio.create_subprocess_exec(
self._pactl,
"subscribe",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
assert process.stdout is not None
try:
async for line in process.stdout:
text = line.decode(errors="replace")
if "sink" in text or "server" in text:
self._schedule_refresh()
except asyncio.CancelledError:
process.kill()
raise
await process.wait()
log.info("pactl subscribe exited, restarting in 2 s")
await asyncio.sleep(2)
def snapshot(self) -> dict[str, Any]:
return {
"available": self.available,
"default": self._default,
"max_volume": self._max_volume,
"sinks": self._sinks,
}
def _check_sink(self, name: Any) -> str:
if not isinstance(name, str) or name not in {sink["name"] for sink in self._sinks}:
raise ValueError("unknown sink")
return name
async def execute(self, action: str, sink: Any, value: Any) -> None:
if not self.available:
raise RuntimeError("audio control unavailable")
sink_name = self._check_sink(sink if sink is not None else self._default)
match action:
case "set_volume":
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError("numeric volume expected")
volume = min(self._max_volume, max(0.0, float(value)))
await self._run("set-sink-volume", sink_name, f"{round(volume * 100)}%")
case "toggle_mute":
await self._run("set-sink-mute", sink_name, "toggle")
case "set_default":
await self._run("set-default-sink", sink_name)
case _:
raise ValueError(f"unknown audio action '{action}'")
+191
View File
@@ -0,0 +1,191 @@
"""Chargement et validation de la configuration TOML."""
from __future__ import annotations
import os
import re
import secrets
import tomllib
from dataclasses import dataclass
from pathlib import Path
from typing import Any
# Emplacement par défaut, conforme XDG
CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "mediadeck"
CONFIG_PATH = CONFIG_DIR / "config.toml"
MIN_TOKEN_LENGTH = 16
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$")
# Nom d'hôte ou IPv4, sans schéma, port ni chemin (inséré tel quel dans l'URL tablette)
_HOSTNAME_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$")
class ConfigError(Exception):
"""Erreur de configuration lisible par l'utilisateur."""
@dataclass(frozen=True)
class Launcher:
"""Commande lançable depuis la tablette (argv, jamais de shell)."""
id: str
label: str
command: tuple[str, ...]
icon: str = "app"
@dataclass(frozen=True)
class Config:
host: str
port: int
token: str
max_volume: float
enable_input: bool
enable_power: bool
launchers: tuple[Launcher, ...]
# Adresse annoncée dans l'URL/QR code ; vide = détection automatique
advertise_host: str = ""
# HTTPS : certificat + clé du serveur ; tls_ca (public) est servi sur /ca.crt pour l'installer sur la tablette
tls_cert: Path | None = None
tls_key: Path | None = None
tls_ca: Path | None = None
# Page d'administration des lanceurs ; les commandes brutes restent réservées au fichier de configuration
admin_enabled: bool = True
allow_custom_command: bool = False
# Saisie de texte depuis la tablette : équivaut à un clavier complet, donc désactivée par défaut
enable_text_input: bool = False
@property
def tls_enabled(self) -> bool:
return self.tls_cert is not None
def generate_token() -> str:
"""Jeton aléatoire URL-safe (~256 bits)."""
return secrets.token_urlsafe(32)
def _parse_path(server: dict[str, Any], key: str) -> Path | None:
value = server.get(key, "")
if not isinstance(value, str):
raise ConfigError(f"server.{key} must be a string")
return Path(value).expanduser() if value else None
def _parse_launchers(raw: Any) -> tuple[Launcher, ...]:
if raw is None:
return ()
if not isinstance(raw, list):
raise ConfigError("'launchers' must be an array of tables")
launchers: list[Launcher] = []
seen: set[str] = set()
for index, item in enumerate(raw):
if not isinstance(item, dict):
raise ConfigError(f"launchers[{index}] must be a table")
launcher_id = item.get("id")
label = item.get("label")
command = item.get("command")
icon = item.get("icon", "app")
if not isinstance(launcher_id, str) or not _ID_RE.match(launcher_id):
raise ConfigError(f"launchers[{index}].id must match {_ID_RE.pattern}")
if launcher_id in seen:
raise ConfigError(f"duplicate launcher id '{launcher_id}'")
if not isinstance(label, str) or not label:
raise ConfigError(f"launchers[{index}].label must be a non-empty string")
# La commande est une liste argv : aucun passage par un shell
if (
not isinstance(command, list)
or not command
or not all(isinstance(arg, str) and arg for arg in command)
):
raise ConfigError(f"launchers[{index}].command must be a non-empty list of strings")
if not isinstance(icon, str):
raise ConfigError(f"launchers[{index}].icon must be a string")
seen.add(launcher_id)
launchers.append(Launcher(launcher_id, label, tuple(command), icon))
return tuple(launchers)
def parse_config(data: dict[str, Any]) -> Config:
"""Valide un dictionnaire issu du TOML et construit la Config."""
server = data.get("server", {})
features = data.get("features", {})
audio = data.get("audio", {})
admin = data.get("admin", {})
if not all(isinstance(table, dict) for table in (server, features, audio, admin)):
raise ConfigError("[server], [features], [audio] and [admin] must be tables")
host = server.get("host", "0.0.0.0")
port = server.get("port", 8765)
token = server.get("token", "")
advertise_host = server.get("advertise_host", "")
if not isinstance(host, str) or not host:
raise ConfigError("server.host must be a non-empty string")
if not isinstance(port, int) or not 1 <= port <= 65535:
raise ConfigError("server.port must be an integer between 1 and 65535")
if not isinstance(token, str) or len(token) < MIN_TOKEN_LENGTH:
raise ConfigError(
f"server.token must be at least {MIN_TOKEN_LENGTH} characters (run 'make token')"
)
if not isinstance(advertise_host, str) or (advertise_host and not _HOSTNAME_RE.match(advertise_host)):
raise ConfigError("server.advertise_host must be a hostname or IPv4 address (no scheme, port or path)")
tls_cert = _parse_path(server, "tls_cert")
tls_key = _parse_path(server, "tls_key")
tls_ca = _parse_path(server, "tls_ca")
if (tls_cert is None) != (tls_key is None):
raise ConfigError("server.tls_cert and server.tls_key must be set together")
if tls_ca is not None and tls_cert is None:
raise ConfigError("server.tls_ca requires server.tls_cert and server.tls_key")
max_volume = audio.get("max_volume", 1.0)
if not isinstance(max_volume, (int, float)) or not 0.1 <= float(max_volume) <= 1.5:
raise ConfigError("audio.max_volume must be between 0.1 and 1.5")
enable_input = features.get("input", True)
enable_power = features.get("power", True)
enable_text_input = features.get("text_input", False)
if not all(isinstance(flag, bool) for flag in (enable_input, enable_power, enable_text_input)):
raise ConfigError("features.input, features.power and features.text_input must be booleans")
admin_enabled = admin.get("enabled", True)
allow_custom_command = admin.get("allow_custom_command", False)
if not isinstance(admin_enabled, bool) or not isinstance(allow_custom_command, bool):
raise ConfigError("admin.enabled and admin.allow_custom_command must be booleans")
return Config(
host=host,
port=port,
token=token,
max_volume=float(max_volume),
enable_input=enable_input,
enable_power=enable_power,
launchers=_parse_launchers(data.get("launchers")),
advertise_host=advertise_host,
tls_cert=tls_cert,
tls_key=tls_key,
tls_ca=tls_ca,
admin_enabled=admin_enabled,
allow_custom_command=allow_custom_command,
enable_text_input=enable_text_input,
)
def load_config(path: Path | None = None) -> Config:
"""Lit le fichier TOML ; lève ConfigError avec un message explicite."""
config_path = path or CONFIG_PATH
try:
with config_path.open("rb") as handle:
data = tomllib.load(handle)
except FileNotFoundError as exc:
raise ConfigError(f"config file not found: {config_path} (run 'make config')") from exc
except tomllib.TOMLDecodeError as exc:
raise ConfigError(f"invalid TOML in {config_path}: {exc}") from exc
# Le fichier contient le jeton : on refuse s'il est lisible par les autres
mode = config_path.stat().st_mode
if mode & 0o077:
raise ConfigError(f"{config_path} must not be readable by group/others (chmod 600)")
return parse_config(data)
+152
View File
@@ -0,0 +1,152 @@
"""Clavier et souris virtuels via /dev/uinput (fonctionne sous X11 et Wayland)."""
from __future__ import annotations
import logging
from typing import Any
log = logging.getLogger(__name__)
try:
from evdev import UInput, ecodes # type: ignore[import-untyped]
except ImportError: # evdev absent : l'entrée virtuelle est simplement désactivée
UInput = None
ecodes = None
# Touches exposées au client : noms stables -> codes evdev.
# Volontairement limité à la navigation : les caractères passent par la saisie de texte (text.py),
# qui traduit chaque caractère selon la disposition réelle du clavier du PC.
KEY_NAMES = {
"up": "KEY_UP",
"down": "KEY_DOWN",
"left": "KEY_LEFT",
"right": "KEY_RIGHT",
"enter": "KEY_ENTER",
"escape": "KEY_ESC",
"back": "KEY_BACKSPACE",
"space": "KEY_SPACE",
"tab": "KEY_TAB",
"home": "KEY_HOME",
"end": "KEY_END",
"page_up": "KEY_PAGEUP",
"page_down": "KEY_PAGEDOWN",
"fullscreen": "KEY_F",
"f11": "KEY_F11",
"meta": "KEY_LEFTMETA",
"play_pause": "KEY_PLAYPAUSE",
"next": "KEY_NEXTSONG",
"previous": "KEY_PREVIOUSSONG",
"volume_up": "KEY_VOLUMEUP",
"volume_down": "KEY_VOLUMEDOWN",
"mute": "KEY_MUTE",
}
BUTTONS = {"left": "BTN_LEFT", "right": "BTN_RIGHT", "middle": "BTN_MIDDLE"}
# Touches que le clavier virtuel sait produire pour la saisie de texte : bloc principal (Échap … Espace, soit les codes
# 1 à 57), touche « <> » (86) et AltGr (100). Jamais exposées au client : seules les touches de KEY_NAMES le sont.
TYPING_KEYS = frozenset(range(1, 58)) | {86, 100}
# Bornes anti-abus pour les messages du client
MAX_MOVE = 500
MAX_SCROLL = 20
class VirtualInput:
"""Deux périphériques distincts (clavier + pointeur) pour une détection libinput fiable."""
def __init__(self, enabled: bool) -> None:
self._keyboard: Any = None
self._pointer: Any = None
self.reason = ""
if not enabled:
self.reason = "disabled in config"
return
if UInput is None or ecodes is None:
self.reason = "python3-evdev not installed"
return
try:
keys = sorted({getattr(ecodes, code) for code in KEY_NAMES.values()} | TYPING_KEYS)
self._keyboard = UInput({ecodes.EV_KEY: keys}, name="MediaDeck Keyboard")
self._pointer = UInput(
{
ecodes.EV_KEY: [getattr(ecodes, code) for code in BUTTONS.values()],
ecodes.EV_REL: [ecodes.REL_X, ecodes.REL_Y, ecodes.REL_WHEEL, ecodes.REL_HWHEEL],
},
name="MediaDeck Pointer",
)
except (OSError, PermissionError) as exc:
# Cas typique : règle udev uaccess non installée
self.reason = f"cannot open /dev/uinput: {exc} (run 'make uinput')"
self.close()
log.warning(self.reason)
@property
def available(self) -> bool:
return self._keyboard is not None and self._pointer is not None
def close(self) -> None:
for device in (self._keyboard, self._pointer):
if device is not None:
device.close()
self._keyboard = None
self._pointer = None
def snapshot(self) -> dict[str, Any]:
return {"available": self.available, "reason": self.reason, "keys": sorted(KEY_NAMES)}
def write_keys(self, events: list[tuple[int, bool]]) -> None:
"""Écrit des événements (code evdev, appuyée) puis synchronise ; réservé à la saisie de texte."""
if not self.available or ecodes is None:
raise RuntimeError(f"virtual input unavailable: {self.reason}")
for code, pressed in events:
if code not in TYPING_KEYS:
raise ValueError(f"key code {code} not allowed")
self._keyboard.write(ecodes.EV_KEY, code, 1 if pressed else 0)
self._keyboard.syn()
def execute(self, action: str, payload: dict[str, Any]) -> None:
if not self.available or ecodes is None:
raise RuntimeError(f"virtual input unavailable: {self.reason}")
match action:
case "key":
name = payload.get("key")
if name not in KEY_NAMES:
raise ValueError("unknown key")
code = getattr(ecodes, KEY_NAMES[name])
self._keyboard.write(ecodes.EV_KEY, code, 1)
self._keyboard.write(ecodes.EV_KEY, code, 0)
self._keyboard.syn()
case "move":
dx = _clamp_int(payload.get("dx"), MAX_MOVE)
dy = _clamp_int(payload.get("dy"), MAX_MOVE)
if dx:
self._pointer.write(ecodes.EV_REL, ecodes.REL_X, dx)
if dy:
self._pointer.write(ecodes.EV_REL, ecodes.REL_Y, dy)
self._pointer.syn()
case "scroll":
dy = _clamp_int(payload.get("dy"), MAX_SCROLL)
dx = _clamp_int(payload.get("dx", 0), MAX_SCROLL)
if dy:
self._pointer.write(ecodes.EV_REL, ecodes.REL_WHEEL, dy)
if dx:
self._pointer.write(ecodes.EV_REL, ecodes.REL_HWHEEL, dx)
self._pointer.syn()
case "click":
button = payload.get("button", "left")
if button not in BUTTONS:
raise ValueError("unknown button")
code = getattr(ecodes, BUTTONS[button])
self._pointer.write(ecodes.EV_KEY, code, 1)
self._pointer.syn()
self._pointer.write(ecodes.EV_KEY, code, 0)
self._pointer.syn()
case _:
raise ValueError(f"unknown input action '{action}'")
def _clamp_int(value: Any, limit: int) -> int:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError("numeric value expected")
return max(-limit, min(limit, int(value)))
+377
View File
@@ -0,0 +1,377 @@
"""Traduction caractère -> touches selon la disposition réelle du clavier du PC.
La disposition (AZERTY, QWERTY…) est lue dans la configuration de KDE (kxkbrc) ou via setxkbmap, puis compilée
avec libxkbcommon (ctypes, aucune dépendance Python). Chaque caractère devient la ou les touches que produirait
un vrai clavier : Maj, AltGr et touches mortes (é, ê, ñ…) comprises. Rien ne passe par le presse-papiers.
"""
from __future__ import annotations
import asyncio
import configparser
import ctypes
import ctypes.util
import os
import unicodedata
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from .input import TYPING_KEYS
# Codes evdev (linux/input-event-codes.h)
KEY_ENTER = 28
KEY_TAB = 15
KEY_SPACE = 57
KEY_RIGHTALT = 100
# Keysyms X11 utiles (X11/keysymdef.h)
_LOG_LEVEL_CRITICAL = 10
_KEYSYM_SHIFT_L = 0xFFE1
_KEYSYM_ISO_LEVEL3_SHIFT = 0xFE03
# Marque combinante Unicode -> touche morte correspondante
_DEAD_KEYSYMS = {
"̀": 0xFE50, # grave
"́": 0xFE51, # aigu
"̂": 0xFE52, # circonflexe
"̃": 0xFE53, # tilde
"̄": 0xFE54, # macron
"̆": 0xFE55, # brève
"̇": 0xFE56, # point en chef
"̈": 0xFE57, # tréma
"̊": 0xFE58, # rond en chef
"̋": 0xFE59, # double aigu
"̌": 0xFE5A, # caron
"̧": 0xFE5B, # cédille
"̨": 0xFE5C, # ogonek
}
# Accents isolés : touche morte suivie d'une espace (« ^ » sur un clavier AZERTY, par exemple)
_SPACING_ACCENTS = {
"^": 0xFE52,
"`": 0xFE50,
"~": 0xFE53,
"¨": 0xFE57,
"´": 0xFE51,
"¸": 0xFE5B,
}
# Typographie des claviers tactiles, remplacée si la disposition du PC n'a pas le caractère
_TYPOGRAPHIC = {
"‘": "'",
"’": "'",
"“": '"',
"”": '"',
"«": '"',
"»": '"',
"…": "...",
"–": "-",
"—": "-",
" ": " ",
" ": " ",
" ": " ",
}
class KeymapError(Exception):
"""Disposition du clavier introuvable ou bibliothèque xkbcommon absente."""
@dataclass(frozen=True)
class LayoutSpec:
"""Noms XKB d'une disposition (ceux de setxkbmap / kxkbrc)."""
model: str = "pc105"
layout: str = "us"
variant: str = ""
options: str = ""
@dataclass(frozen=True)
class Stroke:
"""Une frappe : une touche (code evdev), éventuellement avec Maj et/ou AltGr."""
code: int
shift: bool = False
altgr: bool = False
# ----------------------------------------------------------------------
# libxkbcommon
# ----------------------------------------------------------------------
class _RuleNames(ctypes.Structure):
_fields_ = [
("rules", ctypes.c_char_p),
("model", ctypes.c_char_p),
("layout", ctypes.c_char_p),
("variant", ctypes.c_char_p),
("options", ctypes.c_char_p),
]
_library: ctypes.CDLL | None = None
def load_xkb() -> ctypes.CDLL:
"""Charge libxkbcommon une seule fois et déclare les prototypes utilisés."""
global _library
if _library is not None:
return _library
name = ctypes.util.find_library("xkbcommon") or "libxkbcommon.so.0"
try:
lib = ctypes.CDLL(name)
except OSError as exc:
raise KeymapError("libxkbcommon not found (apt install libxkbcommon0)") from exc
u32, vp, cp, sz = ctypes.c_uint32, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t
prototypes: dict[str, tuple[Any, list[Any]]] = {
"xkb_context_new": (vp, [ctypes.c_int]),
"xkb_context_unref": (None, [vp]),
"xkb_context_set_log_level": (None, [vp, ctypes.c_int]),
"xkb_keymap_new_from_names": (vp, [vp, ctypes.POINTER(_RuleNames), ctypes.c_int]),
"xkb_keymap_unref": (None, [vp]),
"xkb_keymap_min_keycode": (u32, [vp]),
"xkb_keymap_max_keycode": (u32, [vp]),
"xkb_keymap_num_levels_for_key": (u32, [vp, u32, u32]),
"xkb_keymap_key_get_syms_by_level": (
ctypes.c_int,
[vp, u32, u32, u32, ctypes.POINTER(ctypes.POINTER(u32))],
),
"xkb_keymap_key_get_mods_for_level": (sz, [vp, u32, u32, u32, ctypes.POINTER(u32), sz]),
"xkb_keymap_mod_get_index": (u32, [vp, cp]),
"xkb_utf32_to_keysym": (u32, [u32]),
}
try:
for function, (restype, argtypes) in prototypes.items():
native = getattr(lib, function)
native.restype = restype
native.argtypes = argtypes
except AttributeError as exc:
raise KeymapError(f"libxkbcommon too old: {exc}") from exc
_library = lib
return lib
class Keymap:
"""Table keysym -> frappe pour une disposition donnée (premier groupe de la carte compilée)."""
def __init__(self, spec: LayoutSpec) -> None:
self.spec = spec
self.lib = load_xkb()
self._context: Any = self.lib.xkb_context_new(0)
if not self._context:
raise KeymapError("cannot create an xkb context")
# Les erreurs de compilation deviennent une KeymapError : inutile de les écrire aussi sur stderr
self.lib.xkb_context_set_log_level(self._context, _LOG_LEVEL_CRITICAL)
names = _RuleNames(
b"evdev", spec.model.encode(), spec.layout.encode(), spec.variant.encode(), spec.options.encode()
)
self.handle: Any = self.lib.xkb_keymap_new_from_names(self._context, ctypes.byref(names), 0)
if not self.handle:
self.lib.xkb_context_unref(self._context)
self._context = None
raise KeymapError(f"cannot compile the keyboard layout '{spec.layout}' variant '{spec.variant}'")
self._table: dict[int, Stroke] = {}
self.shift_code: int | None = None
self.altgr_code: int | None = None
self._build()
def close(self) -> None:
if self.handle:
self.lib.xkb_keymap_unref(self.handle)
self.handle = None
if self._context:
self.lib.xkb_context_unref(self._context)
self._context = None
def __del__(self) -> None:
try:
self.close()
except Exception: # noqa: BLE001 - arrêt de l'interpréteur
pass
def _mod_bit(self, name: str) -> int:
index = self.lib.xkb_keymap_mod_get_index(self.handle, name.encode())
return 0 if index == 0xFFFFFFFF else 1 << index
def _build(self) -> None:
lib, handle = self.lib, self.handle
shift_bit, level3_bit = self._mod_bit("Shift"), self._mod_bit("Mod5")
candidates: list[tuple[int, Stroke]] = []
for key in range(lib.xkb_keymap_min_keycode(handle), lib.xkb_keymap_max_keycode(handle) + 1):
code = key - 8 # keycodes xkb = codes evdev + 8
if code not in TYPING_KEYS:
continue
for level in range(lib.xkb_keymap_num_levels_for_key(handle, key, 0)):
syms = ctypes.POINTER(ctypes.c_uint32)()
if lib.xkb_keymap_key_get_syms_by_level(handle, key, 0, level, ctypes.byref(syms)) != 1:
continue
keysym = int(syms[0])
if level == 0 and keysym == _KEYSYM_SHIFT_L and self.shift_code is None:
self.shift_code = code
elif level == 0 and keysym == _KEYSYM_ISO_LEVEL3_SHIFT and self.altgr_code is None:
self.altgr_code = code
masks = (ctypes.c_uint32 * 8)()
count = lib.xkb_keymap_key_get_mods_for_level(handle, key, 0, level, masks, 8)
for mask in masks[:count]:
# Seuls Maj et AltGr sont simulables ; Ctrl, Alt et Super changeraient le sens de la frappe
if mask & ~(shift_bit | level3_bit):
continue
candidates.append((keysym, Stroke(code, bool(mask & shift_bit), bool(mask & level3_bit))))
# Pour un même keysym, la frappe la plus simple : moins de modificateurs, puis code le plus petit
best: dict[int, Stroke] = {}
for keysym, stroke in candidates:
if (stroke.shift and self.shift_code is None) or (stroke.altgr and self.altgr_code is None):
continue
current = best.get(keysym)
if current is None or _cost(stroke) < _cost(current):
best[keysym] = stroke
self._table = best
# ------------------------------------------------------------------
# Texte -> frappes
# ------------------------------------------------------------------
def _direct(self, char: str) -> Stroke | None:
if ord(char) < 0x20:
return None
return self._table.get(int(self.lib.xkb_utf32_to_keysym(ord(char))))
def _sequence(self, char: str) -> list[Stroke] | None:
if char == "\n":
return [Stroke(KEY_ENTER)]
if char == "\t":
return [Stroke(KEY_TAB)]
if char == "\r":
return []
direct = self._direct(char)
if direct is not None:
return [direct]
replacement = _TYPOGRAPHIC.get(char)
if replacement is not None:
parts = [self._sequence(item) for item in replacement]
if any(part is None for part in parts):
return None
return [stroke for part in parts if part is not None for stroke in part]
# Lettre accentuée absente de la disposition : touche morte puis lettre de base (ê = ^ + e)
decomposed = unicodedata.normalize("NFD", char)
if len(decomposed) == 2 and decomposed[1] in _DEAD_KEYSYMS:
dead = self._table.get(_DEAD_KEYSYMS[decomposed[1]])
base = self._direct(decomposed[0])
if dead is not None and base is not None:
return [dead, base]
accent = _SPACING_ACCENTS.get(char)
if accent is not None:
dead, space = self._table.get(accent), self._direct(" ")
if dead is not None and space is not None:
return [dead, space]
return None
def plan(self, text: str) -> tuple[list[Stroke], list[str]]:
"""Frappes à produire pour ce texte, et caractères impossibles à saisir avec cette disposition."""
strokes: list[Stroke] = []
skipped: list[str] = []
for char in text:
sequence = self._sequence(char)
if sequence is None:
if char not in skipped:
skipped.append(char)
else:
strokes.extend(sequence)
return strokes, skipped
def _cost(stroke: Stroke) -> tuple[int, int]:
return int(stroke.shift) + int(stroke.altgr), stroke.code
# ----------------------------------------------------------------------
# Détection de la disposition courante
# ----------------------------------------------------------------------
class _CaseSensitiveParser(configparser.RawConfigParser):
def optionxform(self, optionstr: str) -> str:
return optionstr
def _specs(model: str, layouts: str, variants: str, options: str) -> list[LayoutSpec]:
names = [name.strip() for name in layouts.split(",") if name.strip()]
variant_list = [variant.strip() for variant in variants.split(",")]
variant_list += [""] * (len(names) - len(variant_list))
return [
LayoutSpec(model.strip() or "pc105", name, variant_list[index], options.strip())
for index, name in enumerate(names)
]
def parse_kxkbrc(text: str) -> list[LayoutSpec] | None:
"""Dispositions déclarées dans le fichier kxkbrc de KDE, ou None s'il ne s'applique pas."""
parser = _CaseSensitiveParser(strict=False)
try:
parser.read_string(text)
except configparser.Error:
return None
if not parser.has_section("Layout") or parser.get("Layout", "Use", fallback="false").lower() != "true":
return None
specs = _specs(
parser.get("Layout", "Model", fallback=""),
parser.get("Layout", "LayoutList", fallback=""),
parser.get("Layout", "VariantList", fallback=""),
parser.get("Layout", "Options", fallback=""),
)
return specs or None
def parse_setxkbmap(text: str) -> list[LayoutSpec] | None:
"""Dispositions de la sortie de ``setxkbmap -query`` (session X11)."""
values: dict[str, str] = {}
for line in text.splitlines():
key, _, value = line.partition(":")
values[key.strip()] = value.strip()
specs = _specs(
values.get("model", ""), values.get("layout", ""), values.get("variant", ""), values.get("options", "")
)
return specs or None
async def _configured_layouts() -> list[LayoutSpec]:
config_home = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")))
try:
specs = parse_kxkbrc(await asyncio.to_thread((config_home / "kxkbrc").read_text, "utf-8"))
except OSError:
specs = None
if specs:
return specs
try:
process = await asyncio.create_subprocess_exec(
"setxkbmap", "-query", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL
)
output, _ = await process.communicate()
specs = parse_setxkbmap(output.decode(errors="replace"))
except OSError:
specs = None
if specs:
return specs
raise KeymapError("cannot detect the keyboard layout (no kxkbrc, no setxkbmap)")
async def _kde_layout_index(bus: Any) -> int:
"""Index de la disposition active selon KDE (0 si le service est absent)."""
try:
introspection = await bus.introspect("org.kde.keyboard", "/Layouts")
proxy = bus.get_proxy_object("org.kde.keyboard", "/Layouts", introspection)
layouts: Any = proxy.get_interface("org.kde.KeyboardLayouts")
return int(await layouts.call_get_layout())
except Exception: # noqa: BLE001 - pas de KDE ou bus indisponible
return 0
async def current_layout(bus: Any | None) -> LayoutSpec:
"""Disposition réellement active : la liste configurée, l'index choisi par KDE si plusieurs sont déclarées."""
specs = await _configured_layouts()
index = await _kde_layout_index(bus) if bus is not None and len(specs) > 1 else 0
return specs[index] if 0 <= index < len(specs) else specs[0]
+366
View File
@@ -0,0 +1,366 @@
"""Lanceurs gérés en base SQLite : stockage, validation et construction de la commande.
Trois types de lanceurs, du plus sûr au plus ouvert :
- ``web`` : URL http(s) ouverte dans un navigateur choisi parmi une liste fermée ;
- ``app`` : application installée, désignée par son fichier .desktop (lancée via ``gio launch``) ;
- ``command`` : liste argv brute, réservée à la configuration (``admin.allow_custom_command``).
Le client n'écrit donc jamais de commande, sauf autorisation explicite dans le fichier de configuration.
"""
from __future__ import annotations
import json
import logging
import os
import re
import shutil
import sqlite3
import unicodedata
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
from .config import Launcher as ConfigLauncher
log = logging.getLogger(__name__)
DATA_DIR = Path(os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local" / "share"))) / "mediadeck"
DB_PATH = DATA_DIR / "launchers.db"
# Icônes du sprite de l'interface (index.html)
ICONS = ("app", "tv", "film", "globe", "music", "screen-off", "speaker", "lock", "window")
KINDS = ("web", "app", "command")
MAX_LAUNCHERS = 64
MAX_LABEL = 40
MAX_URL = 2000
MAX_ARGS = 32
MAX_ARG_LENGTH = 1000
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$")
_DESKTOP_ID_RE = re.compile(r"^[A-Za-z0-9._+-]{1,200}\.desktop$")
_URL_FORBIDDEN_RE = re.compile(r"[\s\x00-\x1f\x7f]")
class LauncherError(ValueError):
"""Requête de lanceur invalide (message lisible par l'utilisateur)."""
class LauncherNotFound(LauncherError):
"""Identifiant de lanceur inconnu."""
class CommandNotAllowed(LauncherError):
"""Commande brute refusée : réservée au fichier de configuration."""
@dataclass(frozen=True)
class Browser:
id: str
name: str
executable: str
args: tuple[str, ...]
# None = plein écran automatique impossible (le mode kiosque de Firefox ignore F11)
fullscreen_args: tuple[str, ...] | None
@property
def installed(self) -> bool:
return shutil.which(self.executable) is not None
BROWSERS = (
Browser("chromium", "Chromium", "chromium", (), ("--start-fullscreen",)),
Browser("chrome", "Google Chrome", "google-chrome-stable", (), ("--start-fullscreen",)),
Browser("brave", "Brave", "brave-browser", (), ("--start-fullscreen",)),
Browser("firefox", "Firefox", "firefox", ("--new-window",), None),
)
def browser_by_id(browser_id: str) -> Browser | None:
return next((browser for browser in BROWSERS if browser.id == browser_id), None)
@dataclass(frozen=True)
class LauncherEntry:
id: str
label: str
icon: str
kind: str
spec: dict[str, Any]
def to_dict(self) -> dict[str, Any]:
return {"id": self.id, "label": self.label, "icon": self.icon, "kind": self.kind, "spec": self.spec}
# ----------------------------------------------------------------------
# Applications installées (.desktop)
# ----------------------------------------------------------------------
@dataclass(frozen=True)
class DesktopApp:
id: str
name: str
def desktop_dirs() -> list[Path]:
"""Dossiers « applications » par ordre de priorité XDG, y compris les exports Flatpak."""
data_home = Path(os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local" / "share")))
data_dirs = os.environ.get("XDG_DATA_DIRS") or "/usr/local/share:/usr/share"
roots = [
data_home,
*(Path(entry) for entry in data_dirs.split(":") if entry),
data_home / "flatpak" / "exports" / "share",
Path("/var/lib/flatpak/exports/share"),
]
return list(dict.fromkeys(root / "applications" for root in roots))
def _read_desktop_name(path: Path) -> str | None:
"""Nom affichable d'une entrée .desktop lançable, ou None (masquée, terminal, illisible)."""
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
values: dict[str, str] = {}
in_entry = False
for raw in text.splitlines():
line = raw.strip()
if line.startswith("["):
in_entry = line == "[Desktop Entry]"
elif in_entry and "=" in line and not line.startswith("#"):
key, _, value = line.partition("=")
values.setdefault(key.strip(), value.strip())
if values.get("Type") != "Application" or not values.get("Exec") or not values.get("Name"):
return None
if any(values.get(flag, "").lower() == "true" for flag in ("NoDisplay", "Hidden", "Terminal")):
return None
return values["Name"]
def list_desktop_apps() -> list[DesktopApp]:
apps: dict[str, DesktopApp] = {}
for directory in desktop_dirs():
if not directory.is_dir():
continue
for path in directory.glob("*.desktop"):
# Le premier dossier gagne, comme dans la spécification XDG
if path.name in apps:
continue
name = _read_desktop_name(path)
if name is not None:
apps[path.name] = DesktopApp(path.name, name)
return sorted(apps.values(), key=lambda app: app.name.casefold())
def find_desktop_entry(desktop_id: str) -> Path | None:
if not _DESKTOP_ID_RE.match(desktop_id):
return None
for directory in desktop_dirs():
path = directory / desktop_id
if path.is_file() and _read_desktop_name(path) is not None:
return path
return None
# ----------------------------------------------------------------------
# Validation et construction de la commande
# ----------------------------------------------------------------------
def _validate_spec(kind: Any, spec: Any) -> dict[str, Any]:
if not isinstance(spec, dict):
raise LauncherError("spec must be an object")
match kind:
case "web":
url = spec.get("url")
if not isinstance(url, str) or not 0 < len(url.strip()) <= MAX_URL:
raise LauncherError("a URL is required")
url = url.strip()
parts = urlsplit(url)
if parts.scheme not in ("http", "https") or not parts.netloc or _URL_FORBIDDEN_RE.search(url):
raise LauncherError("the URL must be a valid http:// or https:// address")
browser = browser_by_id(str(spec.get("browser", "")))
if browser is None:
raise LauncherError("unknown browser")
fullscreen = spec.get("fullscreen", False)
if not isinstance(fullscreen, bool):
raise LauncherError("fullscreen must be a boolean")
return {"url": url, "browser": browser.id, "fullscreen": fullscreen and browser.fullscreen_args is not None}
case "app":
desktop_id = spec.get("desktop_id")
if not isinstance(desktop_id, str) or find_desktop_entry(desktop_id) is None:
raise LauncherError("unknown application")
return {"desktop_id": desktop_id}
case "command":
argv = spec.get("argv")
if (
not isinstance(argv, list)
or not 0 < len(argv) <= MAX_ARGS
or not all(isinstance(arg, str) and 0 < len(arg) <= MAX_ARG_LENGTH and "\0" not in arg for arg in argv)
):
raise LauncherError(f"argv must be a list of 1 to {MAX_ARGS} non-empty strings")
return {"argv": list(argv)}
case _:
raise LauncherError(f"kind must be one of: {', '.join(KINDS)}")
def validate(
data: Any, *, allow_command: bool, current: LauncherEntry | None = None
) -> tuple[str, str, str, dict[str, Any]]:
"""Valide une définition de lanceur ; renvoie (label, icon, kind, spec) normalisés."""
if not isinstance(data, dict):
raise LauncherError("body must be a JSON object")
label = data.get("label")
if not isinstance(label, str) or not 0 < len(label.strip()) <= MAX_LABEL:
raise LauncherError(f"label must be 1 to {MAX_LABEL} characters")
icon = data.get("icon", "app")
if icon not in ICONS:
raise LauncherError(f"icon must be one of: {', '.join(ICONS)}")
kind = data.get("kind")
if not isinstance(kind, str) or kind not in KINDS:
raise LauncherError(f"kind must be one of: {', '.join(KINDS)}")
spec = _validate_spec(kind, data.get("spec"))
# Une commande déjà enregistrée peut garder sa commande (renommage, icône) sans l'autorisation
unchanged = current is not None and current.kind == "command" and current.spec == spec
if kind == "command" and not allow_command and not unchanged:
raise CommandNotAllowed("custom commands are disabled (admin.allow_custom_command in config.toml)")
return label.strip(), icon, kind, spec
def build_argv(entry: LauncherEntry) -> list[str]:
"""Commande à exécuter (liste argv, jamais de shell)."""
match entry.kind:
case "web":
browser = browser_by_id(entry.spec.get("browser", ""))
if browser is None or not browser.installed:
raise LauncherError(f"browser not installed: {entry.spec.get('browser')}")
flags = browser.fullscreen_args if entry.spec.get("fullscreen") and browser.fullscreen_args else ()
return [browser.executable, *browser.args, *flags, entry.spec["url"]]
case "app":
path = find_desktop_entry(entry.spec.get("desktop_id", ""))
if path is None:
raise LauncherError(f"application not found: {entry.spec.get('desktop_id')}")
if shutil.which("gio") is None:
raise LauncherError("gio not found (apt install libglib2.0-bin)")
return ["gio", "launch", str(path)]
case "command":
return list(entry.spec["argv"])
case _:
raise LauncherError(f"unknown launcher kind '{entry.kind}'")
# ----------------------------------------------------------------------
# Stockage
# ----------------------------------------------------------------------
_SCHEMA = """
CREATE TABLE IF NOT EXISTS launchers (
id TEXT PRIMARY KEY,
position INTEGER NOT NULL,
label TEXT NOT NULL,
icon TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('web', 'app', 'command')),
spec TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
"""
def _slug(label: str) -> str:
ascii_label = unicodedata.normalize("NFKD", label).encode("ascii", "ignore").decode().lower()
return re.sub(r"[^a-z0-9]+", "-", ascii_label).strip("-")[:28] or "launcher"
class LauncherStore:
"""Liste ordonnée des lanceurs ; une seule boucle asyncio, donc un seul accès à la fois."""
def __init__(self, path: Path = DB_PATH) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.parent.chmod(0o700)
self._db = sqlite3.connect(path)
path.chmod(0o600)
self._db.executescript(_SCHEMA)
self._db.execute("PRAGMA user_version = 1")
self._cache: list[LauncherEntry] | None = None
def close(self) -> None:
self._db.close()
def list(self) -> list[LauncherEntry]:
if self._cache is None:
rows = self._db.execute("SELECT id, label, icon, kind, spec FROM launchers ORDER BY position").fetchall()
self._cache = [LauncherEntry(r[0], r[1], r[2], r[3], json.loads(r[4])) for r in rows]
return list(self._cache)
def get(self, launcher_id: str) -> LauncherEntry | None:
return next((entry for entry in self.list() if entry.id == launcher_id), None)
def _write(self, sql: str, *params: Any) -> None:
with self._db:
self._db.execute(sql, params)
self._cache = None
def create(self, label: str, icon: str, kind: str, spec: dict[str, Any]) -> LauncherEntry:
entries = self.list()
if len(entries) >= MAX_LAUNCHERS:
raise LauncherError(f"at most {MAX_LAUNCHERS} launchers")
taken = {entry.id for entry in entries}
base = _slug(label)
launcher_id, counter = base, 1
while launcher_id in taken:
counter += 1
launcher_id = f"{base}-{counter}"
position = len(entries)
self._write(
"INSERT INTO launchers (id, position, label, icon, kind, spec) VALUES (?, ?, ?, ?, ?, ?)",
launcher_id, position, label, icon, kind, json.dumps(spec),
)
return LauncherEntry(launcher_id, label, icon, kind, spec)
def update(self, launcher_id: str, label: str, icon: str, kind: str, spec: dict[str, Any]) -> LauncherEntry:
if self.get(launcher_id) is None:
raise LauncherNotFound("unknown launcher")
self._write(
"UPDATE launchers SET label = ?, icon = ?, kind = ?, spec = ? WHERE id = ?",
label, icon, kind, json.dumps(spec), launcher_id,
)
return LauncherEntry(launcher_id, label, icon, kind, spec)
def delete(self, launcher_id: str) -> None:
if self.get(launcher_id) is None:
raise LauncherNotFound("unknown launcher")
self._write("DELETE FROM launchers WHERE id = ?", launcher_id)
def reorder(self, ids: list[str]) -> None:
if sorted(ids) != sorted(entry.id for entry in self.list()):
raise LauncherError("ids must list every launcher exactly once")
with self._db:
self._db.executemany("UPDATE launchers SET position = ? WHERE id = ?", list(enumerate(ids)))
self._cache = None
def seed(self, launchers: Iterable[ConfigLauncher]) -> int:
"""Importe une seule fois les [[launchers]] du fichier de configuration ; renvoie le nombre importé."""
if self._db.execute("SELECT 1 FROM meta WHERE key = 'seeded'").fetchone() is not None:
return 0
imported = 0
with self._db:
for position, launcher in enumerate(launchers):
if not _ID_RE.match(launcher.id):
continue
self._db.execute(
"INSERT INTO launchers (id, position, label, icon, kind, spec) VALUES (?, ?, ?, ?, 'command', ?)",
(
launcher.id,
position,
launcher.label,
launcher.icon if launcher.icon in ICONS else "app",
json.dumps({"argv": list(launcher.command)}),
),
)
imported += 1
self._db.execute("INSERT INTO meta (key, value) VALUES ('seeded', '1')")
self._cache = None
return imported
+301
View File
@@ -0,0 +1,301 @@
"""Suivi et pilotage des lecteurs MPRIS sur le bus D-Bus de session."""
from __future__ import annotations
import asyncio
import hashlib
import logging
from collections.abc import Callable
from typing import Any
from dbus_next.signature import Variant
from dbus_next.aio.message_bus import MessageBus
log = logging.getLogger(__name__)
MPRIS_PREFIX = "org.mpris.MediaPlayer2."
MPRIS_PATH = "/org/mpris/MediaPlayer2"
ROOT_IFACE = "org.mpris.MediaPlayer2"
PLAYER_IFACE = "org.mpris.MediaPlayer2.Player"
PROPS_IFACE = "org.freedesktop.DBus.Properties"
# Champs de métadonnées transmis au client
_METADATA_KEYS = {
"mpris:trackid": "trackid",
"mpris:length": "length",
"mpris:artUrl": "art_url",
"xesam:title": "title",
"xesam:artist": "artist",
"xesam:album": "album",
"xesam:url": "url",
}
_LOOP_VALUES = ("None", "Track", "Playlist")
def unwrap(value: Any) -> Any:
"""Convertit récursivement les Variant D-Bus en types Python natifs."""
if isinstance(value, Variant):
return unwrap(value.value)
if isinstance(value, dict):
return {key: unwrap(item) for key, item in value.items()}
if isinstance(value, list):
return [unwrap(item) for item in value]
return value
def normalize_metadata(raw: dict[str, Any]) -> dict[str, Any]:
"""Réduit les métadonnées MPRIS aux champs utiles, avec des types stables."""
data = unwrap(raw)
result: dict[str, Any] = {}
for source, target in _METADATA_KEYS.items():
if source in data:
result[target] = data[source]
# xesam:artist est une liste de chaînes selon la spec
artist = result.get("artist")
if isinstance(artist, list):
result["artist"] = ", ".join(str(item) for item in artist)
# mpris:length peut être int64 ou uint64 selon le lecteur
length = result.get("length")
result["length"] = int(length) if isinstance(length, (int, float)) else 0
return result
class Player:
"""Un lecteur MPRIS et son état mis en cache."""
def __init__(self, bus_name: str, root: Any, player: Any, props: Any) -> None:
self.bus_name = bus_name
self._root = root
self._player = player
self._props = props
self.state: dict[str, Any] = {}
self.position_us = 0
self.position_stamp = 0.0
@property
def art_url(self) -> str | None:
url = self.state.get("metadata", {}).get("art_url")
return url if isinstance(url, str) and url else None
async def refresh(self) -> None:
"""Relit toutes les propriétés (appelé à l'ajout et sur PropertiesChanged)."""
root_props = unwrap(await self._props.call_get_all(ROOT_IFACE))
player_props = unwrap(await self._props.call_get_all(PLAYER_IFACE))
self.state = {
"identity": root_props.get("Identity", self.bus_name.removeprefix(MPRIS_PREFIX)),
"can_raise": bool(root_props.get("CanRaise", False)),
"status": player_props.get("PlaybackStatus", "Stopped"),
"metadata": normalize_metadata(player_props.get("Metadata", {})),
"volume": player_props.get("Volume"),
"shuffle": player_props.get("Shuffle"),
"loop": player_props.get("LoopStatus"),
"can_play": bool(player_props.get("CanPlay", False)),
"can_pause": bool(player_props.get("CanPause", False)),
"can_seek": bool(player_props.get("CanSeek", False)),
"can_next": bool(player_props.get("CanGoNext", False)),
"can_previous": bool(player_props.get("CanGoPrevious", False)),
}
await self.refresh_position()
async def refresh_position(self) -> None:
"""Position non signalée par PropertiesChanged : lecture explicite."""
try:
value = unwrap(await self._props.call_get(PLAYER_IFACE, "Position"))
self.position_us = int(value)
except Exception: # noqa: BLE001 - certains lecteurs ne l'exposent pas
self.position_us = 0
self.position_stamp = asyncio.get_running_loop().time()
def snapshot(self, art_path: str | None) -> dict[str, Any]:
metadata = dict(self.state.get("metadata", {}))
# L'URL de pochette réelle reste côté serveur (file:// notamment)
metadata.pop("art_url", None)
metadata["art"] = art_path
return {**self.state, "name": self.bus_name, "metadata": metadata, "position": self.position_us}
async def execute(self, action: str, value: Any) -> None:
"""Exécute une commande validée sur le lecteur."""
player = self._player
match action:
case "play_pause":
await player.call_play_pause()
case "play":
await player.call_play()
case "pause":
await player.call_pause()
case "stop":
await player.call_stop()
case "next":
await player.call_next()
case "previous":
await player.call_previous()
case "seek":
# Décalage relatif en microsecondes
await player.call_seek(int(_require_number(value)))
case "set_position":
trackid = self.state.get("metadata", {}).get("trackid")
if not isinstance(trackid, str) or not trackid.startswith("/"):
raise ValueError("player does not expose a valid trackid")
await player.call_set_position(trackid, max(0, int(_require_number(value))))
case "set_volume":
volume = min(1.0, max(0.0, float(_require_number(value))))
await self._props.call_set(PLAYER_IFACE, "Volume", Variant("d", volume))
case "shuffle":
if not isinstance(value, bool):
raise ValueError("shuffle expects a boolean")
await self._props.call_set(PLAYER_IFACE, "Shuffle", Variant("b", value))
case "loop":
if value not in _LOOP_VALUES:
raise ValueError(f"loop expects one of {_LOOP_VALUES}")
await self._props.call_set(PLAYER_IFACE, "LoopStatus", Variant("s", value))
case "raise":
await self._root.call_raise()
case _:
raise ValueError(f"unknown player action '{action}'")
if action in {"seek", "set_position"}:
await self.refresh_position()
def _require_number(value: Any) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError("numeric value expected")
return float(value)
class MprisManager:
"""Découvre les lecteurs, suit leurs changements et notifie le serveur."""
def __init__(self, bus: MessageBus, on_change: Callable[[], None]) -> None:
self._bus = bus
self._on_change = on_change
self._players: dict[str, Player] = {}
self._pending: dict[str, asyncio.Task[None]] = {}
async def start(self) -> None:
introspection = await self._bus.introspect("org.freedesktop.DBus", "/org/freedesktop/DBus")
proxy = self._bus.get_proxy_object("org.freedesktop.DBus", "/org/freedesktop/DBus", introspection)
dbus: Any = proxy.get_interface("org.freedesktop.DBus")
dbus.on_name_owner_changed(self._on_name_owner_changed)
for name in await dbus.call_list_names():
if name.startswith(MPRIS_PREFIX):
await self._add(name)
def _on_name_owner_changed(self, name: str, old_owner: str, new_owner: str) -> None:
if not name.startswith(MPRIS_PREFIX):
return
if old_owner and name in self._players:
self._remove(name)
if new_owner:
# Laisse le lecteur publier son objet avant l'introspection
self._schedule(name, self._add(name, delay=0.3))
def _schedule(self, name: str, coro: Any) -> None:
previous = self._pending.pop(name, None)
if previous is not None:
previous.cancel()
task = asyncio.create_task(coro)
self._pending[name] = task
def on_done(done: asyncio.Task[None]) -> None:
# Ne retire que la tâche courante, pas une remplaçante plus récente
if self._pending.get(name) is done:
del self._pending[name]
task.add_done_callback(on_done)
async def _add(self, name: str, delay: float = 0.0) -> None:
if delay:
await asyncio.sleep(delay)
try:
introspection = await self._bus.introspect(name, MPRIS_PATH)
proxy = self._bus.get_proxy_object(name, MPRIS_PATH, introspection)
root: Any = proxy.get_interface(ROOT_IFACE)
player_iface: Any = proxy.get_interface(PLAYER_IFACE)
props: Any = proxy.get_interface(PROPS_IFACE)
except Exception as exc: # noqa: BLE001 - lecteur au D-Bus défaillant
log.warning("cannot attach MPRIS player %s: %s", name, exc)
return
player = Player(name, root, player_iface, props)
def on_properties_changed(interface: str, _changed: dict[str, Any], _invalidated: list[str]) -> None:
if interface in (PLAYER_IFACE, ROOT_IFACE):
self._schedule(name, self._refresh(player))
def on_seeked(position: int) -> None:
player.position_us = int(position)
player.position_stamp = asyncio.get_running_loop().time()
self._on_change()
props.on_properties_changed(on_properties_changed)
# dbus-next ne génère on_seeked que si le signal figure dans l'introspection :
# certains lecteurs (navigateurs) ne le déclarent pas, la position est alors relue à la demande
subscribe_seeked = getattr(player_iface, "on_seeked", None)
if subscribe_seeked is not None:
subscribe_seeked(on_seeked)
else:
log.debug("MPRIS player %s does not declare the Seeked signal", name)
try:
await player.refresh()
except Exception as exc: # noqa: BLE001
log.warning("cannot read MPRIS player %s: %s", name, exc)
return
self._players[name] = player
log.info("MPRIS player added: %s", name)
self._on_change()
async def _refresh(self, player: Player) -> None:
# Regroupe les rafales de PropertiesChanged
await asyncio.sleep(0.05)
try:
await player.refresh()
except Exception as exc: # noqa: BLE001
log.debug("refresh failed for %s: %s", player.bus_name, exc)
return
self._on_change()
def _remove(self, name: str) -> None:
self._players.pop(name, None)
log.info("MPRIS player removed: %s", name)
self._on_change()
def get(self, name: str) -> Player:
player = self._players.get(name)
if player is None:
raise ValueError(f"unknown player '{name}'")
return player
def active_name(self) -> str | None:
"""Lecteur par défaut : celui en lecture, sinon en pause, sinon le premier."""
for status in ("Playing", "Paused"):
for name, player in self._players.items():
if player.state.get("status") == status:
return name
return next(iter(self._players), None)
async def snapshot(self) -> dict[str, Any]:
players = []
for player in list(self._players.values()):
if player.state.get("status") == "Playing":
await player.refresh_position()
players.append(player.snapshot(art_path(player)))
return {"players": players, "active": self.active_name()}
def art_path(player: Player) -> str | None:
"""Chemin exposé au client pour la pochette.
Les pochettes locales (file://) passent par /art ; les URL http(s) sont
servies directement au client ; les autres schémas sont ignorés.
"""
url = player.art_url
if url is None:
return None
if url.startswith(("http://", "https://")):
return url
if url.startswith("file://"):
# Le hash force le rechargement du cache navigateur à chaque changement
digest = hashlib.sha1(url.encode()).hexdigest()[:12]
return f"/art?player={player.bus_name}&v={digest}"
return None
+278
View File
@@ -0,0 +1,278 @@
"""Serveur HTTP + WebSocket : diffuse l'état et relaie les commandes de la tablette."""
from __future__ import annotations
import asyncio
import hmac
import json
import logging
import mimetypes
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlparse
from aiohttp import WSMsgType, web
from dbus_next.aio.message_bus import MessageBus
from . import __version__
from .admin import AdminApi
from .audio import AudioManager
from .config import Config
from .input import VirtualInput
from .keymap import LayoutSpec, current_layout
from .launchers import LauncherStore
from .mpris import MprisManager
from .system import SystemControl
from .text import TextTyper
log = logging.getLogger(__name__)
WEB_DIR = Path(__file__).resolve().parent / "web"
MAX_ART_BYTES = 10 * 1024 * 1024
MAX_MESSAGE_BYTES = 4096
STATE_REFRESH_SECONDS = 10.0
CSP = (
"default-src 'self'; img-src 'self' https: http: data:; "
"connect-src 'self' ws: wss:; style-src 'self'; script-src 'self'; "
"base-uri 'none'; frame-ancestors 'none'"
)
class MediaDeckServer:
def __init__(self, config: Config) -> None:
self._config = config
self._clients: set[web.WebSocketResponse] = set()
self._broadcast_task: asyncio.Task[None] | None = None
self._background: list[asyncio.Task[None]] = []
self._bus: MessageBus | None = None
self.mpris: MprisManager | None = None
self.audio = AudioManager(config.max_volume, self.notify)
self.input = VirtualInput(config.enable_input)
self.text = TextTyper(self.input, config.enable_text_input, self._keyboard_layout)
self.system: SystemControl | None = None
self.launchers = LauncherStore()
imported = self.launchers.seed(config.launchers)
if imported:
log.info("imported %d launcher(s) from the config file; manage them on /admin", imported)
elif config.launchers:
log.info("[[launchers]] of the config file are ignored (already imported): manage them on /admin")
# ------------------------------------------------------------------
# Cycle de vie
# ------------------------------------------------------------------
async def on_startup(self, _app: web.Application) -> None:
try:
self._bus = await MessageBus().connect()
self.mpris = MprisManager(self._bus, self.notify)
await self.mpris.start()
self.system = SystemControl(
self._bus, self.launchers, self._config.enable_power, self._config.admin_enabled
)
await self.system.start()
except Exception as exc: # noqa: BLE001 - lancé hors session graphique
log.error("D-Bus session bus unavailable, MPRIS and system control disabled: %s", exc)
await self.audio.start()
self._background.append(asyncio.create_task(self._periodic_state()))
async def on_shutdown(self, _app: web.Application) -> None:
for task in self._background:
task.cancel()
await self.audio.stop()
for client in list(self._clients):
await client.close(code=1001, message=b"server shutdown")
self.text.close()
self.input.close()
self.launchers.close()
if self._bus is not None:
self._bus.disconnect()
async def _keyboard_layout(self) -> LayoutSpec:
# Disposition active du PC, relue à chaque saisie (KDE peut basculer AZERTY/QWERTY)
return await current_layout(self._bus)
def build_app(self) -> web.Application:
app = web.Application(middlewares=[security_headers])
app.on_startup.append(self.on_startup)
app.on_shutdown.append(self.on_shutdown)
app.router.add_get("/", self.index)
app.router.add_get("/ws", self.websocket)
app.router.add_get("/art", self.art)
if self._config.admin_enabled:
app.router.add_get("/admin", self.admin_page)
AdminApi(self._config, self.launchers, self.notify).add_routes(app)
if self._config.tls_ca is not None:
app.router.add_get("/ca.crt", self.ca_certificate)
app.router.add_static("/static", WEB_DIR / "static", show_index=False, follow_symlinks=False)
return app
# ------------------------------------------------------------------
# Authentification
# ------------------------------------------------------------------
def _authorized(self, request: web.Request) -> bool:
token = request.query.get("token", "")
return hmac.compare_digest(token.encode(), self._config.token.encode())
# ------------------------------------------------------------------
# Routes HTTP
# ------------------------------------------------------------------
async def index(self, _request: web.Request) -> web.StreamResponse:
# La page elle-même est publique : le jeton protège /ws et /art
return web.FileResponse(WEB_DIR / "index.html")
async def admin_page(self, _request: web.Request) -> web.StreamResponse:
# Page publique comme l'index : l'API /api/* exige le jeton (en-tête Authorization)
return web.FileResponse(WEB_DIR / "admin.html")
async def ca_certificate(self, _request: web.Request) -> web.StreamResponse:
"""Certificat public de la CA locale, à installer une fois sur la tablette."""
ca = self._config.tls_ca
if ca is None or not ca.is_file():
raise web.HTTPNotFound()
return web.FileResponse(
ca,
headers={
"Content-Type": "application/x-x509-ca-cert",
"Content-Disposition": 'attachment; filename="mediadeck-ca.crt"',
},
)
async def art(self, request: web.Request) -> web.StreamResponse:
"""Sert la pochette locale (file://) du lecteur demandé, et rien d'autre."""
if not self._authorized(request):
raise web.HTTPUnauthorized()
if self.mpris is None:
raise web.HTTPNotFound()
try:
player = self.mpris.get(request.query.get("player", ""))
except ValueError as exc:
raise web.HTTPNotFound() from exc
url = player.art_url
if url is None or not url.startswith("file://"):
raise web.HTTPNotFound()
path = Path(unquote(urlparse(url).path))
mime, _ = mimetypes.guess_type(path.name)
# Seuls les fichiers image réguliers sont servis
if mime is None or not mime.startswith("image/") or not path.is_file():
raise web.HTTPNotFound()
if path.stat().st_size > MAX_ART_BYTES:
raise web.HTTPRequestEntityTooLarge(MAX_ART_BYTES, path.stat().st_size)
return web.FileResponse(path, headers={"Cache-Control": "private, max-age=3600"})
# ------------------------------------------------------------------
# WebSocket
# ------------------------------------------------------------------
async def websocket(self, request: web.Request) -> web.StreamResponse:
if not self._authorized(request):
raise web.HTTPUnauthorized()
ws = web.WebSocketResponse(heartbeat=20, max_msg_size=MAX_MESSAGE_BYTES)
await ws.prepare(request)
self._clients.add(ws)
log.info("client connected: %s (%d total)", request.remote, len(self._clients))
try:
await ws.send_json(await self.state())
async for message in ws:
if message.type == WSMsgType.TEXT:
await self._handle(ws, message.data)
elif message.type == WSMsgType.ERROR:
log.debug("websocket error: %s", ws.exception())
finally:
self._clients.discard(ws)
log.info("client disconnected: %s", request.remote)
return ws
async def _handle(self, ws: web.WebSocketResponse, raw: str) -> None:
try:
message = json.loads(raw)
if not isinstance(message, dict):
raise ValueError("message must be an object")
await self._dispatch(message)
except Exception as exc: # noqa: BLE001 - toute erreur est renvoyée au client
log.debug("command failed: %s", exc)
await ws.send_json({"type": "error", "message": str(exc)})
async def _dispatch(self, message: dict[str, Any]) -> None:
domain = message.get("domain")
action = message.get("action")
if not isinstance(action, str):
raise ValueError("missing action")
match domain:
case "player":
if self.mpris is None:
raise RuntimeError("MPRIS unavailable")
player_name = message.get("player")
if not isinstance(player_name, str):
raise ValueError("missing player")
await self.mpris.get(player_name).execute(action, message.get("value"))
case "audio":
await self.audio.execute(action, message.get("sink"), message.get("value"))
case "input":
if action == "text":
await self.text.type(message.get("text"))
else:
self.input.execute(action, message)
case "system":
if self.system is None:
raise RuntimeError("system control unavailable")
await self.system.execute(action, message)
case "ping":
return
case _:
raise ValueError(f"unknown domain '{domain}'")
# ------------------------------------------------------------------
# Diffusion de l'état
# ------------------------------------------------------------------
async def state(self) -> dict[str, Any]:
mpris_state: dict[str, Any] = {"players": [], "active": None, "available": False}
if self.mpris is not None:
mpris_state = {**await self.mpris.snapshot(), "available": True}
system_state = self.system.snapshot() if self.system else {"power": False, "admin": self._config.admin_enabled, "launchers": []}
return {
"type": "state",
"version": __version__,
"mpris": mpris_state,
"audio": self.audio.snapshot(),
"input": {**self.input.snapshot(), "text": self.text.snapshot()},
"system": system_state,
}
def notify(self) -> None:
"""Planifie une diffusion groupée (anti-rebond 100 ms)."""
if not self._clients:
return
if self._broadcast_task is not None and not self._broadcast_task.done():
return
self._broadcast_task = asyncio.create_task(self._broadcast(delay=0.1))
async def _broadcast(self, delay: float = 0.0) -> None:
if delay:
await asyncio.sleep(delay)
if not self._clients:
return
payload = json.dumps(await self.state())
for client in list(self._clients):
try:
await client.send_str(payload)
except ConnectionResetError:
self._clients.discard(client)
async def _periodic_state(self) -> None:
# Recale régulièrement la position de lecture interpolée côté client
while True:
await asyncio.sleep(STATE_REFRESH_SECONDS)
await self._broadcast()
@web.middleware
async def security_headers(request: web.Request, handler: Any) -> web.StreamResponse:
response: web.StreamResponse = await handler(request)
response.headers.setdefault("Content-Security-Policy", CSP)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("Referrer-Policy", "no-referrer")
return response
+99
View File
@@ -0,0 +1,99 @@
"""Actions système : alimentation (logind), verrouillage (ScreenSaver) et lanceurs."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
from dbus_next.constants import BusType
from dbus_next.aio.message_bus import MessageBus
from .launchers import LauncherStore, build_argv
log = logging.getLogger(__name__)
LOGIND_NAME = "org.freedesktop.login1"
LOGIND_PATH = "/org/freedesktop/login1"
LOGIND_IFACE = "org.freedesktop.login1.Manager"
# Méthodes logind : l'argument booléen « interactive » vaut False (pas de prompt polkit)
_POWER_METHODS = {"suspend": "call_suspend", "reboot": "call_reboot", "poweroff": "call_power_off"}
class SystemControl:
def __init__(
self, session_bus: MessageBus, launchers: LauncherStore, enable_power: bool, admin_enabled: bool
) -> None:
self._session_bus = session_bus
self._launchers = launchers
self._enable_power = enable_power
self._admin_enabled = admin_enabled
self._logind: Any = None
self._processes: set[asyncio.subprocess.Process] = set()
async def start(self) -> None:
if not self._enable_power:
return
try:
system_bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
introspection = await system_bus.introspect(LOGIND_NAME, LOGIND_PATH)
proxy = system_bus.get_proxy_object(LOGIND_NAME, LOGIND_PATH, introspection)
self._logind = proxy.get_interface(LOGIND_IFACE)
except Exception as exc: # noqa: BLE001 - pas de bus système (conteneur, etc.)
log.warning("logind unavailable, power actions disabled: %s", exc)
def snapshot(self) -> dict[str, Any]:
return {
"power": self._logind is not None,
"admin": self._admin_enabled,
"launchers": [
{"id": launcher.id, "label": launcher.label, "icon": launcher.icon}
for launcher in self._launchers.list()
],
}
async def execute(self, action: str, payload: dict[str, Any]) -> None:
match action:
case "power":
await self._power(payload.get("kind"))
case "lock":
await self._lock()
case "launch":
await self._launch(payload.get("id"))
case _:
raise ValueError(f"unknown system action '{action}'")
async def _power(self, kind: Any) -> None:
if self._logind is None:
raise RuntimeError("power actions unavailable")
if kind not in _POWER_METHODS:
raise ValueError("unknown power action")
log.info("power action requested: %s", kind)
await getattr(self._logind, _POWER_METHODS[kind])(False)
async def _lock(self) -> None:
# Interface freedesktop implémentée par KDE (ksmserver) et GNOME
introspection = await self._session_bus.introspect("org.freedesktop.ScreenSaver", "/ScreenSaver")
proxy = self._session_bus.get_proxy_object("org.freedesktop.ScreenSaver", "/ScreenSaver", introspection)
screensaver: Any = proxy.get_interface("org.freedesktop.ScreenSaver")
await screensaver.call_lock()
async def _launch(self, launcher_id: Any) -> None:
launcher = self._launchers.get(launcher_id) if isinstance(launcher_id, str) else None
if launcher is None:
raise ValueError("unknown launcher")
command = build_argv(launcher)
log.info("launching %s: %s", launcher.id, command)
# Session séparée : le programme survit à un redémarrage du service
process = await asyncio.create_subprocess_exec(
*command,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
start_new_session=True,
)
# Récupère le code de retour pour éviter les zombies
self._processes.add(process)
task = asyncio.create_task(process.wait())
task.add_done_callback(lambda _t: self._processes.discard(process))
+119
View File
@@ -0,0 +1,119 @@
"""Saisie de texte depuis la tablette : chaque caractère devient les touches d'un vrai clavier.
Le texte passe par le clavier virtuel uinput, traduit selon la disposition active du PC (keymap.py) : aucun
presse-papiers n'est touché, donc rien n'est conservé dans l'historique de Klipper, mots de passe compris.
"""
from __future__ import annotations
import asyncio
import logging
from collections.abc import Awaitable, Callable
from typing import Any, Protocol
from .keymap import Keymap, KeymapError, LayoutSpec, Stroke, current_layout, load_xkb
log = logging.getLogger(__name__)
# 500 caractères de 4 octets (emoji) = 2 Ko, sous la limite de 4 Ko d'un message WebSocket (qui coupe la connexion)
MAX_TEXT_LENGTH = 500
# Pause entre deux phases d'une frappe, pour que le serveur graphique les voie dans l'ordre
STROKE_DELAY = 0.004
MAX_REPORTED = 10
LayoutProvider = Callable[[], Awaitable[LayoutSpec]]
class KeyWriter(Protocol):
"""Ce dont la saisie a besoin du clavier virtuel (VirtualInput, ou un faux dans les tests)."""
@property
def available(self) -> bool: ...
@property
def reason(self) -> str: ...
def write_keys(self, events: list[tuple[int, bool]]) -> None: ...
class TextTyper:
def __init__(
self,
keyboard: KeyWriter,
enabled: bool,
layout: LayoutProvider | None = None,
delay: float = STROKE_DELAY,
) -> None:
self._keyboard = keyboard
self._layout: LayoutProvider = layout or (lambda: current_layout(None))
self._delay = delay
self._keymaps: dict[LayoutSpec, Keymap] = {}
self._lock = asyncio.Lock()
self.reason = ""
if not enabled:
self.reason = "disabled in config (features.text_input)"
return
if not keyboard.available:
self.reason = keyboard.reason or "virtual input unavailable"
return
try:
load_xkb()
except KeymapError as exc:
self.reason = str(exc)
@property
def available(self) -> bool:
return not self.reason
def snapshot(self) -> dict[str, Any]:
return {"available": self.available, "reason": self.reason}
async def _keymap(self) -> Keymap:
# La disposition peut changer en cours de route (bascule AZERTY/QWERTY) : relue à chaque saisie
spec = await self._layout()
keymap = self._keymaps.get(spec)
if keymap is None:
keymap = await asyncio.to_thread(Keymap, spec)
self._keymaps[spec] = keymap
log.info("keyboard layout for text entry: %s", spec)
return keymap
async def _press(self, stroke: Stroke, keymap: Keymap) -> None:
modifiers: list[int] = []
if stroke.shift and keymap.shift_code is not None:
modifiers.append(keymap.shift_code)
if stroke.altgr and keymap.altgr_code is not None:
modifiers.append(keymap.altgr_code)
self._keyboard.write_keys([*((code, True) for code in modifiers), (stroke.code, True)])
try:
await asyncio.sleep(self._delay)
finally:
# Même si la connexion est coupée en pleine saisie, aucune touche ne reste enfoncée
self._keyboard.write_keys([(stroke.code, False), *((code, False) for code in reversed(modifiers))])
await asyncio.sleep(self._delay)
async def type(self, text: Any) -> None:
if not self.available:
raise RuntimeError(f"text entry unavailable: {self.reason}")
if not isinstance(text, str) or not text:
raise ValueError("text must be a non-empty string")
if len(text) > MAX_TEXT_LENGTH:
raise ValueError(f"text too long (maximum {MAX_TEXT_LENGTH} characters)")
# Une seule saisie à la fois : deux textes envoyés coup sur coup ne doivent pas s'entremêler
async with self._lock:
try:
keymap = await self._keymap()
except KeymapError as exc:
raise RuntimeError(str(exc)) from exc
strokes, skipped = keymap.plan(text)
log.info("typing %d character(s) as %d key stroke(s)", len(text), len(strokes))
for stroke in strokes:
await self._press(stroke, keymap)
if skipped:
shown = "".join(skipped[:MAX_REPORTED])
raise ValueError(f"characters not available on the PC keyboard layout, skipped: {shown}")
def close(self) -> None:
for keymap in self._keymaps.values():
keymap.close()
self._keymaps.clear()
+185
View File
@@ -0,0 +1,185 @@
"""HTTPS local : autorité de certification privée, certificat serveur et contexte TLS.
La tablette fait confiance à la CA : celle-ci est donc limitée (nameConstraints) aux réseaux
privés et aux noms locaux, pour qu'une fuite de sa clé ne permette pas d'usurper un site public.
"""
from __future__ import annotations
import ipaddress
import json
import re
import socket
import ssl
import subprocess
import tempfile
from collections.abc import Iterable
from pathlib import Path
from .config import CONFIG_DIR, Config, ConfigError
TLS_DIR = CONFIG_DIR / "tls"
CA_KEY = "ca.key"
CA_CERT = "mediadeck-ca.crt"
SERVER_KEY = "server.key"
SERVER_CERT = "server.pem"
CA_DAYS = 3650
SERVER_DAYS = 825
# Plages que la CA a le droit de signer (voir nameConstraints)
_PRIVATE_NETWORKS = (
ipaddress.ip_network("127.0.0.0/8"),
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("172.16.0.0/12"),
ipaddress.ip_network("192.168.0.0/16"),
)
_LOCAL_SUFFIXES = (".local", ".lan")
def _is_ip(host: str) -> bool:
try:
ipaddress.ip_address(host)
except ValueError:
return False
return True
def is_permitted(host: str, hostname: str) -> bool:
"""Indique si la CA peut signer ce nom (miroir des nameConstraints de la CA)."""
try:
address = ipaddress.ip_address(host)
except ValueError:
name = host.lower()
return name in ("localhost", hostname.lower()) or name.endswith(_LOCAL_SUFFIXES)
return any(address in network for network in _PRIVATE_NETWORKS)
def default_hosts(advertised: str) -> list[str]:
"""Noms et adresses inscrits dans le certificat serveur, sans doublon."""
hostname = socket.gethostname()
hosts = [advertised, hostname, f"{hostname}.local", "localhost", "127.0.0.1"]
return list(dict.fromkeys(host for host in hosts if host))
def _openssl(*args: str | Path) -> None:
try:
subprocess.run(["openssl", *map(str, args)], check=True, capture_output=True, text=True)
except FileNotFoundError as exc:
raise ConfigError("openssl not found (apt install openssl)") from exc
except subprocess.CalledProcessError as exc:
# openssl verify écrit ses diagnostics sur stdout, les autres commandes sur stderr
raise ConfigError(f"openssl {args[0]} failed: {(exc.stderr or exc.stdout).strip()}") from exc
def _generate_key(path: Path) -> None:
_openssl("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", path)
path.chmod(0o600)
def _req_config(common_name: str, extensions: str = "") -> str:
return (
"[req]\ndistinguished_name = dn\nprompt = no\nx509_extensions = ext\n"
f"[dn]\nCN = {common_name}\n[ext]\n{extensions}"
)
def _create_ca(directory: Path, hostname: str) -> None:
constraints = [f"permitted;IP:{net.network_address}/{net.netmask}" for net in _PRIVATE_NETWORKS]
names = ["localhost", hostname, *_LOCAL_SUFFIXES]
constraints += [f"permitted;DNS:{name}" for name in names]
extensions = (
"basicConstraints = critical, CA:TRUE, pathlen:0\n"
"keyUsage = critical, keyCertSign, cRLSign\n"
"subjectKeyIdentifier = hash\n"
f"nameConstraints = critical, {', '.join(constraints)}\n"
)
label = re.sub(r"[^A-Za-z0-9.-]", "", hostname)
key = directory / CA_KEY
with tempfile.TemporaryDirectory() as tmp:
conf = Path(tmp) / "ca.cnf"
conf.write_text(_req_config(f"MediaDeck local CA {label}", extensions))
_generate_key(key)
_openssl(
"req", "-new", "-x509", "-key", key, "-sha256", "-days", str(CA_DAYS),
"-config", conf, "-out", directory / CA_CERT,
)
def _issue_server_cert(directory: Path, hosts: Iterable[str]) -> None:
san = ", ".join(f"{'IP' if _is_ip(host) else 'DNS'}:{host}" for host in hosts)
extensions = (
"basicConstraints = critical, CA:FALSE\n"
"keyUsage = critical, digitalSignature\n"
"extendedKeyUsage = serverAuth\n"
"subjectKeyIdentifier = hash\n"
"authorityKeyIdentifier = keyid\n"
f"subjectAltName = {san}\n"
)
key = directory / SERVER_KEY
with tempfile.TemporaryDirectory() as tmp:
conf = Path(tmp) / "server.cnf"
csr = Path(tmp) / "server.csr"
conf.write_text(_req_config("MediaDeck", extensions))
_generate_key(key)
_openssl("req", "-new", "-key", key, "-config", conf, "-out", csr)
_openssl(
"x509", "-req", "-in", csr, "-CA", directory / CA_CERT, "-CAkey", directory / CA_KEY,
"-CAcreateserial", "-CAserial", Path(tmp) / "ca.srl", "-days", str(SERVER_DAYS),
"-sha256", "-extfile", conf, "-extensions", "ext", "-out", directory / SERVER_CERT,
)
# Garde-fou : la CA existante doit couvrir ces noms (le nom de la machine a pu changer)
try:
_openssl("verify", "-CAfile", directory / CA_CERT, directory / SERVER_CERT)
except ConfigError as exc:
raise ConfigError(f"{exc}; delete {directory} to recreate the CA, then rerun 'make cert'") from exc
def generate_certificates(directory: Path, hosts: list[str]) -> tuple[Path, Path, Path]:
"""Crée la CA si besoin puis (ré)émet le certificat serveur ; renvoie (CA, certificat, clé)."""
hostname = socket.gethostname()
refused = [host for host in hosts if not is_permitted(host, hostname)]
if refused:
raise ConfigError(
f"the local CA can only sign private addresses and .local/.lan names, not: {', '.join(refused)}"
)
directory.mkdir(parents=True, exist_ok=True)
directory.chmod(0o700)
if not (directory / CA_KEY).exists() or not (directory / CA_CERT).exists():
_create_ca(directory, hostname)
_issue_server_cert(directory, hosts)
return directory / CA_CERT, directory / SERVER_CERT, directory / SERVER_KEY
def enable_tls(config_path: Path, cert: Path, key: Path, ca: Path) -> bool:
"""Déclare le certificat dans [server] ; renvoie False si la configuration le faisait déjà."""
text = config_path.read_text()
if re.search(r"(?m)^\s*tls_cert\s*=", text):
return False
lines = "".join(
f"\n{name} = {json.dumps(str(path))}" for name, path in (("tls_cert", cert), ("tls_key", key), ("tls_ca", ca))
)
updated, count = re.subn(r"(?m)^port\s*=.*$", lambda match: match.group(0) + lines, text, count=1)
if count == 0:
raise ConfigError(f"no 'port' line found in {config_path}: add tls_cert, tls_key and tls_ca manually")
config_path.write_text(updated)
return True
def build_ssl_context(config: Config) -> ssl.SSLContext | None:
"""Contexte TLS serveur, ou None si HTTPS n'est pas configuré."""
if config.tls_cert is None or config.tls_key is None:
return None
for label, path in (("tls_cert", config.tls_cert), ("tls_key", config.tls_key), ("tls_ca", config.tls_ca)):
if path is not None and not path.is_file():
raise ConfigError(f"server.{label}: file not found: {path} (run 'make cert')")
# Même règle que pour le fichier de configuration : la clé privée reste personnelle
if config.tls_key.stat().st_mode & 0o077:
raise ConfigError(f"{config.tls_key} must not be readable by group/others (chmod 600)")
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.minimum_version = ssl.TLSVersion.TLSv1_2
try:
context.load_cert_chain(config.tls_cert, config.tls_key)
except (ssl.SSLError, OSError) as exc:
raise ConfigError(f"cannot load TLS certificate {config.tls_cert}: {exc}") from exc
return context
+98
View File
@@ -0,0 +1,98 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0e0f13">
<title>MediaDeck – Lanceurs</title>
<link rel="icon" href="/static/icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/style.css">
<link rel="stylesheet" href="/static/admin.css">
<script type="module" src="/static/admin.js"></script>
</head>
<body class="admin">
<header class="admin-bar">
<a class="chip" href="/" data-i18n="admin.back"></a>
<h1 data-i18n="admin.title"></h1>
<button class="chip" id="lang-toggle" type="button">EN</button>
</header>
<main class="admin-main">
<p class="sub" data-i18n="admin.help"></p>
<p class="banner" id="admin-error" role="alert" hidden></p>
<ul class="admin-list" id="admin-list"></ul>
<p class="sub" id="admin-empty" data-i18n="admin.empty" hidden></p>
<button class="primary" id="admin-add" type="button" data-i18n="admin.add"></button>
</main>
<dialog id="launcher-dialog" aria-labelledby="form-title">
<form id="launcher-form" novalidate>
<h2 id="form-title"></h2>
<label class="field">
<span data-i18n="form.label"></span>
<input id="form-label" type="text" maxlength="40" required autocomplete="off">
</label>
<div class="field-row">
<label class="field">
<span data-i18n="form.icon"></span>
<select id="form-icon"></select>
</label>
<label class="field">
<span data-i18n="form.kind"></span>
<select id="form-kind"></select>
</label>
</div>
<div data-group="web">
<label class="field">
<span data-i18n="form.url"></span>
<input id="form-url" type="url" inputmode="url" autocomplete="off" placeholder="https://">
</label>
<label class="field">
<span data-i18n="form.browser"></span>
<select id="form-browser"></select>
</label>
<label class="check">
<input id="form-fullscreen" type="checkbox">
<span data-i18n="form.fullscreen"></span>
</label>
<p class="sub" id="form-fullscreen-hint" data-i18n="form.fullscreen_unavailable" hidden></p>
</div>
<div data-group="app" hidden>
<label class="field">
<span data-i18n="form.app"></span>
<input id="form-app-filter" type="search" autocomplete="off" data-i18n-placeholder="form.app_filter">
</label>
<select id="form-app" size="8" aria-label="Applications"></select>
<p class="sub" id="form-apps-empty" data-i18n="form.apps_empty" hidden></p>
</div>
<div data-group="command" hidden>
<label class="field">
<span data-i18n="form.command"></span>
<textarea id="form-command" rows="5" spellcheck="false" autocapitalize="off" autocomplete="off"></textarea>
</label>
<p class="sub" id="form-command-hint" data-i18n="form.command_help"></p>
</div>
<p class="banner" id="form-error" role="alert" hidden></p>
<div class="form-actions">
<button class="chip" id="form-cancel" type="button" data-i18n="form.cancel"></button>
<button class="primary" type="submit" data-i18n="form.save"></button>
</div>
</form>
</dialog>
<div class="overlay" id="no-token" hidden>
<h1 data-i18n="token.title"></h1>
<p data-i18n="admin.token_help"></p>
<a class="chip" href="/" data-i18n="admin.back"></a>
</div>
</body>
</html>
+256
View File
@@ -0,0 +1,256 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
<meta name="theme-color" content="#0e0f13">
<meta name="mobile-web-app-capable" content="yes">
<title>MediaDeck</title>
<link rel="manifest" href="/static/manifest.webmanifest">
<link rel="icon" href="/static/icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/style.css">
<script type="module" src="/static/app.js"></script>
</head>
<body>
<!-- Sprite d'icônes : référencé par <use href="#i-..."> -->
<svg class="sprite" aria-hidden="true">
<symbol id="i-play" viewBox="0 0 24 24"><path d="M8 5.5v13l10.5-6.5z" fill="currentColor"/></symbol>
<symbol id="i-pause" viewBox="0 0 24 24"><path d="M7 5h3.5v14H7zM13.5 5H17v14h-3.5z" fill="currentColor"/></symbol>
<symbol id="i-next" viewBox="0 0 24 24"><path d="M6 6l8.5 6L6 18zM16 6h2.5v12H16z" fill="currentColor"/></symbol>
<symbol id="i-prev" viewBox="0 0 24 24"><path d="M18 6l-8.5 6 8.5 6zM5.5 6H8v12H5.5z" fill="currentColor"/></symbol>
<symbol id="i-shuffle" viewBox="0 0 24 24"><path d="M4 7h3.5c2 0 3 1 4.5 3.5S14.5 17 16.5 17H20M17 14l3 3-3 3M4 17h3.5c1.2 0 2-.4 2.8-1.3M14 8.3c.8-.9 1.6-1.3 2.5-1.3H20M17 4l3 3-3 3" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-loop" viewBox="0 0 24 24"><path d="M17 3l3 3-3 3M4 11V9a3 3 0 0 1 3-3h13M7 21l-3-3 3-3M20 13v2a3 3 0 0 1-3 3H4" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-volume" viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z" fill="currentColor"/><path d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></symbol>
<symbol id="i-mute" viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z" fill="currentColor"/><path d="M16 9.5l5 5M21 9.5l-5 5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></symbol>
<symbol id="i-music" viewBox="0 0 24 24"><path d="M9 18V5.5l11-2V16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><circle cx="6.5" cy="18" r="2.5" fill="currentColor"/><circle cx="17.5" cy="16" r="2.5" fill="currentColor"/></symbol>
<symbol id="i-speaker" viewBox="0 0 24 24"><rect x="6" y="3" width="12" height="18" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="12" cy="14.5" r="3" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="12" cy="7" r="1.2" fill="currentColor"/></symbol>
<symbol id="i-touch" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="13" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M9 20.5h6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></symbol>
<symbol id="i-power" viewBox="0 0 24 24"><path d="M12 3.5v8M7 6.5a7 7 0 1 0 10 0" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/></symbol>
<symbol id="i-lock" viewBox="0 0 24 24"><rect x="5" y="10.5" width="14" height="10" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5" fill="none" stroke="currentColor" stroke-width="1.8"/></symbol>
<symbol id="i-moon" viewBox="0 0 24 24"><path d="M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></symbol>
<symbol id="i-restart" viewBox="0 0 24 24"><path d="M4.5 12a7.5 7.5 0 1 0 2.2-5.3M4.5 4v4.5H9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-app" viewBox="0 0 24 24"><rect x="4" y="4" width="7" height="7" rx="1.5" fill="currentColor"/><rect x="13" y="4" width="7" height="7" rx="1.5" fill="currentColor" opacity=".6"/><rect x="4" y="13" width="7" height="7" rx="1.5" fill="currentColor" opacity=".6"/><rect x="13" y="13" width="7" height="7" rx="1.5" fill="currentColor"/></symbol>
<symbol id="i-tv" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="12" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M8 20.5h8" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></symbol>
<symbol id="i-film" viewBox="0 0 24 24"><rect x="4" y="3.5" width="16" height="17" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M8 3.5v17M16 3.5v17M4 8h4M4 12h4M4 16h4M16 8h4M16 12h4M16 16h4" stroke="currentColor" stroke-width="1.5"/></symbol>
<symbol id="i-globe" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M3.5 12h17M12 3.5c2.5 2.5 3.5 5.5 3.5 8.5s-1 6-3.5 8.5c-2.5-2.5-3.5-5.5-3.5-8.5s1-6 3.5-8.5z" fill="none" stroke="currentColor" stroke-width="1.5"/></symbol>
<symbol id="i-screen-off" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="12" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M3 3l18 18" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></symbol>
<symbol id="i-up" viewBox="0 0 24 24"><path d="M6 15l6-6 6 6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-down" viewBox="0 0 24 24"><path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-left" viewBox="0 0 24 24"><path d="M15 6l-6 6 6 6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-right" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-back" viewBox="0 0 24 24"><path d="M9 7L4 12l5 5M4.5 12H15a5 5 0 0 1 0 10h-2" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-keyboard" viewBox="0 0 24 24"><rect x="2.5" y="6" width="19" height="12" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M6.5 10h.01M10 10h.01M14 10h.01M17.5 10h.01M7.5 14h9" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-expand" viewBox="0 0 24 24"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-window" viewBox="0 0 24 24"><rect x="3.5" y="5" width="17" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M3.5 9h17" stroke="currentColor" stroke-width="1.8"/></symbol>
</svg>
<div class="app" id="app">
<header class="topbar">
<div class="status" id="status" data-state="connecting">
<span class="status-dot"></span>
<span class="status-text" id="status-text" data-i18n="status.connecting"></span>
</div>
<div class="topbar-actions">
<button class="chip" id="lang-toggle" type="button">EN</button>
<button class="icon-btn" id="fullscreen" type="button" data-i18n-label="action.fullscreen">
<svg><use href="#i-expand"/></svg>
</button>
</div>
</header>
<main class="panels">
<!-- Lecture -->
<section class="panel" id="panel-player" data-panel="player">
<div class="empty" id="player-empty">
<svg><use href="#i-music"/></svg>
<p data-i18n="player.none"></p>
</div>
<div class="now-playing" id="player-view" hidden>
<div class="cover" id="cover">
<img id="cover-img" alt="" hidden>
<svg class="cover-fallback"><use href="#i-music"/></svg>
</div>
<div class="track">
<div class="player-tabs" id="player-tabs" role="tablist"></div>
<h1 class="track-title" id="track-title"></h1>
<p class="track-artist" id="track-artist"></p>
<p class="track-album" id="track-album"></p>
<div class="progress">
<input type="range" id="seek" min="0" max="1000" value="0" step="1" data-i18n-label="player.seek">
<div class="times">
<span id="time-pos">0:00</span>
<span id="time-len">0:00</span>
</div>
</div>
<div class="transport">
<button class="icon-btn toggle" id="btn-shuffle" type="button" data-i18n-label="player.shuffle">
<svg><use href="#i-shuffle"/></svg>
</button>
<button class="icon-btn big" id="btn-prev" type="button" data-i18n-label="player.previous">
<svg><use href="#i-prev"/></svg>
</button>
<button class="play-btn" id="btn-play" type="button" data-i18n-label="player.play_pause">
<svg><use id="play-icon" href="#i-play"/></svg>
</button>
<button class="icon-btn big" id="btn-next" type="button" data-i18n-label="player.next">
<svg><use href="#i-next"/></svg>
</button>
<button class="icon-btn toggle" id="btn-loop" type="button" data-i18n-label="player.loop">
<svg><use href="#i-loop"/></svg>
<span class="badge" id="loop-badge" hidden>1</span>
</button>
</div>
<div class="player-extra">
<div class="slider-row" id="player-volume-row" hidden>
<svg><use href="#i-volume"/></svg>
<input type="range" id="player-volume" min="0" max="100" value="0" data-i18n-label="player.volume">
</div>
<button class="chip" id="btn-raise" type="button" hidden>
<svg><use href="#i-window"/></svg>
<span data-i18n="player.raise"></span>
</button>
</div>
</div>
</div>
</section>
<!-- Son -->
<section class="panel" id="panel-audio" data-panel="audio" hidden>
<div class="empty" id="audio-empty" hidden>
<svg><use href="#i-speaker"/></svg>
<p data-i18n="audio.none"></p>
</div>
<div class="audio-view" id="audio-view">
<div class="master">
<button class="mute-btn" id="master-mute" type="button" data-i18n-label="audio.mute">
<svg><use id="master-mute-icon" href="#i-volume"/></svg>
</button>
<div class="master-body">
<div class="master-head">
<span class="label" data-i18n="audio.master"></span>
<span class="value" id="master-value">0 %</span>
</div>
<input type="range" id="master-volume" class="thick" min="0" max="100" value="0" data-i18n-label="audio.master">
<span class="sub" id="master-name"></span>
</div>
</div>
<h2 class="section-title" data-i18n="audio.outputs"></h2>
<ul class="sink-list" id="sink-list"></ul>
</div>
</section>
<!-- Pavé tactile -->
<section class="panel" id="panel-remote" data-panel="remote" hidden>
<div class="empty" id="remote-empty" hidden>
<svg><use href="#i-touch"/></svg>
<p data-i18n="remote.none"></p>
<p class="sub" id="remote-reason"></p>
</div>
<div class="remote-view" id="remote-view">
<div class="touchpad" id="touchpad">
<span class="touchpad-hint" data-i18n="remote.hint"></span>
</div>
<div class="remote-side">
<div class="dpad">
<button class="dpad-btn up" type="button" data-key="up" data-i18n-label="key.up"><svg><use href="#i-up"/></svg></button>
<button class="dpad-btn left" type="button" data-key="left" data-i18n-label="key.left"><svg><use href="#i-left"/></svg></button>
<button class="dpad-btn ok" type="button" data-key="enter">OK</button>
<button class="dpad-btn right" type="button" data-key="right" data-i18n-label="key.right"><svg><use href="#i-right"/></svg></button>
<button class="dpad-btn down" type="button" data-key="down" data-i18n-label="key.down"><svg><use href="#i-down"/></svg></button>
</div>
<div class="key-grid">
<button class="key" type="button" data-key="escape">Esc</button>
<button class="key" type="button" data-key="back"><svg><use href="#i-back"/></svg></button>
<button class="key" type="button" data-key="space" data-i18n="key.space"></button>
<button class="key" type="button" data-key="fullscreen">F</button>
<button class="key" type="button" data-key="f11">F11</button>
<button class="key" type="button" data-key="meta" data-i18n="key.meta"></button>
<button class="key" type="button" data-key="page_up" data-i18n="key.page_up"></button>
<button class="key" type="button" data-key="page_down" data-i18n="key.page_down"></button>
<button class="key" type="button" data-key="tab">Tab</button>
<button class="key wide" type="button" id="text-open">
<svg><use href="#i-keyboard"/></svg><span data-i18n="text.open"></span>
</button>
</div>
</div>
</div>
</section>
<!-- Lanceurs -->
<section class="panel" id="panel-launchers" data-panel="launchers" hidden>
<div class="section-head">
<h2 class="section-title" data-i18n="launchers.title"></h2>
<a class="chip" id="launchers-manage" href="/admin" data-i18n="launchers.manage" hidden></a>
</div>
<div class="launcher-grid" id="launcher-grid"></div>
<p class="sub" id="launchers-empty" data-i18n="launchers.empty" hidden></p>
</section>
<!-- Système : opérations délicates (verrouillage, veille, redémarrage, extinction) -->
<section class="panel" id="panel-system" data-panel="system" hidden>
<h2 class="section-title" data-i18n="system.session"></h2>
<div class="power-grid">
<button class="power-btn" type="button" data-system="lock">
<svg><use href="#i-lock"/></svg><span data-i18n="system.lock"></span>
</button>
<button class="power-btn hold" type="button" data-power="suspend">
<svg><use href="#i-moon"/></svg><span data-i18n="system.suspend"></span>
</button>
<button class="power-btn hold" type="button" data-power="reboot">
<svg><use href="#i-restart"/></svg><span data-i18n="system.reboot"></span>
</button>
<button class="power-btn hold danger" type="button" data-power="poweroff">
<svg><use href="#i-power"/></svg><span data-i18n="system.poweroff"></span>
</button>
</div>
<p class="sub" data-i18n="system.hold_hint"></p>
</section>
</main>
<nav class="tabbar" id="tabbar">
<button class="tab active" type="button" data-tab="player"><svg><use href="#i-music"/></svg><span data-i18n="tab.player"></span></button>
<button class="tab" type="button" data-tab="audio"><svg><use href="#i-speaker"/></svg><span data-i18n="tab.audio"></span></button>
<button class="tab" type="button" data-tab="remote"><svg><use href="#i-touch"/></svg><span data-i18n="tab.remote"></span></button>
<button class="tab" type="button" data-tab="launchers"><svg><use href="#i-app"/></svg><span data-i18n="tab.launchers"></span></button>
<button class="tab" type="button" data-tab="system"><svg><use href="#i-power"/></svg><span data-i18n="tab.system"></span></button>
</nav>
<!-- Saisie de texte : le clavier de la tablette remplit le champ, le PC reçoit des frappes -->
<dialog class="top" id="text-dialog" aria-labelledby="text-title">
<form id="text-form" novalidate>
<h2 id="text-title" data-i18n="text.title"></h2>
<input id="text-input" type="text" maxlength="500" enterkeyhint="send" autocomplete="off"
autocapitalize="off" autocorrect="off" spellcheck="false" data-i18n-placeholder="text.placeholder"
data-i18n-label="text.title">
<label class="check">
<input id="text-mask" type="checkbox">
<span data-i18n="text.mask"></span>
</label>
<div class="quick-keys">
<button class="key" type="button" data-text-key="tab">Tab</button>
<button class="key" type="button" data-text-key="back" data-i18n-label="key.back"><svg><use href="#i-back"/></svg></button>
<button class="key" type="button" data-text-key="enter">↵</button>
</div>
<p class="sub" data-i18n="text.hint"></p>
<div class="form-actions">
<button class="chip" id="text-close" type="button" data-i18n="text.close"></button>
<button class="chip" id="text-send" type="button" data-i18n="text.send"></button>
<button class="primary" type="submit" data-i18n="text.send_enter"></button>
</div>
</form>
</dialog>
<div class="toast" id="toast" role="status" aria-live="polite" hidden></div>
<div class="overlay" id="no-token" hidden>
<svg><use href="#i-lock"/></svg>
<h1 data-i18n="token.title"></h1>
<p data-i18n="token.help"></p>
<code>python -m mediadeck --url</code>
</div>
</div>
</body>
</html>
+99
View File
@@ -0,0 +1,99 @@
/* MediaDeck : page d'administration des lanceurs (complète style.css) */
html,
body.admin {
height: auto;
min-height: 100%;
-webkit-user-select: text;
user-select: text;
overscroll-behavior: auto;
}
.admin-bar {
position: sticky;
top: 0;
z-index: 5;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: calc(12px + env(safe-area-inset-top)) 20px 12px;
background: var(--bg);
border-bottom: 1px solid var(--line);
}
.admin-bar h1 {
margin: 0;
font-size: 18px;
}
.admin-main {
max-width: 760px;
margin: 0 auto;
padding: 16px 20px calc(32px + env(safe-area-inset-bottom));
}
.admin-list {
display: grid;
gap: 12px;
margin: 16px 0;
padding: 0;
list-style: none;
}
.admin-item {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px 16px;
align-items: center;
padding: 14px 16px;
border-radius: var(--radius);
background: var(--surface);
border: 1px solid var(--line);
}
.admin-item-text {
min-width: 0;
}
.admin-item-title {
display: flex;
align-items: center;
gap: 10px;
font-weight: 600;
}
.kind-tag {
padding: 2px 10px;
border-radius: 999px;
background: var(--surface-3);
color: var(--accent);
font-size: 12px;
font-weight: 600;
}
.admin-item .sub {
margin: 4px 0 0;
overflow-wrap: anywhere;
}
.admin-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
}
.chip.danger {
color: var(--danger);
}
@media (max-width: 520px) {
.admin-item {
grid-template-columns: 1fr;
}
.admin-actions {
justify-content: flex-start;
}
}
+555
View File
@@ -0,0 +1,555 @@
// MediaDeck : page d'administration des lanceurs (/admin). Une classe par responsabilité.
import { $, I18n, Storage, STORAGE_TOKEN } from "./common.js";
// ----------------------------------------------------------------------
// Traductions fr/en
// ----------------------------------------------------------------------
const MESSAGES = {
fr: {
"admin.title": "Lanceurs",
"admin.back": "← Télécommande",
"admin.help": "Les lanceurs apparaissent dans l'onglet Lanceurs de la télécommande. Les modifications sont appliquées tout de suite.",
"admin.empty": "Aucun lanceur pour l'instant.",
"admin.add": "Ajouter un lanceur",
"admin.edit": "Modifier",
"admin.delete": "Supprimer",
"admin.up": "Monter",
"admin.down": "Descendre",
"admin.confirm_delete": "Supprimer « {name} » ?",
"admin.token_help": "Ouvrez d'abord la télécommande avec son URL complète (make url), puis revenez sur cette page.",
"token.title": "Jeton d'accès manquant",
"form.add_title": "Nouveau lanceur",
"form.edit_title": "Modifier le lanceur",
"form.label": "Nom",
"form.icon": "Icône",
"form.kind": "Type",
"form.url": "Adresse (URL)",
"form.browser": "Navigateur",
"form.fullscreen": "Démarrer en plein écran",
"form.fullscreen_unavailable": "Indisponible avec ce navigateur (le mode kiosque de Firefox ignore F11).",
"form.not_installed": "{name} (non installé)",
"form.app": "Application",
"form.app_filter": "Filtrer…",
"form.apps_empty": "Aucune application trouvée.",
"form.app_missing": "{id} (introuvable)",
"form.command": "Commande (un argument par ligne)",
"form.command_help": "Pas de shell : chaque ligne est un argument, sans guillemets.",
"form.command_locked": "Commandes brutes désactivées : seuls le nom et l'icône sont modifiables. Pour les autoriser, définir allow_custom_command = true dans la section [admin] de config.toml.",
"form.save": "Enregistrer",
"form.cancel": "Annuler",
"kind.web": "Site web",
"kind.app": "Application installée",
"kind.command": "Commande (avancé)",
"icon.app": "Application",
"icon.tv": "Télévision",
"icon.film": "Film",
"icon.globe": "Web",
"icon.music": "Musique",
"icon.screen-off": "Écran éteint",
"icon.speaker": "Enceinte",
"icon.lock": "Verrou",
"icon.window": "Fenêtre",
"error.auth": "Jeton refusé : rouvrez la télécommande avec son URL complète (make url).",
"error.network": "Serveur injoignable.",
"error.prefix": "Erreur : {message}",
},
en: {
"admin.title": "Launchers",
"admin.back": "← Remote",
"admin.help": "Launchers appear in the Launchers tab of the remote. Changes apply immediately.",
"admin.empty": "No launcher yet.",
"admin.add": "Add a launcher",
"admin.edit": "Edit",
"admin.delete": "Delete",
"admin.up": "Move up",
"admin.down": "Move down",
"admin.confirm_delete": "Delete “{name}”?",
"admin.token_help": "Open the remote first with its full URL (make url), then come back to this page.",
"token.title": "Missing access token",
"form.add_title": "New launcher",
"form.edit_title": "Edit launcher",
"form.label": "Name",
"form.icon": "Icon",
"form.kind": "Type",
"form.url": "Address (URL)",
"form.browser": "Browser",
"form.fullscreen": "Start fullscreen",
"form.fullscreen_unavailable": "Unavailable with this browser (Firefox kiosk mode ignores F11).",
"form.not_installed": "{name} (not installed)",
"form.app": "Application",
"form.app_filter": "Filter…",
"form.apps_empty": "No application found.",
"form.app_missing": "{id} (not found)",
"form.command": "Command (one argument per line)",
"form.command_help": "No shell: each line is one argument, without quotes.",
"form.command_locked": "Raw commands are disabled: only the name and icon can be changed. To allow them, set allow_custom_command = true in the [admin] section of config.toml.",
"form.save": "Save",
"form.cancel": "Cancel",
"kind.web": "Website",
"kind.app": "Installed application",
"kind.command": "Command (advanced)",
"icon.app": "Application",
"icon.tv": "Television",
"icon.film": "Film",
"icon.globe": "Web",
"icon.music": "Music",
"icon.screen-off": "Screen off",
"icon.speaker": "Speaker",
"icon.lock": "Lock",
"icon.window": "Window",
"error.auth": "Token rejected: reopen the remote with its full URL (make url).",
"error.network": "Server unreachable.",
"error.prefix": "Error: {message}",
},
};
// ----------------------------------------------------------------------
// Accès à l'API REST
// ----------------------------------------------------------------------
class ApiError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
class Api {
constructor(token) {
this.token = token;
}
async request(method, path, body) {
const headers = { Authorization: `Bearer ${this.token}` };
if (body !== undefined) {
headers["Content-Type"] = "application/json";
}
let response;
try {
response = await fetch(path, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
cache: "no-store",
});
} catch {
throw new ApiError(0, "network");
}
if (response.status === 204) {
return null;
}
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new ApiError(response.status, data.error ?? response.statusText);
}
return data;
}
list() {
return this.request("GET", "/api/launchers");
}
apps() {
return this.request("GET", "/api/apps");
}
create(entry) {
return this.request("POST", "/api/launchers", entry);
}
update(id, entry) {
return this.request("PUT", `/api/launchers/${encodeURIComponent(id)}`, entry);
}
remove(id) {
return this.request("DELETE", `/api/launchers/${encodeURIComponent(id)}`);
}
reorder(ids) {
return this.request("POST", "/api/launchers/reorder", { ids });
}
}
// Message d'erreur affichable pour une exception d'API
function describeError(i18n, error) {
if (error instanceof ApiError) {
if (error.status === 401) {
return i18n.t("error.auth");
}
if (error.status === 0) {
return i18n.t("error.network");
}
}
return i18n.t("error.prefix", { message: error.message });
}
function button(className, text, onClick) {
const element = document.createElement("button");
element.type = "button";
element.className = className;
element.textContent = text;
element.addEventListener("click", onClick);
return element;
}
// ----------------------------------------------------------------------
// Liste des lanceurs
// ----------------------------------------------------------------------
class LauncherList {
// handlers : { edit(entry), remove(entry), move(entry, delta) }
constructor(i18n, handlers) {
this.i18n = i18n;
this.handlers = handlers;
}
render(launchers, browsers) {
$("admin-empty").hidden = launchers.length > 0;
$("admin-list").replaceChildren(
...launchers.map((entry, index) => this.item(entry, index, launchers.length, browsers)),
);
}
static summary(entry, browsers) {
switch (entry.kind) {
case "web": {
const browser = browsers.find((candidate) => candidate.id === entry.spec.browser);
return `${entry.spec.url} · ${browser ? browser.name : entry.spec.browser}`;
}
case "app":
return entry.spec.desktop_id;
default:
return entry.spec.argv.join(" ");
}
}
item(entry, index, total, browsers) {
const t = (key) => this.i18n.t(key);
const title = document.createElement("div");
title.className = "admin-item-title";
const name = document.createElement("span");
name.textContent = entry.label;
const tag = document.createElement("span");
tag.className = "kind-tag";
tag.textContent = t(`kind.${entry.kind}`);
title.append(name, tag);
const summary = document.createElement("p");
summary.className = "sub";
summary.textContent = LauncherList.summary(entry, browsers);
const text = document.createElement("div");
text.className = "admin-item-text";
text.append(title, summary);
const actions = document.createElement("div");
actions.className = "admin-actions";
const up = button("chip", "↑", () => this.handlers.move(entry, -1));
up.disabled = index === 0;
up.setAttribute("aria-label", t("admin.up"));
const down = button("chip", "↓", () => this.handlers.move(entry, 1));
down.disabled = index === total - 1;
down.setAttribute("aria-label", t("admin.down"));
actions.append(
up,
down,
button("chip", t("admin.edit"), () => this.handlers.edit(entry)),
button("chip danger", t("admin.delete"), () => this.handlers.remove(entry)),
);
const item = document.createElement("li");
item.className = "admin-item";
item.append(text, actions);
return item;
}
}
// ----------------------------------------------------------------------
// Formulaire d'ajout / modification
// ----------------------------------------------------------------------
class LauncherForm {
constructor(i18n, api, onSaved) {
this.i18n = i18n;
this.api = api;
this.onSaved = onSaved;
this.meta = null;
this.editing = null;
this.apps = null;
this.dialog = $("launcher-dialog");
$("launcher-form").addEventListener("submit", (event) => {
event.preventDefault();
this.submit();
});
$("form-cancel").addEventListener("click", () => this.dialog.close());
$("form-kind").addEventListener("change", () => this.showGroup());
$("form-browser").addEventListener("change", () => this.updateFullscreen());
$("form-app-filter").addEventListener("input", () => this.renderApps());
i18n.onChange(() => {
if (this.meta) {
this.populate();
}
});
}
// (Re)construit les listes déroulantes, en conservant la sélection courante
populate() {
const t = (key, params) => this.i18n.t(key, params);
const fill = (select, options) => {
const previous = select.value;
select.replaceChildren(
...options.map(({ value, text, disabled }) => {
const option = new Option(text, value);
option.disabled = Boolean(disabled);
return option;
}),
);
if (options.some((option) => option.value === previous)) {
select.value = previous;
}
};
fill($("form-icon"), this.meta.icons.map((icon) => ({ value: icon, text: t(`icon.${icon}`) })));
// Un lanceur « commande » existant reste modifiable (nom, icône) même si les commandes brutes sont interdites
const commandAllowed = this.meta.allow_command || this.editing?.kind === "command";
fill(
$("form-kind"),
["web", "app", "command"].map((kind) => ({
value: kind,
text: t(`kind.${kind}`),
disabled: kind === "command" && !commandAllowed,
})),
);
const browserOptions = this.meta.browsers.map((browser) => ({
value: browser.id,
text: browser.installed ? browser.name : t("form.not_installed", { name: browser.name }),
disabled: !browser.installed && browser.id !== this.editing?.spec?.browser,
}));
fill($("form-browser"), browserOptions);
}
open(meta, entry = null) {
this.meta = meta;
this.editing = entry;
this.populate();
$("form-title").textContent = this.i18n.t(entry ? "form.edit_title" : "form.add_title");
this.setError("");
const spec = entry?.spec ?? {};
$("form-label").value = entry?.label ?? "";
$("form-icon").value = entry?.icon ?? "tv";
$("form-kind").value = entry?.kind ?? "web";
$("form-url").value = spec.url ?? "";
const firstInstalled = this.meta.browsers.find((browser) => browser.installed);
$("form-browser").value = spec.browser ?? firstInstalled?.id ?? this.meta.browsers[0].id;
$("form-fullscreen").checked = Boolean(spec.fullscreen);
$("form-command").value = (spec.argv ?? []).join("\n");
$("form-app-filter").value = "";
this.selectedApp = spec.desktop_id ?? null;
const locked = entry?.kind === "command" && !this.meta.allow_command;
$("form-command").disabled = locked;
$("form-command-hint").dataset.i18n = locked ? "form.command_locked" : "form.command_help";
$("form-command-hint").textContent = this.i18n.t(locked ? "form.command_locked" : "form.command_help");
this.showGroup();
this.updateFullscreen();
this.dialog.showModal();
$("form-label").focus();
}
showGroup() {
const kind = $("form-kind").value;
this.dialog.querySelectorAll("[data-group]").forEach((group) => {
group.hidden = group.dataset.group !== kind;
});
if (kind === "app") {
this.loadApps();
}
}
updateFullscreen() {
const browser = this.meta.browsers.find((candidate) => candidate.id === $("form-browser").value);
const supported = Boolean(browser?.fullscreen);
$("form-fullscreen").disabled = !supported;
if (!supported) {
$("form-fullscreen").checked = false;
}
$("form-fullscreen-hint").hidden = supported;
}
async loadApps() {
if (this.apps === null) {
try {
this.apps = await this.api.apps();
} catch (error) {
this.setError(describeError(this.i18n, error));
return;
}
}
this.renderApps();
}
renderApps() {
if (this.apps === null) {
return;
}
const select = $("form-app");
const current = select.value || this.selectedApp;
const filter = $("form-app-filter").value.trim().toLocaleLowerCase();
const options = this.apps
.filter((app) => app.name.toLocaleLowerCase().includes(filter) || app.id.toLocaleLowerCase().includes(filter))
.map((app) => new Option(app.name, app.id));
// Application enregistrée mais désinstallée depuis : on la montre au lieu de la perdre en silence
if (this.selectedApp && !this.apps.some((app) => app.id === this.selectedApp)) {
options.unshift(new Option(this.i18n.t("form.app_missing", { id: this.selectedApp }), this.selectedApp));
}
select.replaceChildren(...options);
$("form-apps-empty").hidden = options.length > 0;
if (options.some((option) => option.value === current)) {
select.value = current;
}
}
setError(message) {
$("form-error").textContent = message;
$("form-error").hidden = message === "";
}
// Arguments d'une commande : une ligne par argument, sans interprétation
static parseArgv(text) {
return text.split("\n").filter((line) => line !== "");
}
collect() {
const kind = $("form-kind").value;
let spec;
if (kind === "web") {
spec = {
url: $("form-url").value.trim(),
browser: $("form-browser").value,
fullscreen: $("form-fullscreen").checked,
};
} else if (kind === "app") {
spec = { desktop_id: $("form-app").value };
} else {
spec = { argv: LauncherForm.parseArgv($("form-command").value) };
}
return { label: $("form-label").value.trim(), icon: $("form-icon").value, kind, spec };
}
async submit() {
try {
const entry = this.collect();
if (this.editing) {
await this.api.update(this.editing.id, entry);
} else {
await this.api.create(entry);
}
} catch (error) {
this.setError(describeError(this.i18n, error));
return;
}
this.dialog.close();
this.onSaved();
}
}
// ----------------------------------------------------------------------
// Page
// ----------------------------------------------------------------------
class AdminPage {
constructor() {
this.i18n = new I18n(MESSAGES);
this.i18n.apply();
this.data = null;
const token = Storage.get(STORAGE_TOKEN);
if (!token) {
$("no-token").hidden = false;
return;
}
this.api = new Api(token);
this.list = new LauncherList(this.i18n, {
edit: (entry) => this.form.open(this.data, entry),
remove: (entry) => this.remove(entry),
move: (entry, delta) => this.move(entry, delta),
});
this.form = new LauncherForm(this.i18n, this.api, () => this.refresh());
$("admin-add").addEventListener("click", () => this.data && this.form.open(this.data));
$("lang-toggle").addEventListener("click", () => this.i18n.toggle());
this.i18n.onChange(() => {
this.updateLangButton();
this.render();
});
this.updateLangButton();
this.refresh();
}
updateLangButton() {
// Le bouton affiche la langue vers laquelle on bascule
$("lang-toggle").textContent = this.i18n.lang === "fr" ? "EN" : "FR";
}
showError(error) {
const message = error ? describeError(this.i18n, error) : "";
$("admin-error").textContent = message;
$("admin-error").hidden = message === "";
}
async refresh() {
try {
this.data = await this.api.list();
} catch (error) {
this.showError(error);
return;
}
this.showError(null);
this.render();
}
render() {
if (this.data) {
this.list.render(this.data.launchers, this.data.browsers);
}
}
// Exécute une modification puis recharge la liste ; l'erreur éventuelle est affichée
async apply(action) {
try {
await action();
} catch (error) {
this.showError(error);
return;
}
await this.refresh();
}
move(entry, delta) {
const ids = this.data.launchers.map((launcher) => launcher.id);
const from = ids.indexOf(entry.id);
const to = from + delta;
if (from < 0 || to < 0 || to >= ids.length) {
return Promise.resolve();
}
[ids[from], ids[to]] = [ids[to], ids[from]];
return this.apply(() => this.api.reorder(ids));
}
remove(entry) {
if (!window.confirm(this.i18n.t("admin.confirm_delete", { name: entry.label }))) {
return Promise.resolve();
}
return this.apply(() => this.api.remove(entry.id));
}
}
new AdminPage();
File diff suppressed because it is too large Load Diff
+70
View File
@@ -0,0 +1,70 @@
// MediaDeck : éléments partagés entre l'interface tablette (app.js) et la page d'administration (admin.js).
export const STORAGE_TOKEN = "mediadeck.token";
export const STORAGE_LANG = "mediadeck.lang";
export class Storage {
// localStorage peut être indisponible (navigation privée, kiosque)
static get(key) {
try {
return window.localStorage.getItem(key);
} catch {
return null;
}
}
static set(key, value) {
try {
window.localStorage.setItem(key, value);
} catch {
// Sans persistance : l'URL avec jeton reste nécessaire à chaque ouverture
}
}
}
export class I18n {
// messages : { fr: {clé: texte}, en: {…} } ; la langue choisie est partagée entre les pages
constructor(messages) {
this.messages = messages;
const stored = Storage.get(STORAGE_LANG);
const browser = (navigator.language || "fr").slice(0, 2);
this.lang = stored in messages ? stored : browser in messages ? browser : "en";
this.listeners = [];
}
t(key, params = {}) {
const template = this.messages[this.lang][key] ?? this.messages.en[key] ?? key;
return template.replace(/\{(\w+)\}/g, (_, name) => params[name] ?? "");
}
// Applique les traductions aux éléments marqués data-i18n / data-i18n-label / data-i18n-placeholder
apply(root = document) {
document.documentElement.lang = this.lang;
root.querySelectorAll("[data-i18n]").forEach((el) => {
el.textContent = this.t(el.dataset.i18n);
});
root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
el.setAttribute("placeholder", this.t(el.dataset.i18nPlaceholder));
});
root.querySelectorAll("[data-i18n-label]").forEach((el) => {
const label = this.t(el.dataset.i18nLabel);
el.setAttribute("aria-label", label);
el.setAttribute("title", label);
});
}
toggle() {
this.lang = this.lang === "fr" ? "en" : "fr";
Storage.set(STORAGE_LANG, this.lang);
this.apply();
this.listeners.forEach((listener) => listener(this.lang));
}
onChange(listener) {
this.listeners.push(listener);
}
}
export function $(id) {
return document.getElementById(id);
}
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" fill="#0e0f13"/>
<circle cx="256" cy="256" r="150" fill="#f5a524"/>
<path d="M222 186v140l112-70z" fill="#1b1305"/>
</svg>

After

Width:  |  Height:  |  Size: 238 B

+19
View File
@@ -0,0 +1,19 @@
{
"name": "MediaDeck",
"short_name": "MediaDeck",
"description": "Web remote for a Linux media PC",
"start_url": "/",
"scope": "/",
"display": "fullscreen",
"orientation": "any",
"background_color": "#0e0f13",
"theme_color": "#0e0f13",
"icons": [
{
"src": "/static/icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any maskable"
}
]
}
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "mediadeck"
version = "0.1.0"
description = "Web remote for a Linux media PC: MPRIS, PipeWire, virtual input, power"
readme = "README-EN.md"
license = "MIT"
requires-python = ">=3.11"
authors = [{ name = "Denis" }]
dependencies = [
"aiohttp>=3.9",
"dbus-next>=0.2.3",
"evdev>=1.6",
]
[project.optional-dependencies]
dev = ["pyright>=1.1.380"]
[project.scripts]
mediadeck = "mediadeck.__main__:main"
[tool.setuptools]
packages = ["mediadeck"]
[tool.setuptools.package-data]
mediadeck = ["web/*.html", "web/static/*"]
+8
View File
@@ -0,0 +1,8 @@
{
"include": ["mediadeck", "tests"],
"venvPath": ".",
"venv": ".venv",
"pythonVersion": "3.11",
"typeCheckingMode": "standard",
"reportMissingTypeStubs": false
}
+18
View File
@@ -0,0 +1,18 @@
# Service utilisateur : doit tourner dans la session graphique (bus D-Bus de session)
[Unit]
Description=MediaDeck web remote for the media PC
Documentation=file://@PROJECT_DIR@/README.md
After=graphical-session.target pipewire-pulse.service
PartOf=graphical-session.target
[Service]
Type=simple
ExecStart=@PROJECT_DIR@/.venv/bin/python -m mediadeck
Restart=on-failure
RestartSec=3
# Durcissement compatible avec le pilotage de la session
NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=graphical-session.target
View File
+167
View File
@@ -0,0 +1,167 @@
"""Tests de l'API REST d'administration des lanceurs (sans D-Bus : seules les routes /api sont montées)."""
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
from mediadeck.admin import AdminApi
from mediadeck.config import parse_config
from mediadeck.launchers import LauncherStore
TOKEN = "t" * 32
AUTH = {"Authorization": f"Bearer {TOKEN}"}
WEB = {"label": "Arte", "icon": "tv", "kind": "web", "spec": {"url": "https://www.arte.tv/fr/", "browser": "chromium"}}
COMMAND = {"label": "Off", "icon": "screen-off", "kind": "command", "spec": {"argv": ["kscreen-doctor", "--dpms", "off"]}}
class AdminApiCase(unittest.IsolatedAsyncioTestCase):
"""Serveur de test sans commande brute autorisée ; les sous-classes ajoutent les tests."""
allow_command = False
async def asyncSetUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.store = LauncherStore(Path(self._tmp.name) / "launchers.db")
self.changes = 0
config = parse_config(
{"server": {"token": TOKEN}, "admin": {"allow_custom_command": self.allow_command}}
)
app = web.Application()
AdminApi(config, self.store, self._on_change).add_routes(app)
self.client = TestClient(TestServer(app))
await self.client.start_server()
async def asyncTearDown(self) -> None:
await self.client.close()
self.store.close()
self._tmp.cleanup()
def _on_change(self) -> None:
self.changes += 1
class AdminApiTest(AdminApiCase):
async def test_token_required_on_every_route(self) -> None:
calls = [
("GET", "/api/launchers"), ("POST", "/api/launchers"), ("PUT", "/api/launchers/x"),
("DELETE", "/api/launchers/x"), ("POST", "/api/launchers/reorder"), ("GET", "/api/apps"),
]
wrong = {"Authorization": "Bearer nope"}
for method, path in calls:
for headers in ({}, wrong, {"Authorization": TOKEN}, {"Authorization": f"Basic {TOKEN}"}):
with self.subTest(method=method, path=path, headers=headers):
response = await self.client.request(method, path, headers=headers, json=WEB)
self.assertEqual(response.status, 401)
# Le jeton en paramètre d'URL n'est pas accepté : il finirait dans les journaux et l'historique
response = await self.client.get(f"/api/launchers?token={TOKEN}")
self.assertEqual(response.status, 401)
async def test_list_exposes_options(self) -> None:
response = await self.client.get("/api/launchers", headers=AUTH)
data = await response.json()
self.assertEqual(response.status, 200)
self.assertEqual(data["launchers"], [])
self.assertIn("tv", data["icons"])
self.assertFalse(data["allow_command"])
self.assertEqual({browser["id"] for browser in data["browsers"]}, {"chromium", "chrome", "brave", "firefox"})
async def test_crud_cycle(self) -> None:
created = await self.client.post("/api/launchers", headers=AUTH, json=WEB)
self.assertEqual(created.status, 201)
entry = await created.json()
self.assertEqual(entry["id"], "arte")
self.assertEqual(entry["spec"]["fullscreen"], False)
updated = await self.client.put("/api/launchers/arte", headers=AUTH, json={**WEB, "label": "Arte TV"})
self.assertEqual(updated.status, 200)
self.assertEqual((await updated.json())["label"], "Arte TV")
second = await self.client.post("/api/launchers", headers=AUTH, json={**WEB, "label": "Autre"})
self.assertEqual(second.status, 201)
reorder = await self.client.post("/api/launchers/reorder", headers=AUTH, json={"ids": ["autre", "arte"]})
self.assertEqual(reorder.status, 204)
listing = await (await self.client.get("/api/launchers", headers=AUTH)).json()
self.assertEqual([item["id"] for item in listing["launchers"]], ["autre", "arte"])
deleted = await self.client.delete("/api/launchers/arte", headers=AUTH)
self.assertEqual(deleted.status, 204)
self.assertEqual((await self.client.delete("/api/launchers/arte", headers=AUTH)).status, 404)
self.assertEqual((await self.client.put("/api/launchers/arte", headers=AUTH, json=WEB)).status, 404)
# create + update + create + reorder + delete : chaque modification notifie les tablettes
self.assertEqual(self.changes, 5)
async def test_validation_errors_do_not_change_anything(self) -> None:
bad = {**WEB, "spec": {**WEB["spec"], "url": "javascript:alert(1)"}}
response = await self.client.post("/api/launchers", headers=AUTH, json=bad)
self.assertEqual(response.status, 400)
self.assertIn("error", await response.json())
invalid_json = await self.client.post("/api/launchers", headers=AUTH, data=b"{nope")
self.assertEqual(invalid_json.status, 400)
too_large = await self.client.post("/api/launchers", headers=AUTH, data=b" " * 20000)
self.assertEqual(too_large.status, 400)
bad_order = await self.client.post("/api/launchers/reorder", headers=AUTH, json={"ids": ["x"]})
self.assertEqual(bad_order.status, 400)
self.assertEqual(self.store.list(), [])
self.assertEqual(self.changes, 0)
async def test_raw_commands_are_forbidden_by_default(self) -> None:
response = await self.client.post("/api/launchers", headers=AUTH, json=COMMAND)
self.assertEqual(response.status, 403)
self.assertEqual(self.store.list(), [])
async def test_imported_command_can_be_renamed_but_not_rewritten(self) -> None:
entry = self.store.create("Off", "screen-off", "command", COMMAND["spec"])
renamed = await self.client.put(f"/api/launchers/{entry.id}", headers=AUTH, json={**COMMAND, "label": "Écran off"})
self.assertEqual(renamed.status, 200)
rewritten = await self.client.put(
f"/api/launchers/{entry.id}", headers=AUTH, json={**COMMAND, "spec": {"argv": ["reboot"]}}
)
self.assertEqual(rewritten.status, 403)
stored = self.store.get(entry.id)
assert stored is not None
self.assertEqual(stored.spec, COMMAND["spec"])
async def test_apps_listing_and_app_launcher(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "vlc.desktop").write_text("[Desktop Entry]\nType=Application\nName=VLC\nExec=vlc\n")
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]):
apps = await (await self.client.get("/api/apps", headers=AUTH)).json()
self.assertEqual(apps, [{"id": "vlc.desktop", "name": "VLC"}])
ok = await self.client.post(
"/api/launchers", headers=AUTH,
json={"label": "VLC", "icon": "film", "kind": "app", "spec": {"desktop_id": "vlc.desktop"}},
)
self.assertEqual(ok.status, 201)
unknown = await self.client.post(
"/api/launchers", headers=AUTH,
json={"label": "X", "icon": "app", "kind": "app", "spec": {"desktop_id": "../../x.desktop"}},
)
self.assertEqual(unknown.status, 400)
class AdminApiCommandAllowedTest(AdminApiCase):
allow_command = True
async def test_list_announces_raw_commands(self) -> None:
data = await (await self.client.get("/api/launchers", headers=AUTH)).json()
self.assertTrue(data["allow_command"])
async def test_raw_commands_are_accepted(self) -> None:
response = await self.client.post("/api/launchers", headers=AUTH, json=COMMAND)
self.assertEqual(response.status, 201)
self.assertEqual((await response.json())["spec"], COMMAND["spec"])
async def test_command_can_be_rewritten(self) -> None:
entry = self.store.create("Off", "screen-off", "command", COMMAND["spec"])
rewritten = await self.client.put(
f"/api/launchers/{entry.id}", headers=AUTH, json={**COMMAND, "spec": {"argv": ["reboot"]}}
)
self.assertEqual(rewritten.status, 200)
if __name__ == "__main__":
unittest.main()
+94
View File
@@ -0,0 +1,94 @@
"""Tests de validation de la configuration."""
import os
import tempfile
import unittest
from pathlib import Path
from mediadeck.config import ConfigError, load_config, parse_config
TOKEN = "x" * 32
class ParseConfigTest(unittest.TestCase):
def test_defaults(self) -> None:
config = parse_config({"server": {"token": TOKEN}})
self.assertEqual(config.port, 8765)
self.assertEqual(config.max_volume, 1.0)
self.assertTrue(config.enable_input)
self.assertEqual(config.launchers, ())
def test_short_token_rejected(self) -> None:
with self.assertRaises(ConfigError):
parse_config({"server": {"token": "short"}})
def test_launcher_command_must_be_argv(self) -> None:
# Une chaîne seule serait tentante à passer à un shell : refusée
with self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN}, "launchers": [{"id": "a", "label": "A", "command": "vlc"}]})
def test_duplicate_launcher_id(self) -> None:
launcher = {"id": "vlc", "label": "VLC", "command": ["vlc"]}
with self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN}, "launchers": [launcher, launcher]})
def test_advertise_host(self) -> None:
self.assertEqual(parse_config({"server": {"token": TOKEN}}).advertise_host, "")
config = parse_config({"server": {"token": TOKEN, "advertise_host": "192.168.1.104"}})
self.assertEqual(config.advertise_host, "192.168.1.104")
self.assertEqual(
parse_config({"server": {"token": TOKEN, "advertise_host": "mediapc.local"}}).advertise_host,
"mediapc.local",
)
def test_advertise_host_rejects_url_syntax(self) -> None:
# La valeur est insérée telle quelle dans l'URL : pas de schéma, port, chemin ni espace
for value in ("http://192.168.1.104", "192.168.1.104:8765", "host/path", "a b", "x@y", 42):
with self.subTest(value=value), self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN, "advertise_host": value}})
def test_tls_paths(self) -> None:
config = parse_config({"server": {"token": TOKEN, "tls_cert": "~/c.pem", "tls_key": "/k.key"}})
self.assertTrue(config.tls_enabled)
self.assertEqual(config.tls_cert, Path.home() / "c.pem")
self.assertIsNone(config.tls_ca)
self.assertFalse(parse_config({"server": {"token": TOKEN}}).tls_enabled)
def test_tls_options_are_consistent(self) -> None:
for server in (
{"tls_cert": "/c.pem"}, # clé manquante
{"tls_key": "/k.key"}, # certificat manquant
{"tls_ca": "/ca.crt"}, # CA sans certificat
{"tls_cert": 1, "tls_key": "/k.key"},
):
with self.subTest(server=server), self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN, **server}})
def test_max_volume_bounds(self) -> None:
with self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN}, "audio": {"max_volume": 3}})
class LoadConfigTest(unittest.TestCase):
def test_world_readable_file_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.toml"
path.write_text(f'[server]\ntoken = "{TOKEN}"\n')
os.chmod(path, 0o644)
with self.assertRaises(ConfigError):
load_config(path)
os.chmod(path, 0o600)
self.assertEqual(load_config(path).token, TOKEN)
def test_example_config_is_valid(self) -> None:
example = Path(__file__).resolve().parent.parent / "config.example.toml"
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.toml"
path.write_text(example.read_text().replace("CHANGE_ME", TOKEN))
os.chmod(path, 0o600)
config = load_config(path)
self.assertGreater(len(config.launchers), 0)
if __name__ == "__main__":
unittest.main()
+215
View File
@@ -0,0 +1,215 @@
"""Tests des lanceurs : stockage SQLite, validation, construction de la commande, applications .desktop."""
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from mediadeck import launchers
from mediadeck.config import Launcher as ConfigLauncher
from mediadeck.launchers import (
CommandNotAllowed,
LauncherEntry,
LauncherError,
LauncherNotFound,
LauncherStore,
build_argv,
validate,
)
WEB = {"label": "Arte", "icon": "tv", "kind": "web", "spec": {"url": "https://www.arte.tv/fr/", "browser": "chromium"}}
COMMAND = {"label": "Off", "icon": "screen-off", "kind": "command", "spec": {"argv": ["kscreen-doctor", "--dpms", "off"]}}
DESKTOP = """[Desktop Entry]
Type=Application
Name=Lecteur {name}
Exec={name} %U
{extra}
"""
def write_desktop(directory: Path, filename: str, name: str, extra: str = "") -> None:
(directory / filename).write_text(DESKTOP.format(name=name, extra=extra))
class StoreTest(unittest.TestCase):
def setUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.path = Path(self._tmp.name) / "data" / "launchers.db"
self.store = LauncherStore(self.path)
def tearDown(self) -> None:
self.store.close()
self._tmp.cleanup()
def test_private_permissions(self) -> None:
self.assertEqual(self.path.stat().st_mode & 0o077, 0)
self.assertEqual(self.path.parent.stat().st_mode & 0o077, 0)
def test_create_generates_unique_slugs_and_keeps_order(self) -> None:
first = self.store.create("Écran off", "app", "command", {"argv": ["a"]})
second = self.store.create("Écran off", "app", "command", {"argv": ["b"]})
self.assertEqual((first.id, second.id), ("ecran-off", "ecran-off-2"))
self.assertEqual([entry.id for entry in self.store.list()], ["ecran-off", "ecran-off-2"])
def test_update_and_delete(self) -> None:
entry = self.store.create("Arte", "tv", "web", WEB["spec"])
self.store.update(entry.id, "Arte TV", "film", "web", WEB["spec"])
updated = self.store.get(entry.id)
assert updated is not None
self.assertEqual((updated.label, updated.icon), ("Arte TV", "film"))
self.store.delete(entry.id)
self.assertIsNone(self.store.get(entry.id))
with self.assertRaises(LauncherNotFound):
self.store.delete(entry.id)
with self.assertRaises(LauncherNotFound):
self.store.update("absent", "x", "app", "command", {"argv": ["x"]})
def test_reorder_requires_every_id(self) -> None:
ids = [self.store.create(name, "app", "command", {"argv": [name]}).id for name in ("a", "b", "c")]
self.store.reorder(["c", "a", "b"])
self.assertEqual([entry.id for entry in self.store.list()], ["c", "a", "b"])
for bad in (ids[:2], [*ids, "d"], ["a", "a", "b"]):
with self.subTest(ids=bad), self.assertRaises(LauncherError):
self.store.reorder(bad)
def test_data_survives_reopening(self) -> None:
self.store.create("Arte", "tv", "web", WEB["spec"])
self.store.close()
self.store = LauncherStore(self.path)
self.assertEqual([entry.label for entry in self.store.list()], ["Arte"])
def test_seed_imports_config_launchers_once(self) -> None:
config_launchers = [
ConfigLauncher("vlc", "VLC", ("vlc",), "film"),
ConfigLauncher("odd", "Odd", ("odd", "--x"), "inconnue"),
]
self.assertEqual(self.store.seed(config_launchers), 2)
self.assertEqual(self.store.seed(config_launchers), 0)
entries = self.store.list()
self.assertEqual([entry.id for entry in entries], ["vlc", "odd"])
self.assertEqual(entries[0].kind, "command")
self.assertEqual(entries[1].spec, {"argv": ["odd", "--x"]})
self.assertEqual(entries[1].icon, "app")
# Une fois importés, les lanceurs supprimés ne reviennent pas au redémarrage
self.store.delete("vlc")
self.store.close()
self.store = LauncherStore(self.path)
self.assertEqual(self.store.seed(config_launchers), 0)
self.assertEqual([entry.id for entry in self.store.list()], ["odd"])
def test_limit(self) -> None:
for index in range(launchers.MAX_LAUNCHERS):
self.store.create(f"l{index}", "app", "command", {"argv": ["x"]})
with self.assertRaises(LauncherError):
self.store.create("one more", "app", "command", {"argv": ["x"]})
class ValidateTest(unittest.TestCase):
def test_valid_web(self) -> None:
label, icon, kind, spec = validate(WEB, allow_command=False)
self.assertEqual((label, icon, kind), ("Arte", "tv", "web"))
self.assertEqual(spec, {"url": "https://www.arte.tv/fr/", "browser": "chromium", "fullscreen": False})
def test_fullscreen_dropped_for_firefox(self) -> None:
data = {**WEB, "spec": {**WEB["spec"], "browser": "firefox", "fullscreen": True}}
self.assertFalse(validate(data, allow_command=False)[3]["fullscreen"])
def test_rejected_urls(self) -> None:
for url in ("javascript:alert(1)", "file:///etc/passwd", "http://", "https://a b.example", "--kiosk", "", " ",
"https://x/\n--evil", 5):
with self.subTest(url=url), self.assertRaises(LauncherError):
validate({**WEB, "spec": {**WEB["spec"], "url": url}}, allow_command=False)
def test_rejected_fields(self) -> None:
for patch in (
{"label": ""}, {"label": "x" * 41}, {"label": 3}, {"icon": "nope"}, {"kind": "shell"}, {"kind": None},
{"spec": "x"}, {"spec": {**WEB["spec"], "browser": "netscape"}}, {"spec": {**WEB["spec"], "fullscreen": "yes"}},
):
with self.subTest(patch=patch), self.assertRaises(LauncherError):
validate({**WEB, **patch}, allow_command=False)
with self.assertRaises(LauncherError):
validate([], allow_command=False)
def test_command_forbidden_by_default(self) -> None:
with self.assertRaises(CommandNotAllowed):
validate(COMMAND, allow_command=False)
self.assertEqual(validate(COMMAND, allow_command=True)[3], {"argv": ["kscreen-doctor", "--dpms", "off"]})
def test_command_argv_rules(self) -> None:
for argv in ([], "vlc", [""], ["a", 3], ["a\0b"], ["x"] * 33):
with self.subTest(argv=argv), self.assertRaises(LauncherError):
validate({**COMMAND, "spec": {"argv": argv}}, allow_command=True)
def test_existing_command_can_be_renamed_but_not_changed(self) -> None:
current = LauncherEntry("off", "Off", "app", "command", COMMAND["spec"])
renamed = validate({**COMMAND, "label": "Écran éteint"}, allow_command=False, current=current)
self.assertEqual(renamed[0], "Écran éteint")
with self.assertRaises(CommandNotAllowed):
validate({**COMMAND, "spec": {"argv": ["rm", "-rf", "~"]}}, allow_command=False, current=current)
# Convertir un lanceur web en commande brute reste une création de commande
web = LauncherEntry("w", "W", "tv", "web", WEB["spec"])
with self.assertRaises(CommandNotAllowed):
validate(COMMAND, allow_command=False, current=web)
class BuildArgvTest(unittest.TestCase):
def test_web_argv(self) -> None:
spec = {"url": "https://www.arte.tv/fr/", "browser": "chromium", "fullscreen": True}
entry = LauncherEntry("arte", "Arte", "tv", "web", spec)
with mock.patch("mediadeck.launchers.shutil.which", return_value="/usr/bin/chromium"):
self.assertEqual(build_argv(entry), ["chromium", "--start-fullscreen", "https://www.arte.tv/fr/"])
windowed = LauncherEntry("arte", "Arte", "tv", "web", {**spec, "fullscreen": False})
self.assertEqual(build_argv(windowed), ["chromium", "https://www.arte.tv/fr/"])
firefox = LauncherEntry("arte", "Arte", "tv", "web", {**spec, "browser": "firefox"})
self.assertEqual(build_argv(firefox), ["firefox", "--new-window", "https://www.arte.tv/fr/"])
def test_web_browser_not_installed(self) -> None:
entry = LauncherEntry("arte", "Arte", "tv", "web", WEB["spec"])
with mock.patch("mediadeck.launchers.shutil.which", return_value=None), self.assertRaises(LauncherError):
build_argv(entry)
def test_command_argv(self) -> None:
entry = LauncherEntry("off", "Off", "app", "command", COMMAND["spec"])
self.assertEqual(build_argv(entry), ["kscreen-doctor", "--dpms", "off"])
def test_app_argv_uses_gio_and_the_resolved_path(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
write_desktop(Path(tmp), "vlc.desktop", "vlc")
entry = LauncherEntry("vlc", "VLC", "film", "app", {"desktop_id": "vlc.desktop"})
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]), \
mock.patch("mediadeck.launchers.shutil.which", return_value="/usr/bin/gio"):
self.assertEqual(build_argv(entry), ["gio", "launch", str(Path(tmp) / "vlc.desktop")])
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]), \
mock.patch("mediadeck.launchers.shutil.which", return_value=None), self.assertRaises(LauncherError):
build_argv(entry)
class DesktopAppsTest(unittest.TestCase):
def test_listing_filters_and_precedence(self) -> None:
with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
user, system = Path(first), Path(second)
write_desktop(user, "mpv.desktop", "mpv-utilisateur")
write_desktop(system, "mpv.desktop", "mpv-systeme")
write_desktop(system, "zeal.desktop", "zeal")
write_desktop(system, "hidden.desktop", "hidden", "NoDisplay=true")
write_desktop(system, "shell.desktop", "shell", "Terminal=true")
(system / "broken.desktop").write_text("pas un fichier desktop")
(system / "notes.txt").write_text("[Desktop Entry]")
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[user, system, system / "absent"]):
apps = launchers.list_desktop_apps()
self.assertEqual([(app.id, app.name) for app in apps],
[("mpv.desktop", "Lecteur mpv-utilisateur"), ("zeal.desktop", "Lecteur zeal")])
self.assertIsNone(launchers.find_desktop_entry("hidden.desktop"))
def test_find_desktop_entry_rejects_path_tricks(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
write_desktop(Path(tmp), "vlc.desktop", "vlc")
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp) / "sub"]):
for desktop_id in ("../vlc.desktop", "/etc/passwd", "vlc", "a/b.desktop", ""):
with self.subTest(desktop_id=desktop_id):
self.assertIsNone(launchers.find_desktop_entry(desktop_id))
if __name__ == "__main__":
unittest.main()
+61
View File
@@ -0,0 +1,61 @@
"""Tests des conversions MPRIS et pactl, sans D-Bus ni serveur audio."""
import json
import unittest
from dbus_next.signature import Variant
from mediadeck.audio import parse_sinks
from mediadeck.mpris import normalize_metadata, unwrap
class MprisTest(unittest.TestCase):
def test_unwrap_nested_variants(self) -> None:
value = {"a": Variant("as", ["x", "y"]), "b": Variant("v", Variant("i", 3))}
self.assertEqual(unwrap(value), {"a": ["x", "y"], "b": 3})
def test_normalize_metadata(self) -> None:
raw = {
"mpris:trackid": Variant("o", "/org/mpris/MediaPlayer2/Track/1"),
"mpris:length": Variant("x", 215_000_000),
"xesam:title": Variant("s", "Song"),
"xesam:artist": Variant("as", ["A", "B"]),
"xesam:comment": Variant("as", ["ignored"]),
}
meta = normalize_metadata(raw)
self.assertEqual(meta["artist"], "A, B")
self.assertEqual(meta["length"], 215_000_000)
self.assertEqual(meta["trackid"], "/org/mpris/MediaPlayer2/Track/1")
self.assertNotIn("comment", meta)
def test_missing_length_defaults_to_zero(self) -> None:
self.assertEqual(normalize_metadata({})["length"], 0)
class PactlTest(unittest.TestCase):
def test_parse_sinks_average_volume(self) -> None:
raw = json.dumps(
[
{
"name": "alsa_output.hdmi",
"description": "HDMI TV",
"mute": False,
"volume": {
"front-left": {"value": 26214, "value_percent": "40%", "db": "-23.88 dB"},
"front-right": {"value": 32768, "value_percent": "50%", "db": "-18.06 dB"},
},
},
{"name": "bt", "description": "", "mute": True, "volume": {}},
]
)
sinks = parse_sinks(raw)
self.assertEqual(sinks[0]["volume"], 0.45)
self.assertFalse(sinks[0]["muted"])
# Description vide : repli sur le nom
self.assertEqual(sinks[1]["description"], "bt")
self.assertTrue(sinks[1]["muted"])
self.assertEqual(sinks[1]["volume"], 0.0)
if __name__ == "__main__":
unittest.main()
+296
View File
@@ -0,0 +1,296 @@
"""Tests de la saisie de texte : disposition du clavier, traduction caractère -> touches, envoi des frappes."""
import asyncio
import unittest
from typing import Any
from mediadeck.input import TYPING_KEYS, VirtualInput
from mediadeck.keymap import (
KEY_ENTER,
KEY_SPACE,
Keymap,
KeymapError,
LayoutSpec,
Stroke,
parse_kxkbrc,
parse_setxkbmap,
)
from mediadeck.text import MAX_TEXT_LENGTH, TextTyper
from xkbsim import Simulator, SimulatorUnavailable
US = LayoutSpec(layout="us")
FR = LayoutSpec(layout="fr")
FR_LATIN9 = LayoutSpec(model="pc104", layout="fr", variant="latin9")
DE = LayoutSpec(layout="de")
KEY_A, KEY_Q, KEY_2, KEY_0 = 30, 16, 3, 11
KEY_LEFTSHIFT, KEY_RIGHTALT = 42, 100
ASCII = "Hello, World! 0123456789 @#$%^&*()_+-=[]{};:'\",.<>/?\\|`~ end"
FRENCH = "Élève à l'école, ça coûte 5 €, garçon naïf, forêt, Noël, Ça va ? Œuvre : « oui »."
def build(spec: LayoutSpec) -> Keymap:
try:
return Keymap(spec)
except KeymapError as exc:
raise unittest.SkipTest(f"xkb unavailable for {spec}: {exc}") from exc
class ParseTest(unittest.TestCase):
def test_kxkbrc(self) -> None:
text = "[Layout]\nDisplayNames=,\nLayoutList=fr,us\nModel=pc104\nOptions=compose:ralt\nUse=true\nVariantList=latin9,\n"
self.assertEqual(
parse_kxkbrc(text),
[
LayoutSpec("pc104", "fr", "latin9", "compose:ralt"),
LayoutSpec("pc104", "us", "", "compose:ralt"),
],
)
def test_kxkbrc_not_applicable(self) -> None:
self.assertIsNone(parse_kxkbrc("[Layout]\nLayoutList=fr\nUse=false\n"))
self.assertIsNone(parse_kxkbrc("[Other]\nUse=true\n"))
self.assertIsNone(parse_kxkbrc("[Layout]\nUse=true\nLayoutList=\n"))
self.assertIsNone(parse_kxkbrc("pas un fichier ini"))
def test_kxkbrc_defaults_model(self) -> None:
specs = parse_kxkbrc("[Layout]\nUse=true\nLayoutList=de\n")
assert specs is not None
self.assertEqual(specs[0], LayoutSpec("pc105", "de", "", ""))
def test_setxkbmap(self) -> None:
output = "rules: evdev\nmodel: pc104\nlayout: fr,us\nvariant: latin9,\noptions: grp:alt_shift_toggle\n"
self.assertEqual(
parse_setxkbmap(output),
[
LayoutSpec("pc104", "fr", "latin9", "grp:alt_shift_toggle"),
LayoutSpec("pc104", "us", "", "grp:alt_shift_toggle"),
],
)
self.assertIsNone(parse_setxkbmap(""))
class KeymapTest(unittest.TestCase):
def test_us_basic(self) -> None:
keymap = build(US)
self.assertEqual(keymap.plan("a")[0], [Stroke(KEY_A)])
self.assertEqual(keymap.plan("A")[0], [Stroke(KEY_A, shift=True)])
self.assertEqual(keymap.plan("@")[0], [Stroke(KEY_2, shift=True)])
self.assertEqual(keymap.plan(" ")[0], [Stroke(KEY_SPACE)])
self.assertEqual(keymap.plan("\n")[0], [Stroke(KEY_ENTER)])
self.assertEqual((keymap.shift_code, keymap.altgr_code), (KEY_LEFTSHIFT, None))
def test_azerty_differs_from_qwerty(self) -> None:
# Le piège d'origine : la même lettre ne se tape pas avec la même touche
keymap = build(FR)
self.assertEqual(keymap.plan("a")[0], [Stroke(KEY_Q)])
self.assertEqual(keymap.plan("1")[0], [Stroke(2, shift=True)])
self.assertEqual(keymap.plan("é")[0], [Stroke(KEY_2)])
self.assertEqual(keymap.plan("@")[0], [Stroke(KEY_0, altgr=True)])
self.assertEqual(keymap.altgr_code, KEY_RIGHTALT)
def test_unavailable_characters_are_reported_once(self) -> None:
strokes, skipped = build(US).plan("a→b→😀")
self.assertEqual(len(strokes), 2)
self.assertEqual(skipped, ["→", "😀"])
def test_typographic_fallback(self) -> None:
keymap = build(US)
apostrophe = keymap.plan("'")[0]
self.assertEqual(keymap.plan("’")[0], apostrophe)
self.assertEqual(keymap.plan("…")[0], keymap.plan("...")[0])
def test_only_allowed_keys_are_used(self) -> None:
keymap = build(FR_LATIN9)
strokes, _ = keymap.plan(ASCII + FRENCH)
self.assertTrue(all(stroke.code in TYPING_KEYS for stroke in strokes))
def test_invalid_layout(self) -> None:
with self.assertRaises(KeymapError):
Keymap(LayoutSpec(layout="zz-not-a-layout"))
class RoundTripTest(unittest.TestCase):
"""Les frappes calculées, rejouées par un état xkb, redonnent exactement le texte demandé."""
def simulate(self, spec: LayoutSpec, text: str) -> tuple[str, list[str]]:
keymap = build(spec)
try:
simulator = Simulator(keymap)
except SimulatorUnavailable as exc:
raise unittest.SkipTest(f"no compose table for {exc}") from exc
strokes, skipped = keymap.plan(text)
return simulator.type(strokes), skipped
def test_ascii_on_us(self) -> None:
typed, skipped = self.simulate(US, ASCII)
self.assertEqual((typed, skipped), (ASCII, []))
def test_ascii_on_azerty_latin9(self) -> None:
typed, skipped = self.simulate(FR_LATIN9, ASCII)
self.assertEqual((typed, skipped), (ASCII, []))
def test_ascii_on_german(self) -> None:
typed, skipped = self.simulate(DE, ASCII)
self.assertEqual((typed, skipped), (ASCII, []))
def test_french_text_on_azerty(self) -> None:
typed, skipped = self.simulate(FR_LATIN9, FRENCH)
self.assertEqual(skipped, [])
self.assertEqual(typed, FRENCH)
def test_accents_with_dead_keys(self) -> None:
# ê, ï, ñ, ü, â : absents de la rangée de touches ou obtenus par touche morte
text = "ê ï ñ ü â Ê Ö ã û"
typed, skipped = self.simulate(FR_LATIN9, text)
self.assertEqual((typed, skipped), (text, []))
def test_partial_text_only_loses_the_unavailable_characters(self) -> None:
typed, skipped = self.simulate(US, "abc → def")
self.assertEqual(skipped, ["→"])
self.assertEqual(typed, "abc def")
def test_newline_and_tab(self) -> None:
typed, _ = self.simulate(US, "a\tb\nc")
# Entrée produit « \r » dans xkb ; les applications le lisent comme la touche Entrée
self.assertEqual(typed, "a\tb\rc")
class FakeKeyboard:
"""Remplace VirtualInput : enregistre les événements et suit les touches enfoncées."""
available = True
reason = ""
def __init__(self) -> None:
self.events: list[tuple[int, bool]] = []
self.down: set[int] = set()
def write_keys(self, events: list[tuple[int, bool]]) -> None:
for code, pressed in events:
assert code in TYPING_KEYS
self.events.append((code, pressed))
(self.down.add if pressed else self.down.discard)(code)
def typer(keyboard: Any = None, enabled: bool = True, spec: LayoutSpec = US, delay: float = 0) -> TextTyper:
async def layout() -> LayoutSpec:
return spec
return TextTyper(keyboard or FakeKeyboard(), enabled, layout, delay)
class TextTyperTest(unittest.IsolatedAsyncioTestCase):
async def test_event_order_with_modifiers(self) -> None:
keyboard = FakeKeyboard()
await typer(keyboard).type("aA")
self.assertEqual(
keyboard.events,
[
(KEY_A, True), (KEY_A, False),
(KEY_LEFTSHIFT, True), (KEY_A, True), (KEY_A, False), (KEY_LEFTSHIFT, False),
],
)
self.assertEqual(keyboard.down, set())
async def test_layout_is_read_on_each_call(self) -> None:
keyboard = FakeKeyboard()
spec = [US]
async def layout() -> LayoutSpec:
return spec[0]
text_typer = TextTyper(keyboard, True, layout, 0)
await text_typer.type("a")
spec[0] = FR
await text_typer.type("a")
self.assertEqual([code for code, pressed in keyboard.events if pressed], [KEY_A, KEY_Q])
async def test_unavailable_characters_are_typed_around_then_reported(self) -> None:
keyboard = FakeKeyboard()
with self.assertRaisesRegex(ValueError, "→"):
await typer(keyboard).type("a→b")
self.assertEqual([code for code, pressed in keyboard.events if pressed], [KEY_A, 48])
async def test_validation(self) -> None:
for bad in ("", None, 5, ["a"], "x" * (MAX_TEXT_LENGTH + 1)):
with self.subTest(bad=bad), self.assertRaises(ValueError):
await typer().type(bad)
async def test_disabled_by_config(self) -> None:
disabled = typer(enabled=False)
self.assertFalse(disabled.available)
self.assertIn("features.text_input", disabled.snapshot()["reason"])
with self.assertRaises(RuntimeError):
await disabled.type("a")
async def test_keyboard_unavailable(self) -> None:
keyboard = FakeKeyboard()
keyboard.available = False
keyboard.reason = "cannot open /dev/uinput"
text_typer = typer(keyboard)
self.assertEqual(text_typer.snapshot(), {"available": False, "reason": "cannot open /dev/uinput"})
async def test_concurrent_texts_do_not_interleave(self) -> None:
keyboard = FakeKeyboard()
text_typer = typer(keyboard, delay=0.001)
await asyncio.gather(text_typer.type("aaaa"), text_typer.type("bbbb"))
pressed = [code for code, is_down in keyboard.events if is_down]
self.assertEqual(pressed, [KEY_A] * 4 + [48] * 4)
async def test_cancellation_never_leaves_a_key_down(self) -> None:
keyboard = FakeKeyboard()
text_typer = typer(keyboard, delay=0.05)
task = asyncio.create_task(text_typer.type("AAAA"))
await asyncio.sleep(0.02) # Maj + A sont enfoncées, la pause est en cours
self.assertTrue(keyboard.down)
task.cancel()
with self.assertRaises(asyncio.CancelledError):
await task
self.assertEqual(keyboard.down, set())
class VirtualInputKeysTest(unittest.TestCase):
class Device:
def __init__(self) -> None:
self.written: list[tuple[int, int, int]] = []
self.synced = 0
def write(self, event_type: int, code: int, value: int) -> None:
self.written.append((event_type, code, value))
def syn(self) -> None:
self.synced += 1
def close(self) -> None:
pass
def make(self) -> tuple[VirtualInput, "VirtualInputKeysTest.Device"]:
keyboard_input = VirtualInput(False)
device = self.Device()
keyboard_input._keyboard = device
keyboard_input._pointer = self.Device()
return keyboard_input, device
def test_write_keys_syncs_once(self) -> None:
keyboard_input, device = self.make()
keyboard_input.write_keys([(KEY_LEFTSHIFT, True), (KEY_A, True)])
self.assertEqual([(code, value) for _type, code, value in device.written], [(KEY_LEFTSHIFT, 1), (KEY_A, 1)])
self.assertEqual(device.synced, 1)
def test_keys_outside_the_typing_block_are_refused(self) -> None:
keyboard_input, device = self.make()
for code in (116, 142, 205, 0, 300): # POWER, SLEEP, SUSPEND, hors plage
with self.subTest(code=code), self.assertRaises(ValueError):
keyboard_input.write_keys([(code, True)])
self.assertEqual(device.written, [])
def test_unavailable_input(self) -> None:
with self.assertRaises(RuntimeError):
VirtualInput(False).write_keys([(KEY_A, True)])
if __name__ == "__main__":
unittest.main()
+143
View File
@@ -0,0 +1,143 @@
"""Tests du HTTPS local : génération des certificats, validation et poignée de main TLS."""
import asyncio
import os
import shutil
import ssl
import tempfile
import unittest
from pathlib import Path
from mediadeck.__main__ import client_url
from mediadeck.config import Config, ConfigError, load_config, parse_config
from mediadeck.tls import build_ssl_context, enable_tls, generate_certificates, is_permitted
TOKEN = "x" * 32
LAN_IP = "192.168.1.104"
class PermittedNamesTest(unittest.TestCase):
def test_private_addresses_and_local_names(self) -> None:
for host in (LAN_IP, "10.2.0.2", "172.20.0.1", "127.0.0.1", "localhost", "pc.local", "pc.lan", "pc"):
with self.subTest(host=host):
self.assertTrue(is_permitted(host, "pc"))
def test_public_names_refused(self) -> None:
for host in ("8.8.8.8", "172.32.0.1", "example.com", "evil.local.example.com", "::1"):
with self.subTest(host=host):
self.assertFalse(is_permitted(host, "pc"))
class ClientUrlTest(unittest.TestCase):
def test_scheme_follows_tls(self) -> None:
server = {"token": TOKEN, "advertise_host": LAN_IP}
self.assertTrue(client_url(parse_config({"server": server})).startswith(f"http://{LAN_IP}:8765/?token="))
tls = {**server, "tls_cert": "/c.pem", "tls_key": "/k.key"}
self.assertTrue(client_url(parse_config({"server": tls})).startswith(f"https://{LAN_IP}:8765/?token="))
@unittest.skipUnless(shutil.which("openssl"), "openssl is required")
class CertificateTest(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls._tmp = tempfile.TemporaryDirectory()
cls.directory = Path(cls._tmp.name) / "tls"
cls.ca, cls.cert, cls.key = generate_certificates(cls.directory, [LAN_IP, "localhost", "127.0.0.1"])
@classmethod
def tearDownClass(cls) -> None:
cls._tmp.cleanup()
def _config(self) -> Config:
server = {"token": TOKEN, "tls_cert": str(self.cert), "tls_key": str(self.key), "tls_ca": str(self.ca)}
return parse_config({"server": server})
def test_private_keys_are_personal(self) -> None:
self.assertEqual((self.directory / "ca.key").stat().st_mode & 0o077, 0)
self.assertEqual(self.key.stat().st_mode & 0o077, 0)
self.assertEqual(self.directory.stat().st_mode & 0o077, 0)
def test_public_name_refused(self) -> None:
with self.assertRaises(ConfigError):
generate_certificates(self.directory, ["example.com"])
def test_reissue_keeps_the_ca(self) -> None:
before = self.ca.read_bytes()
with tempfile.TemporaryDirectory() as tmp:
# Copie du dossier : le certificat serveur est réémis, la CA (donc la confiance de la tablette) reste
copy = Path(tmp) / "tls"
shutil.copytree(self.directory, copy)
generate_certificates(copy, [LAN_IP])
self.assertEqual((copy / "mediadeck-ca.crt").read_bytes(), before)
def test_world_readable_key_rejected(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
key = Path(tmp) / "server.key"
shutil.copy(self.key, key)
os.chmod(key, 0o644)
server = {"token": TOKEN, "tls_cert": str(self.cert), "tls_key": str(key)}
with self.assertRaises(ConfigError):
build_ssl_context(parse_config({"server": server}))
def test_missing_file_rejected(self) -> None:
server = {"token": TOKEN, "tls_cert": "/nonexistent.pem", "tls_key": str(self.key)}
with self.assertRaises(ConfigError):
build_ssl_context(parse_config({"server": server}))
def test_no_tls_without_certificate(self) -> None:
self.assertIsNone(build_ssl_context(parse_config({"server": {"token": TOKEN}})))
def test_handshake_verifies_with_the_ca(self) -> None:
# Le client se connecte en local mais vérifie le nom annoncé à la tablette
for name in (LAN_IP, "localhost", "127.0.0.1"):
with self.subTest(name=name):
asyncio.run(self._handshake(name, cafile=self.ca))
def test_handshake_refused_for_other_address(self) -> None:
with self.assertRaises(ssl.SSLCertVerificationError):
asyncio.run(self._handshake("192.168.1.105", cafile=self.ca))
def test_handshake_refused_without_the_ca(self) -> None:
with self.assertRaises(ssl.SSLCertVerificationError):
asyncio.run(self._handshake(LAN_IP, cafile=None))
async def _handshake(self, server_hostname: str, cafile: Path | None) -> None:
context = build_ssl_context(self._config())
server = await asyncio.start_server(lambda _reader, writer: writer.close(), "127.0.0.1", 0, ssl=context)
port = server.sockets[0].getsockname()[1]
client = ssl.create_default_context(cafile=str(cafile) if cafile else None)
try:
_reader, writer = await asyncio.open_connection(
"127.0.0.1", port, ssl=client, server_hostname=server_hostname
)
writer.close()
await writer.wait_closed()
finally:
server.close()
await server.wait_closed()
class EnableTlsTest(unittest.TestCase):
def test_inserts_paths_once(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "config.toml"
path.write_text(f'[server]\nhost = "0.0.0.0"\nport = 8765\ntoken = "{TOKEN}"\n\n[audio]\nmax_volume = 1.0\n')
os.chmod(path, 0o600)
cert, key, ca = Path("/t/server.pem"), Path("/t/server.key"), Path("/t/ca.crt")
self.assertTrue(enable_tls(path, cert, key, ca))
self.assertFalse(enable_tls(path, cert, key, ca))
config = load_config(path)
self.assertEqual((config.tls_cert, config.tls_key, config.tls_ca), (cert, key, ca))
self.assertEqual(config.max_volume, 1.0)
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
def test_missing_port_line(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "config.toml"
path.write_text(f'[server]\ntoken = "{TOKEN}"\n')
with self.assertRaises(ConfigError):
enable_tls(path, Path("/c"), Path("/k"), Path("/a"))
if __name__ == "__main__":
unittest.main()
+77
View File
@@ -0,0 +1,77 @@
"""Simulateur de clavier pour les tests : rejoue des frappes dans un état xkb avec composition des touches mortes.
Reproduit ce que fait le serveur graphique (X11 ou Wayland) avec les touches reçues d'un périphérique uinput.
"""
import ctypes
from mediadeck.keymap import Keymap, Stroke
_COMPOSING, _COMPOSED, _CANCELLED = 1, 2, 3
_KEY_UP, _KEY_DOWN = 0, 1
class SimulatorUnavailable(Exception):
"""Table de composition introuvable pour la locale demandée."""
class Simulator:
def __init__(self, keymap: Keymap, locale: str = "en_US.UTF-8") -> None:
self.keymap = keymap
lib = keymap.lib
vp, u32, cp, sz = ctypes.c_void_p, ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t
for name, restype, argtypes in (
("xkb_state_new", vp, [vp]),
("xkb_state_unref", None, [vp]),
("xkb_state_update_key", ctypes.c_int, [vp, u32, ctypes.c_int]),
("xkb_state_key_get_one_sym", u32, [vp, u32]),
("xkb_state_key_get_utf8", ctypes.c_int, [vp, u32, ctypes.c_char_p, sz]),
("xkb_compose_table_new_from_locale", vp, [vp, cp, ctypes.c_int]),
("xkb_compose_state_new", vp, [vp, ctypes.c_int]),
("xkb_compose_state_feed", ctypes.c_int, [vp, u32]),
("xkb_compose_state_get_status", ctypes.c_int, [vp]),
("xkb_compose_state_get_utf8", ctypes.c_int, [vp, ctypes.c_char_p, sz]),
("xkb_compose_state_reset", None, [vp]),
):
function = getattr(lib, name)
function.restype, function.argtypes = restype, argtypes
self.lib = lib
self.state = lib.xkb_state_new(keymap.handle)
table = lib.xkb_compose_table_new_from_locale(keymap._context, locale.encode(), 0)
if not table:
raise SimulatorUnavailable(locale)
self.compose = lib.xkb_compose_state_new(table, 0)
def _utf8(self, function, *args) -> str:
buffer = ctypes.create_string_buffer(64)
function(*args, buffer, 64)
return buffer.value.decode()
def type(self, strokes: list[Stroke]) -> str:
"""Texte obtenu après ces frappes (les touches mortes en attente ne produisent rien)."""
lib, output = self.lib, []
for stroke in strokes:
modifiers = [
code
for code, wanted in ((self.keymap.shift_code, stroke.shift), (self.keymap.altgr_code, stroke.altgr))
if wanted and code is not None
]
for code in modifiers:
lib.xkb_state_update_key(self.state, code + 8, _KEY_DOWN)
key = stroke.code + 8
keysym = lib.xkb_state_key_get_one_sym(self.state, key)
text = self._utf8(lib.xkb_state_key_get_utf8, self.state, key)
lib.xkb_state_update_key(self.state, key, _KEY_DOWN)
lib.xkb_state_update_key(self.state, key, _KEY_UP)
for code in reversed(modifiers):
lib.xkb_state_update_key(self.state, code + 8, _KEY_UP)
lib.xkb_compose_state_feed(self.compose, keysym)
status = lib.xkb_compose_state_get_status(self.compose)
if status == _COMPOSING:
continue
if status == _COMPOSED:
output.append(self._utf8(lib.xkb_compose_state_get_utf8, self.compose))
elif status != _CANCELLED:
output.append(text)
lib.xkb_compose_state_reset(self.compose)
return "".join(output)
+4
View File
@@ -0,0 +1,4 @@
# Donne accès à /dev/uinput à l'utilisateur de la session locale active (ACL logind).
# Plus restrictif que l'ajout au groupe « input », qui permettrait de lire tous les claviers.
# Le numéro doit rester < 73 pour être traité avant 73-seat-late.rules.
KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"