commit e823b2d470aef75add06afc8baef395d9e152242 Author: Denis Date: Fri Oct 23 23:33:10 2026 +0200 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 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..504bedf --- /dev/null +++ b/.editorconfig @@ -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 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b3e96ca --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..36183b2 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f6555b9 --- /dev/null +++ b/CLAUDE.md @@ -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": "", "value": …} +{"domain": "audio", "action": "set_volume|toggle_mute|set_default", "sink": "", "value": 0.0-max_volume} +{"domain": "input", "action": "key", "key": ""} +{"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": ""} +``` + +- `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 ` 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=`, 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 `) 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`). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..17063bd --- /dev/null +++ b/LICENSE @@ -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. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9f0cce1 --- /dev/null +++ b/Makefile @@ -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) diff --git a/README-EN.md b/README-EN.md new file mode 100644 index 0000000..3ec3fca --- /dev/null +++ b/README-EN.md @@ -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://: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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..a29c5d6 --- /dev/null +++ b/README.md @@ -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://: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 diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..a4723e8 --- /dev/null +++ b/config.example.toml @@ -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://:/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"] diff --git a/mediadeck/__init__.py b/mediadeck/__init__.py new file mode 100644 index 0000000..22d09f7 --- /dev/null +++ b/mediadeck/__init__.py @@ -0,0 +1,3 @@ +"""MediaDeck : télécommande web pour PC multimédia Linux (MPRIS, PipeWire, uinput, logind).""" + +__version__ = "0.1.0" diff --git a/mediadeck/__main__.py b/mediadeck/__main__.py new file mode 100644 index 0000000..2cfa348 --- /dev/null +++ b/mediadeck/__main__.py @@ -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()) diff --git a/mediadeck/admin.py b/mediadeck/admin.py new file mode 100644 index 0000000..042b5ac --- /dev/null +++ b/mediadeck/admin.py @@ -0,0 +1,160 @@ +"""API REST d'administration des lanceurs (page /admin). + +Authentification par ``Authorization: Bearer `` : 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"}) diff --git a/mediadeck/audio.py b/mediadeck/audio.py new file mode 100644 index 0000000..ae168e5 --- /dev/null +++ b/mediadeck/audio.py @@ -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}'") diff --git a/mediadeck/config.py b/mediadeck/config.py new file mode 100644 index 0000000..721b668 --- /dev/null +++ b/mediadeck/config.py @@ -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) diff --git a/mediadeck/input.py b/mediadeck/input.py new file mode 100644 index 0000000..8891a6d --- /dev/null +++ b/mediadeck/input.py @@ -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))) diff --git a/mediadeck/keymap.py b/mediadeck/keymap.py new file mode 100644 index 0000000..98420c7 --- /dev/null +++ b/mediadeck/keymap.py @@ -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] diff --git a/mediadeck/launchers.py b/mediadeck/launchers.py new file mode 100644 index 0000000..f520b47 --- /dev/null +++ b/mediadeck/launchers.py @@ -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 diff --git a/mediadeck/mpris.py b/mediadeck/mpris.py new file mode 100644 index 0000000..632f8cd --- /dev/null +++ b/mediadeck/mpris.py @@ -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 diff --git a/mediadeck/server.py b/mediadeck/server.py new file mode 100644 index 0000000..5686824 --- /dev/null +++ b/mediadeck/server.py @@ -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 diff --git a/mediadeck/system.py b/mediadeck/system.py new file mode 100644 index 0000000..5f9fa34 --- /dev/null +++ b/mediadeck/system.py @@ -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)) diff --git a/mediadeck/text.py b/mediadeck/text.py new file mode 100644 index 0000000..1e83e46 --- /dev/null +++ b/mediadeck/text.py @@ -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() diff --git a/mediadeck/tls.py b/mediadeck/tls.py new file mode 100644 index 0000000..0e150be --- /dev/null +++ b/mediadeck/tls.py @@ -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 diff --git a/mediadeck/web/admin.html b/mediadeck/web/admin.html new file mode 100644 index 0000000..5d51851 --- /dev/null +++ b/mediadeck/web/admin.html @@ -0,0 +1,98 @@ + + + + + + + MediaDeck – Lanceurs + + + + + + +
+ +

+ +
+ +
+

+ + +
    + + + +
    + + +
    +

    + + + +
    + + +
    + +
    + + + + +
    + + + + + + + +
    + + +
    +
    +
    + + + + diff --git a/mediadeck/web/index.html b/mediadeck/web/index.html new file mode 100644 index 0000000..29a5912 --- /dev/null +++ b/mediadeck/web/index.html @@ -0,0 +1,256 @@ + + + + + + + + MediaDeck + + + + + + + + + +
    +
    +
    + + +
    +
    + + +
    +
    + +
    + +
    +
    + +

    +
    + +
    + + + + + + + + + + + + +
    + + + + + +
    +

    + + +
    + + + +
    +

    +
    + + + +
    +
    +
    + + + + +
    + + diff --git a/mediadeck/web/static/admin.css b/mediadeck/web/static/admin.css new file mode 100644 index 0000000..0b15d6f --- /dev/null +++ b/mediadeck/web/static/admin.css @@ -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; + } +} diff --git a/mediadeck/web/static/admin.js b/mediadeck/web/static/admin.js new file mode 100644 index 0000000..fa2815f --- /dev/null +++ b/mediadeck/web/static/admin.js @@ -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(); diff --git a/mediadeck/web/static/app.js b/mediadeck/web/static/app.js new file mode 100644 index 0000000..d157a16 --- /dev/null +++ b/mediadeck/web/static/app.js @@ -0,0 +1,1052 @@ +// MediaDeck : interface tablette. Une classe par responsabilité. + +import { $, I18n, Storage, STORAGE_TOKEN } from "./common.js"; + +const STORAGE_TAB = "mediadeck.tab"; + +// ---------------------------------------------------------------------- +// Traductions fr/en +// ---------------------------------------------------------------------- + +const MESSAGES = { + fr: { + "status.connecting": "Connexion…", + "status.online": "Connecté", + "status.offline": "Hors ligne", + "status.auth": "Jeton refusé ?", + "action.fullscreen": "Plein écran", + "tab.player": "Lecture", + "tab.audio": "Son", + "tab.remote": "Pavé", + "tab.launchers": "Lanceurs", + "tab.system": "Système", + "player.none": "Aucun lecteur multimédia actif", + "player.unknown": "Titre inconnu", + "player.seek": "Position", + "player.shuffle": "Aléatoire", + "player.previous": "Précédent", + "player.play_pause": "Lecture / pause", + "player.next": "Suivant", + "player.loop": "Répétition", + "player.volume": "Volume du lecteur", + "player.raise": "Afficher la fenêtre", + "audio.none": "Contrôle audio indisponible (pactl absent)", + "audio.master": "Volume principal", + "audio.mute": "Couper le son", + "audio.outputs": "Sorties audio", + "audio.default": "Par défaut", + "remote.none": "Clavier et souris virtuels indisponibles", + "remote.hint": "Glisser : déplacer · Toucher : clic · 2 doigts : défiler / clic droit", + "text.open": "Clavier", + "text.title": "Saisie de texte", + "text.placeholder": "Texte à saisir sur le PC", + "text.hint": "Tapé dans la fenêtre active du PC, comme sur son clavier.", + "text.mask": "Masquer le texte", + "text.send": "Envoyer", + "text.send_enter": "Envoyer ↵", + "text.close": "Fermer", + "text.sent": "Texte envoyé", + "text.unavailable": "Saisie de texte indisponible : {reason}", + "key.up": "Haut", + "key.down": "Bas", + "key.left": "Gauche", + "key.right": "Droite", + "key.space": "Espace", + "key.meta": "Super", + "key.back": "Effacer", + "key.page_up": "Pg ↑", + "key.page_down": "Pg ↓", + "launchers.title": "Applications et sites", + "launchers.manage": "Gérer", + "launchers.empty": "Aucun lanceur. Ajoutez-en depuis « Gérer ».", + "launchers.launched": "Lancé : {name}", + "system.session": "Session", + "system.lock": "Verrouiller", + "system.suspend": "Veille", + "system.reboot": "Redémarrer", + "system.poweroff": "Éteindre", + "system.hold_hint": "Maintenir appuyé 1 seconde pour veille, redémarrage et extinction.", + "system.power_unavailable": "Actions d'alimentation indisponibles", + "token.title": "Jeton d'accès manquant", + "token.help": "Ouvrez l'URL complète affichée sur le PC (ou scannez son QR code) :", + "error.prefix": "Erreur : {message}", + }, + en: { + "status.connecting": "Connecting…", + "status.online": "Connected", + "status.offline": "Offline", + "status.auth": "Token rejected?", + "action.fullscreen": "Fullscreen", + "tab.player": "Playing", + "tab.audio": "Sound", + "tab.remote": "Touchpad", + "tab.launchers": "Launchers", + "tab.system": "System", + "player.none": "No active media player", + "player.unknown": "Unknown title", + "player.seek": "Position", + "player.shuffle": "Shuffle", + "player.previous": "Previous", + "player.play_pause": "Play / pause", + "player.next": "Next", + "player.loop": "Repeat", + "player.volume": "Player volume", + "player.raise": "Show window", + "audio.none": "Audio control unavailable (pactl missing)", + "audio.master": "Master volume", + "audio.mute": "Mute", + "audio.outputs": "Audio outputs", + "audio.default": "Default", + "remote.none": "Virtual keyboard and mouse unavailable", + "remote.hint": "Drag: move · Tap: click · 2 fingers: scroll / right click", + "text.open": "Keyboard", + "text.title": "Text entry", + "text.placeholder": "Text to type on the PC", + "text.hint": "Typed into the PC's active window, as on its keyboard.", + "text.mask": "Hide text", + "text.send": "Send", + "text.send_enter": "Send ↵", + "text.close": "Close", + "text.sent": "Text sent", + "text.unavailable": "Text entry unavailable: {reason}", + "key.up": "Up", + "key.down": "Down", + "key.left": "Left", + "key.right": "Right", + "key.space": "Space", + "key.meta": "Super", + "key.back": "Backspace", + "key.page_up": "PgUp", + "key.page_down": "PgDn", + "launchers.title": "Apps and sites", + "launchers.manage": "Manage", + "launchers.empty": "No launcher yet. Add some from “Manage”.", + "launchers.launched": "Launched: {name}", + "system.session": "Session", + "system.lock": "Lock", + "system.suspend": "Sleep", + "system.reboot": "Restart", + "system.poweroff": "Shut down", + "system.hold_hint": "Hold for 1 second to sleep, restart or shut down.", + "system.power_unavailable": "Power actions unavailable", + "token.title": "Missing access token", + "token.help": "Open the full URL shown on the PC (or scan its QR code):", + "error.prefix": "Error: {message}", + }, +}; + +// ---------------------------------------------------------------------- +// Utilitaires +// ---------------------------------------------------------------------- + +class Throttle { + // Limite la fréquence d'envoi tout en garantissant l'envoi de la dernière valeur + constructor(delayMs, callback) { + this.delayMs = delayMs; + this.callback = callback; + this.timer = null; + this.pending = undefined; + this.last = 0; + } + + push(value) { + this.pending = value; + const wait = this.delayMs - (performance.now() - this.last); + if (wait <= 0) { + this.flush(); + } else if (this.timer === null) { + this.timer = setTimeout(() => this.flush(), wait); + } + } + + flush() { + if (this.timer !== null) { + clearTimeout(this.timer); + this.timer = null; + } + if (this.pending === undefined) { + return; + } + const value = this.pending; + this.pending = undefined; + this.last = performance.now(); + this.callback(value); + } +} + +function formatTime(microseconds) { + const total = Math.max(0, Math.floor(microseconds / 1e6)); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const seconds = String(total % 60).padStart(2, "0"); + return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${seconds}` : `${minutes}:${seconds}`; +} + +// Met à jour la couleur de remplissage d'un input range via une variable CSS +function paintRange(input) { + const min = Number(input.min) || 0; + const max = Number(input.max) || 100; + const ratio = max > min ? (Number(input.value) - min) / (max - min) : 0; + input.style.setProperty("--fill", `${(ratio * 100).toFixed(2)}%`); +} + +// ---------------------------------------------------------------------- +// Connexion WebSocket avec reconnexion +// ---------------------------------------------------------------------- + +class Connection extends EventTarget { + constructor(token) { + super(); + this.token = token; + this.socket = null; + this.retryDelay = 500; + this.failuresBeforeOpen = 0; + this.everOpened = false; + } + + connect() { + const scheme = location.protocol === "https:" ? "wss" : "ws"; + const url = `${scheme}://${location.host}/ws?token=${encodeURIComponent(this.token)}`; + this.emit("status", "connecting"); + this.socket = new WebSocket(url); + this.socket.addEventListener("open", () => { + this.retryDelay = 500; + this.failuresBeforeOpen = 0; + this.everOpened = true; + this.emit("status", "online"); + }); + this.socket.addEventListener("message", (event) => { + try { + const message = JSON.parse(event.data); + this.emit(message.type, message); + } catch (error) { + console.error("invalid message", error); + } + }); + this.socket.addEventListener("close", () => this.scheduleReconnect()); + } + + scheduleReconnect() { + this.socket = null; + // Échecs répétés sans jamais ouvrir : probablement un jeton invalide (HTTP 401) + this.failuresBeforeOpen += 1; + const suspectAuth = !this.everOpened && this.failuresBeforeOpen >= 3; + this.emit("status", suspectAuth ? "auth" : "offline"); + setTimeout(() => this.connect(), this.retryDelay); + this.retryDelay = Math.min(this.retryDelay * 2, 8000); + } + + send(message) { + if (this.socket && this.socket.readyState === WebSocket.OPEN) { + this.socket.send(JSON.stringify(message)); + } + } + + emit(type, detail) { + this.dispatchEvent(new CustomEvent(type, { detail })); + } +} + +// ---------------------------------------------------------------------- +// Panneau lecture (MPRIS) +// ---------------------------------------------------------------------- + +class PlayerPanel { + constructor(connection, i18n) { + this.connection = connection; + this.i18n = i18n; + this.players = []; + this.selected = null; + this.userSelected = false; + this.receivedAt = 0; + this.seeking = false; + + this.els = { + empty: $("player-empty"), + view: $("player-view"), + tabs: $("player-tabs"), + coverImg: $("cover-img"), + title: $("track-title"), + artist: $("track-artist"), + album: $("track-album"), + seek: $("seek"), + pos: $("time-pos"), + len: $("time-len"), + playIcon: $("play-icon"), + shuffle: $("btn-shuffle"), + loop: $("btn-loop"), + loopBadge: $("loop-badge"), + volumeRow: $("player-volume-row"), + volume: $("player-volume"), + raise: $("btn-raise"), + }; + + this.volumeThrottle = new Throttle(80, (value) => this.command("set_volume", value)); + this.bindEvents(); + // Interpolation locale de la position entre deux états serveur + setInterval(() => this.renderPosition(), 250); + } + + get current() { + return this.players.find((player) => player.name === this.selected) ?? null; + } + + command(action, value) { + const player = this.current; + if (player) { + this.connection.send({ domain: "player", action, player: player.name, value }); + } + } + + bindEvents() { + $("btn-play").addEventListener("click", () => this.command("play_pause")); + $("btn-next").addEventListener("click", () => this.command("next")); + $("btn-prev").addEventListener("click", () => this.command("previous")); + this.els.shuffle.addEventListener("click", () => { + this.command("shuffle", !this.current?.shuffle); + }); + this.els.loop.addEventListener("click", () => { + const order = ["None", "Playlist", "Track"]; + const index = order.indexOf(this.current?.loop ?? "None"); + this.command("loop", order[(index + 1) % order.length]); + }); + this.els.raise.addEventListener("click", () => this.command("raise")); + + const seek = this.els.seek; + seek.addEventListener("pointerdown", () => { + this.seeking = true; + }); + seek.addEventListener("input", () => { + this.seeking = true; + const length = this.current?.metadata.length ?? 0; + this.els.pos.textContent = formatTime((Number(seek.value) / 1000) * length); + paintRange(seek); + }); + seek.addEventListener("change", () => { + const player = this.current; + if (player && player.metadata.length > 0) { + // Seek relatif : fonctionne même sans trackid valide + const target = (Number(seek.value) / 1000) * player.metadata.length; + this.command("seek", Math.round(target - this.position(player))); + } + this.seeking = false; + }); + + this.els.volume.addEventListener("input", () => { + paintRange(this.els.volume); + this.volumeThrottle.push(Number(this.els.volume.value) / 100); + }); + } + + update(mpris) { + this.players = mpris.players ?? []; + this.receivedAt = performance.now(); + const exists = this.players.some((player) => player.name === this.selected); + // Suit automatiquement le lecteur actif tant que l'utilisateur n'a rien choisi + if (!exists || !this.userSelected) { + this.selected = mpris.active; + this.userSelected = this.userSelected && exists; + } + this.render(); + } + + position(player) { + let position = player.position ?? 0; + if (player.status === "Playing") { + position += (performance.now() - this.receivedAt) * 1000; + } + const length = player.metadata.length ?? 0; + return length > 0 ? Math.min(position, length) : position; + } + + render() { + const player = this.current; + this.els.empty.hidden = player !== null; + this.els.view.hidden = player === null; + this.renderTabs(); + if (!player) { + return; + } + + const meta = player.metadata; + this.els.title.textContent = meta.title || this.i18n.t("player.unknown"); + this.els.artist.textContent = meta.artist || ""; + this.els.album.textContent = meta.album || ""; + this.renderCover(meta.art); + + const playing = player.status === "Playing"; + this.els.playIcon.setAttribute("href", playing ? "#i-pause" : "#i-play"); + $("btn-next").disabled = !player.can_next; + $("btn-prev").disabled = !player.can_previous; + this.els.seek.disabled = !player.can_seek || !(meta.length > 0); + + this.els.shuffle.hidden = player.shuffle === null || player.shuffle === undefined; + this.els.shuffle.classList.toggle("on", Boolean(player.shuffle)); + this.els.loop.hidden = !player.loop; + this.els.loop.classList.toggle("on", Boolean(player.loop) && player.loop !== "None"); + this.els.loopBadge.hidden = player.loop !== "Track"; + + const hasVolume = typeof player.volume === "number"; + this.els.volumeRow.hidden = !hasVolume; + if (hasVolume && document.activeElement !== this.els.volume) { + this.els.volume.value = String(Math.round(player.volume * 100)); + paintRange(this.els.volume); + } + this.els.raise.hidden = !player.can_raise; + this.renderPosition(); + } + + renderTabs() { + const tabs = this.els.tabs; + tabs.hidden = this.players.length < 2; + tabs.replaceChildren( + ...this.players.map((player) => { + const button = document.createElement("button"); + button.type = "button"; + button.className = "chip" + (player.name === this.selected ? " active" : ""); + button.textContent = player.identity; + if (player.status === "Playing") { + button.classList.add("live"); + } + button.addEventListener("click", () => { + this.selected = player.name; + this.userSelected = true; + this.render(); + }); + return button; + }), + ); + } + + renderCover(src) { + const img = this.els.coverImg; + if (!src) { + img.hidden = true; + img.removeAttribute("src"); + return; + } + // Les pochettes locales passent par /art, protégé par le jeton + const url = src.startsWith("/art") ? `${src}&token=${encodeURIComponent(this.connection.token)}` : src; + if (img.getAttribute("src") !== url) { + img.hidden = true; + img.onload = () => { + img.hidden = false; + }; + img.onerror = () => { + img.hidden = true; + }; + img.src = url; + } + } + + renderPosition() { + const player = this.current; + if (!player || this.seeking) { + return; + } + const length = player.metadata.length ?? 0; + const position = this.position(player); + this.els.pos.textContent = formatTime(position); + this.els.len.textContent = length > 0 ? formatTime(length) : "–:––"; + this.els.seek.value = length > 0 ? String(Math.round((position / length) * 1000)) : "0"; + paintRange(this.els.seek); + } +} + +// ---------------------------------------------------------------------- +// Panneau son (PipeWire via pactl) +// ---------------------------------------------------------------------- + +class AudioPanel { + constructor(connection, i18n) { + this.connection = connection; + this.i18n = i18n; + this.state = null; + this.dragging = new Set(); + this.throttles = new Map(); + + this.els = { + empty: $("audio-empty"), + view: $("audio-view"), + mute: $("master-mute"), + muteIcon: $("master-mute-icon"), + volume: $("master-volume"), + value: $("master-value"), + name: $("master-name"), + list: $("sink-list"), + }; + + this.els.mute.addEventListener("click", () => this.command("toggle_mute", this.defaultSink?.name)); + this.bindSlider(this.els.volume, () => this.defaultSink?.name, (value) => { + this.els.value.textContent = `${value} %`; + }); + } + + get defaultSink() { + return this.state?.sinks.find((sink) => sink.name === this.state.default) ?? null; + } + + command(action, sink, value) { + this.connection.send({ domain: "audio", action, sink, value }); + } + + throttleFor(sinkName) { + if (!this.throttles.has(sinkName)) { + this.throttles.set( + sinkName, + new Throttle(80, (value) => this.command("set_volume", sinkName, value)), + ); + } + return this.throttles.get(sinkName); + } + + // Branche un slider de volume : envoi limité en fréquence, pas de mise à jour serveur pendant le geste + bindSlider(input, sinkName, onValue) { + input.addEventListener("pointerdown", () => this.dragging.add(input)); + const release = () => this.dragging.delete(input); + input.addEventListener("pointerup", release); + input.addEventListener("pointercancel", release); + input.addEventListener("change", release); + input.addEventListener("input", () => { + const name = sinkName(); + paintRange(input); + onValue?.(input.value); + if (name) { + this.throttleFor(name).push(Number(input.value) / 100); + } + }); + } + + update(audio) { + this.state = audio; + this.els.empty.hidden = audio.available; + this.els.view.hidden = !audio.available; + if (!audio.available) { + return; + } + const maxPercent = Math.round((audio.max_volume ?? 1) * 100); + const sink = this.defaultSink; + this.els.volume.max = String(maxPercent); + if (sink) { + if (!this.dragging.has(this.els.volume)) { + this.els.volume.value = String(Math.round(sink.volume * 100)); + this.els.value.textContent = `${this.els.volume.value} %`; + paintRange(this.els.volume); + } + this.els.name.textContent = sink.description; + this.els.muteIcon.setAttribute("href", sink.muted ? "#i-mute" : "#i-volume"); + this.els.mute.classList.toggle("on", sink.muted); + this.els.volume.classList.toggle("muted", sink.muted); + } + this.renderSinks(maxPercent); + } + + renderSinks(maxPercent) { + // Ne reconstruit pas la liste pendant un geste : on perdrait le slider en cours + if ([...this.dragging].some((el) => this.els.list.contains(el))) { + return; + } + const items = this.state.sinks.map((sink) => { + const li = document.createElement("li"); + li.className = "sink" + (sink.name === this.state.default ? " default" : ""); + + const select = document.createElement("button"); + select.type = "button"; + select.className = "sink-select"; + const radio = document.createElement("span"); + radio.className = "radio"; + const label = document.createElement("span"); + label.className = "sink-name"; + label.textContent = sink.description; + select.append(radio, label); + if (sink.name === this.state.default) { + const tag = document.createElement("span"); + tag.className = "tag"; + tag.textContent = this.i18n.t("audio.default"); + select.append(tag); + } + select.addEventListener("click", () => this.command("set_default", sink.name)); + + const row = document.createElement("div"); + row.className = "slider-row"; + const mute = document.createElement("button"); + mute.type = "button"; + mute.className = "icon-btn small" + (sink.muted ? " on" : ""); + mute.innerHTML = ``; + mute.setAttribute("aria-label", this.i18n.t("audio.mute")); + mute.addEventListener("click", () => this.command("toggle_mute", sink.name)); + const range = document.createElement("input"); + range.type = "range"; + range.min = "0"; + range.max = String(maxPercent); + range.value = String(Math.round(sink.volume * 100)); + range.setAttribute("aria-label", sink.description); + const value = document.createElement("span"); + value.className = "value"; + value.textContent = `${range.value} %`; + this.bindSlider(range, () => sink.name, (v) => { + value.textContent = `${v} %`; + }); + paintRange(range); + row.append(mute, range, value); + + li.append(select, row); + return li; + }); + this.els.list.replaceChildren(...items); + } +} + +// ---------------------------------------------------------------------- +// Pavé tactile et touches (uinput) +// ---------------------------------------------------------------------- + +class Touchpad { + // Seuils des gestes + static TAP_MAX_MS = 220; + static TAP_MAX_MOVE = 8; + static LONG_PRESS_MS = 600; + static SCROLL_STEP_PX = 28; + + constructor(element, connection) { + this.element = element; + this.connection = connection; + this.pointers = new Map(); + this.moveDx = 0; + this.moveDy = 0; + this.scrollAccum = 0; + this.gesture = null; + this.frame = null; + this.longPressTimer = null; + + element.addEventListener("pointerdown", (event) => this.onDown(event)); + element.addEventListener("pointermove", (event) => this.onMove(event)); + element.addEventListener("pointerup", (event) => this.onUp(event)); + element.addEventListener("pointercancel", (event) => this.onUp(event)); + element.addEventListener("contextmenu", (event) => event.preventDefault()); + } + + send(action, payload = {}) { + this.connection.send({ domain: "input", action, ...payload }); + } + + onDown(event) { + event.preventDefault(); + this.element.setPointerCapture(event.pointerId); + this.pointers.set(event.pointerId, { x: event.clientX, y: event.clientY }); + if (this.pointers.size === 1) { + this.gesture = { start: performance.now(), moved: 0, fingers: 1, longPressed: false }; + this.longPressTimer = setTimeout(() => { + if (this.gesture && this.gesture.moved < Touchpad.TAP_MAX_MOVE && this.pointers.size === 1) { + this.gesture.longPressed = true; + this.send("click", { button: "right" }); + this.element.classList.add("flash"); + setTimeout(() => this.element.classList.remove("flash"), 150); + } + }, Touchpad.LONG_PRESS_MS); + } else if (this.gesture) { + this.gesture.fingers = Math.max(this.gesture.fingers, this.pointers.size); + clearTimeout(this.longPressTimer); + } + this.element.classList.add("active"); + } + + onMove(event) { + const previous = this.pointers.get(event.pointerId); + if (!previous || !this.gesture) { + return; + } + const dx = event.clientX - previous.x; + const dy = event.clientY - previous.y; + this.pointers.set(event.pointerId, { x: event.clientX, y: event.clientY }); + this.gesture.moved += Math.hypot(dx, dy); + + if (this.pointers.size >= 2) { + // Défilement à deux doigts : on n'utilise que le premier pointeur + if (event.pointerId === this.pointers.keys().next().value) { + this.scrollAccum += dy; + } + } else { + // Accélération simple : les gestes rapides couvrent plus de distance + const speed = Math.hypot(dx, dy); + const gain = 1.2 + Math.min(speed / 12, 2.3); + this.moveDx += dx * gain; + this.moveDy += dy * gain; + } + this.requestFlush(); + } + + onUp(event) { + this.pointers.delete(event.pointerId); + if (this.pointers.size > 0 || !this.gesture) { + return; + } + clearTimeout(this.longPressTimer); + const gesture = this.gesture; + this.gesture = null; + this.element.classList.remove("active"); + const quick = performance.now() - gesture.start < Touchpad.TAP_MAX_MS; + if (!gesture.longPressed && quick && gesture.moved < Touchpad.TAP_MAX_MOVE) { + this.send("click", { button: gesture.fingers >= 2 ? "right" : "left" }); + } + this.scrollAccum = 0; + } + + requestFlush() { + if (this.frame === null) { + this.frame = requestAnimationFrame(() => this.flush()); + } + } + + // Un message par frame au maximum + flush() { + this.frame = null; + const dx = Math.trunc(this.moveDx); + const dy = Math.trunc(this.moveDy); + if (dx !== 0 || dy !== 0) { + this.moveDx -= dx; + this.moveDy -= dy; + this.send("move", { dx, dy }); + } + const steps = Math.trunc(this.scrollAccum / Touchpad.SCROLL_STEP_PX); + if (steps !== 0) { + this.scrollAccum -= steps * Touchpad.SCROLL_STEP_PX; + // Défilement « naturel » : glisser vers le bas fait monter le contenu + this.send("scroll", { dy: steps }); + } + } +} + +class RemotePanel { + constructor(connection) { + this.connection = connection; + this.touchpad = new Touchpad($("touchpad"), connection); + document.querySelectorAll("#panel-remote [data-key]").forEach((button) => { + button.addEventListener("click", () => { + connection.send({ domain: "input", action: "key", key: button.dataset.key }); + }); + }); + } + + update(input) { + $("remote-empty").hidden = input.available; + $("remote-view").hidden = !input.available; + $("remote-reason").textContent = input.reason || ""; + } +} + +// Saisie de texte : le clavier de la tablette remplit le champ, le PC reçoit de vraies frappes +class TextPanel { + constructor(connection, i18n, toast) { + this.connection = connection; + this.i18n = i18n; + this.toast = toast; + this.dialog = $("text-dialog"); + this.input = $("text-input"); + + $("text-open").addEventListener("click", () => this.open()); + $("text-close").addEventListener("click", () => this.dialog.close()); + $("text-send").addEventListener("click", () => this.send(false)); + // La touche « Envoyer » du clavier tactile valide le formulaire : texte puis Entrée + $("text-form").addEventListener("submit", (event) => { + event.preventDefault(); + this.send(true); + }); + $("text-mask").addEventListener("change", () => { + this.input.type = $("text-mask").checked ? "password" : "text"; + }); + this.dialog.querySelectorAll("[data-text-key]").forEach((button) => { + button.addEventListener("click", () => { + connection.send({ domain: "input", action: "key", key: button.dataset.textKey }); + this.input.focus(); + }); + }); + } + + open() { + // Non modale : le pavé tactile reste utilisable (cliquer dans un champ du PC, puis taper) + this.dialog.show(); + this.input.focus(); + } + + // Le serveur traite les messages d'une connexion dans l'ordre : le texte est saisi avant l'Entrée + send(withEnter) { + const text = this.input.value; + if (text) { + this.connection.send({ domain: "input", action: "text", text }); + } + if (withEnter) { + this.connection.send({ domain: "input", action: "key", key: "enter" }); + } + if (text || withEnter) { + this.toast.show(this.i18n.t("text.sent")); + } + this.input.value = ""; + this.input.focus(); + } + + update(input) { + const text = input.text ?? { available: false, reason: "" }; + const button = $("text-open"); + button.disabled = !input.available || !text.available; + button.title = button.disabled ? this.i18n.t("text.unavailable", { reason: text.reason || input.reason }) : ""; + if (button.disabled && this.dialog.open) { + this.dialog.close(); + } + } +} + +// ---------------------------------------------------------------------- +// Panneau système +// ---------------------------------------------------------------------- + +class HoldButton { + // Bouton à maintenir : évite une extinction accidentelle depuis la tablette + static DURATION_MS = 1000; + + constructor(button, onConfirm) { + this.button = button; + this.timer = null; + const start = (event) => { + event.preventDefault(); + button.classList.add("holding"); + this.timer = setTimeout(() => { + this.cancel(); + onConfirm(); + }, HoldButton.DURATION_MS); + }; + button.addEventListener("pointerdown", start); + button.addEventListener("pointerup", () => this.cancel()); + button.addEventListener("pointerleave", () => this.cancel()); + button.addEventListener("pointercancel", () => this.cancel()); + button.addEventListener("contextmenu", (event) => event.preventDefault()); + } + + cancel() { + clearTimeout(this.timer); + this.timer = null; + this.button.classList.remove("holding"); + } +} + +class LauncherPanel { + // Icônes du sprite (index.html) ; à garder synchronisées avec ICONS de launchers.py + static ICONS = new Set(["app", "tv", "film", "globe", "music", "screen-off", "speaker", "lock", "window"]); + + constructor(connection, i18n, toast) { + this.connection = connection; + this.i18n = i18n; + this.toast = toast; + this.key = ""; + } + + update(system) { + $("launchers-manage").hidden = !system.admin; + + // Reconstruit la grille seulement si la liste a changé + const key = JSON.stringify(system.launchers); + if (key === this.key) { + return; + } + this.key = key; + $("launchers-empty").hidden = system.launchers.length > 0; + $("launcher-grid").replaceChildren( + ...system.launchers.map((launcher) => { + const button = document.createElement("button"); + button.type = "button"; + button.className = "launcher"; + const icon = LauncherPanel.ICONS.has(launcher.icon) ? launcher.icon : "app"; + button.innerHTML = ``; + const label = document.createElement("span"); + label.textContent = launcher.label; + button.append(label); + button.addEventListener("click", () => { + this.connection.send({ domain: "system", action: "launch", id: launcher.id }); + this.toast.show(this.i18n.t("launchers.launched", { name: launcher.label })); + }); + return button; + }), + ); + } +} + +// Opérations délicates : verrouillage, veille, redémarrage, extinction +class SystemPanel { + constructor(connection, i18n) { + this.i18n = i18n; + + document.querySelectorAll("[data-power]").forEach((button) => { + new HoldButton(button, () => { + connection.send({ domain: "system", action: "power", kind: button.dataset.power }); + }); + }); + document.querySelector('[data-system="lock"]').addEventListener("click", () => { + connection.send({ domain: "system", action: "lock" }); + }); + } + + update(system) { + document.querySelectorAll("[data-power]").forEach((button) => { + button.disabled = !system.power; + button.title = system.power ? "" : this.i18n.t("system.power_unavailable"); + }); + } +} + +// ---------------------------------------------------------------------- +// Éléments transverses +// ---------------------------------------------------------------------- + +class Toast { + constructor(element) { + this.element = element; + this.timer = null; + } + + show(text, isError = false) { + this.element.textContent = text; + this.element.classList.toggle("error", isError); + this.element.hidden = false; + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.element.hidden = true; + }, 2500); + } +} + +class Tabs { + constructor() { + this.buttons = [...document.querySelectorAll("#tabbar [data-tab]")]; + this.buttons.forEach((button) => { + button.addEventListener("click", () => this.select(button.dataset.tab)); + }); + this.select(Storage.get(STORAGE_TAB) || "player"); + } + + select(name) { + if (!this.buttons.some((button) => button.dataset.tab === name)) { + name = "player"; + } + this.buttons.forEach((button) => button.classList.toggle("active", button.dataset.tab === name)); + document.querySelectorAll("[data-panel]").forEach((panel) => { + panel.hidden = panel.dataset.panel !== name; + }); + Storage.set(STORAGE_TAB, name); + } +} + +class ScreenKeeper { + // Wake Lock : disponible uniquement en contexte sécurisé (HTTPS ou localhost) + constructor() { + this.lock = null; + if (!("wakeLock" in navigator)) { + return; + } + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") { + this.acquire(); + } + }); + this.acquire(); + } + + async acquire() { + try { + this.lock = await navigator.wakeLock.request("screen"); + } catch { + this.lock = null; + } + } +} + +// ---------------------------------------------------------------------- +// Application +// ---------------------------------------------------------------------- + +class App { + constructor() { + this.i18n = new I18n(MESSAGES); + this.i18n.apply(); + this.toast = new Toast($("toast")); + this.tabs = new Tabs(); + this.screenKeeper = new ScreenKeeper(); + this.lastState = null; + + const token = App.readToken(); + if (!token) { + $("no-token").hidden = false; + return; + } + + this.connection = new Connection(token); + this.player = new PlayerPanel(this.connection, this.i18n); + this.audio = new AudioPanel(this.connection, this.i18n); + this.remote = new RemotePanel(this.connection); + this.text = new TextPanel(this.connection, this.i18n, this.toast); + this.launchers = new LauncherPanel(this.connection, this.i18n, this.toast); + this.system = new SystemPanel(this.connection, this.i18n); + + this.bindTopbar(); + this.connection.addEventListener("state", (event) => this.onState(event.detail)); + this.connection.addEventListener("error", (event) => { + this.toast.show(this.i18n.t("error.prefix", { message: event.detail.message }), true); + }); + this.connection.addEventListener("status", (event) => this.onStatus(event.detail)); + this.i18n.onChange(() => { + this.updateLangButton(); + if (this.lastState) { + this.launchers.key = ""; + this.onState(this.lastState); + } + }); + this.updateLangButton(); + this.connection.connect(); + } + + // Le jeton est lu dans l'URL une fois, mémorisé, puis retiré de la barre d'adresse + static readToken() { + const params = new URLSearchParams(location.search); + const fromUrl = params.get("token"); + if (fromUrl) { + Storage.set(STORAGE_TOKEN, fromUrl); + history.replaceState(null, "", location.pathname); + return fromUrl; + } + return Storage.get(STORAGE_TOKEN); + } + + bindTopbar() { + $("lang-toggle").addEventListener("click", () => this.i18n.toggle()); + $("fullscreen").addEventListener("click", () => { + if (document.fullscreenElement) { + document.exitFullscreen?.(); + } else { + document.documentElement.requestFullscreen?.().catch(() => {}); + } + }); + } + + updateLangButton() { + // Le bouton affiche la langue vers laquelle on bascule + $("lang-toggle").textContent = this.i18n.lang === "fr" ? "EN" : "FR"; + } + + onStatus(status) { + $("status").dataset.state = status; + const text = $("status-text"); + text.dataset.i18n = `status.${status}`; + text.textContent = this.i18n.t(`status.${status}`); + } + + onState(state) { + this.lastState = state; + this.player.update(state.mpris); + this.audio.update(state.audio); + this.remote.update(state.input); + this.text.update(state.input); + this.launchers.update(state.system); + this.system.update(state.system); + } +} + +new App(); diff --git a/mediadeck/web/static/common.js b/mediadeck/web/static/common.js new file mode 100644 index 0000000..60df3d0 --- /dev/null +++ b/mediadeck/web/static/common.js @@ -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); +} diff --git a/mediadeck/web/static/icon.svg b/mediadeck/web/static/icon.svg new file mode 100644 index 0000000..89ef668 --- /dev/null +++ b/mediadeck/web/static/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/mediadeck/web/static/manifest.webmanifest b/mediadeck/web/static/manifest.webmanifest new file mode 100644 index 0000000..aab3cc8 --- /dev/null +++ b/mediadeck/web/static/manifest.webmanifest @@ -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" + } + ] +} diff --git a/mediadeck/web/static/style.css b/mediadeck/web/static/style.css new file mode 100644 index 0000000..ddb91c0 --- /dev/null +++ b/mediadeck/web/static/style.css @@ -0,0 +1,1084 @@ +/* MediaDeck : thème sombre pensé pour une tablette posée près du PC */ + +:root { + --bg: #0e0f13; + --surface: #171920; + --surface-2: #20232c; + --surface-3: #2a2e39; + --line: #2f3340; + --text: #eef0f5; + --text-dim: #9aa0ae; + --text-faint: #636a79; + --accent: #f5a524; + --accent-ink: #1b1305; + --danger: #ef5b5b; + --ok: #3ecf8e; + --radius: 18px; + --radius-sm: 12px; + --tap: 56px; + --font: "Inter", "Noto Sans", "Cantarell", system-ui, sans-serif; + color-scheme: dark; +} + +* { + box-sizing: border-box; + -webkit-tap-highlight-color: transparent; +} + +html, +body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--text); + font-family: var(--font); + -webkit-user-select: none; + user-select: none; + overscroll-behavior: none; +} + +[hidden] { + display: none !important; +} + +button { + font: inherit; + color: inherit; + border: 0; + background: none; + cursor: pointer; + touch-action: manipulation; +} + +button:disabled { + opacity: 0.35; + cursor: default; +} + +svg { + width: 24px; + height: 24px; + flex: none; +} + +.sprite { + display: none; +} + +/* ------------------------------------------------------------------ */ +/* Structure */ +/* ------------------------------------------------------------------ */ + +.app { + display: grid; + grid-template-rows: auto 1fr auto; + height: 100dvh; + padding: env(safe-area-inset-top) env(safe-area-inset-right) 0 env(safe-area-inset-left); +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 20px; +} + +.topbar-actions { + display: flex; + gap: 8px; + align-items: center; +} + +.status { + display: flex; + align-items: center; + gap: 10px; + font-size: 14px; + color: var(--text-dim); +} + +.status-dot { + width: 10px; + height: 10px; + border-radius: 50%; + background: var(--text-faint); +} + +.status[data-state="online"] .status-dot { + background: var(--ok); + box-shadow: 0 0 0 4px color-mix(in srgb, var(--ok) 20%, transparent); +} + +.status[data-state="connecting"] .status-dot { + background: var(--accent); + animation: pulse 1.2s ease-in-out infinite; +} + +.status[data-state="offline"] .status-dot, +.status[data-state="auth"] .status-dot { + background: var(--danger); +} + +@keyframes pulse { + 50% { + opacity: 0.3; + } +} + +.panels { + position: relative; + overflow: hidden; + min-height: 0; +} + +.panel { + height: 100%; + overflow-y: auto; + padding: 8px 24px 24px; +} + +.tabbar { + display: grid; + grid-auto-flow: column; + grid-auto-columns: 1fr; + gap: 6px; + padding: 8px 16px calc(8px + env(safe-area-inset-bottom)); + border-top: 1px solid var(--line); + background: var(--surface); +} + +.tab { + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + min-width: 0; + padding: 8px 0; + border-radius: var(--radius-sm); + color: var(--text-faint); + font-size: 13px; + font-weight: 500; +} + +.tab.active { + color: var(--accent); + background: var(--surface-2); +} + +/* ------------------------------------------------------------------ */ +/* Éléments communs */ +/* ------------------------------------------------------------------ */ + +.icon-btn { + display: inline-grid; + place-items: center; + width: var(--tap); + height: var(--tap); + border-radius: 50%; + color: var(--text-dim); + position: relative; + transition: background 0.15s, color 0.15s; +} + +.icon-btn:active:not(:disabled) { + background: var(--surface-3); +} + +.icon-btn.big svg { + width: 34px; + height: 34px; + color: var(--text); +} + +.icon-btn.small { + width: 44px; + height: 44px; +} + +.icon-btn.on { + color: var(--accent); +} + +.badge { + position: absolute; + top: 10px; + right: 8px; + font-size: 10px; + font-weight: 700; + color: var(--accent); +} + +.chip { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 40px; + padding: 0 16px; + border-radius: 999px; + background: var(--surface-2); + color: var(--text-dim); + font-size: 14px; + font-weight: 600; + white-space: nowrap; +} + +.chip svg { + width: 18px; + height: 18px; +} + +.chip.active { + background: var(--text); + color: var(--bg); +} + +.chip.live::before { + content: ""; + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--accent); +} + +.empty { + display: grid; + place-items: center; + align-content: center; + gap: 8px; + height: 100%; + color: var(--text-faint); + text-align: center; +} + +.empty svg { + width: 64px; + height: 64px; +} + +.sub { + color: var(--text-faint); + font-size: 14px; +} + +.section-title { + margin: 24px 0 12px; + font-size: 13px; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--text-faint); +} + +.section-title:first-child { + margin-top: 8px; +} + +/* Titre de section accompagné d'une action (lien « Gérer ») */ +.section-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin: 8px 0 12px; +} + +.section-head .section-title { + margin: 0; +} + +a.chip { + text-decoration: none; +} + +/* Sliders : piste remplie via --fill (mise à jour en JS) */ +input[type="range"] { + --fill: 0%; + -webkit-appearance: none; + appearance: none; + width: 100%; + height: 32px; + background: transparent; + touch-action: none; +} + +input[type="range"]::-webkit-slider-runnable-track { + height: 6px; + border-radius: 3px; + background: linear-gradient(to right, var(--accent) var(--fill), var(--surface-3) var(--fill)); +} + +input[type="range"]::-moz-range-track { + height: 6px; + border-radius: 3px; + background: linear-gradient(to right, var(--accent) var(--fill), var(--surface-3) var(--fill)); +} + +input[type="range"]::-webkit-slider-thumb { + -webkit-appearance: none; + width: 22px; + height: 22px; + margin-top: -8px; + border-radius: 50%; + background: var(--text); + box-shadow: 0 2px 8px rgb(0 0 0 / 0.5); +} + +input[type="range"]::-moz-range-thumb { + width: 22px; + height: 22px; + border: 0; + border-radius: 50%; + background: var(--text); +} + +input[type="range"].thick { + height: 48px; +} + +input[type="range"].thick::-webkit-slider-runnable-track { + height: 14px; + border-radius: 7px; +} + +input[type="range"].thick::-moz-range-track { + height: 14px; + border-radius: 7px; +} + +input[type="range"].thick::-webkit-slider-thumb { + width: 30px; + height: 30px; + margin-top: -8px; +} + +input[type="range"].muted::-webkit-slider-runnable-track { + background: linear-gradient(to right, var(--text-faint) var(--fill), var(--surface-3) var(--fill)); +} + +input[type="range"].muted::-moz-range-track { + background: linear-gradient(to right, var(--text-faint) var(--fill), var(--surface-3) var(--fill)); +} + +input[type="range"]:disabled { + opacity: 0.4; +} + +.slider-row { + display: flex; + align-items: center; + gap: 12px; + color: var(--text-dim); +} + +.slider-row .value { + min-width: 52px; + text-align: right; + font-variant-numeric: tabular-nums; + font-size: 14px; +} + +/* ------------------------------------------------------------------ */ +/* Lecture */ +/* ------------------------------------------------------------------ */ + +.now-playing { + display: grid; + grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr); + gap: 40px; + align-items: center; + height: 100%; +} + +.cover { + position: relative; + display: grid; + place-items: center; + aspect-ratio: 1; + width: 100%; + max-height: calc(100dvh - 220px); + justify-self: center; + border-radius: var(--radius); + background: var(--surface-2); + overflow: hidden; + box-shadow: 0 24px 60px rgb(0 0 0 / 0.55); +} + +.cover img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; +} + +.cover-fallback { + width: 30%; + height: 30%; + color: var(--surface-3); +} + +.track { + display: flex; + flex-direction: column; + min-width: 0; +} + +.player-tabs { + display: flex; + gap: 8px; + overflow-x: auto; + margin-bottom: 24px; + scrollbar-width: none; +} + +.track-title { + margin: 0; + font-size: clamp(24px, 3.6vw, 40px); + font-weight: 700; + line-height: 1.15; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.track-artist { + margin: 10px 0 0; + font-size: clamp(17px, 2vw, 22px); + color: var(--accent); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.track-album { + margin: 4px 0 0; + font-size: 15px; + color: var(--text-faint); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.progress { + margin-top: 28px; +} + +.times { + display: flex; + justify-content: space-between; + font-size: 13px; + color: var(--text-faint); + font-variant-numeric: tabular-nums; +} + +.transport { + display: flex; + align-items: center; + justify-content: space-between; + max-width: 440px; + margin: 16px auto 0; + width: 100%; +} + +.play-btn { + display: grid; + place-items: center; + width: 84px; + height: 84px; + border-radius: 50%; + background: var(--accent); + color: var(--accent-ink); + box-shadow: 0 10px 30px color-mix(in srgb, var(--accent) 35%, transparent); + transition: transform 0.1s; +} + +.play-btn:active { + transform: scale(0.94); +} + +.play-btn svg { + width: 40px; + height: 40px; +} + +.player-extra { + display: flex; + align-items: center; + gap: 16px; + margin-top: 24px; +} + +.player-extra .slider-row { + flex: 1; +} + +/* ------------------------------------------------------------------ */ +/* Son */ +/* ------------------------------------------------------------------ */ + +.audio-view { + max-width: 820px; + margin: 0 auto; +} + +.master { + display: flex; + align-items: center; + gap: 20px; + padding: 24px; + border-radius: var(--radius); + background: var(--surface); +} + +.mute-btn { + display: grid; + place-items: center; + width: 72px; + height: 72px; + border-radius: 50%; + background: var(--surface-2); + flex: none; +} + +.mute-btn svg { + width: 32px; + height: 32px; +} + +.mute-btn.on { + background: color-mix(in srgb, var(--danger) 20%, var(--surface-2)); + color: var(--danger); +} + +.master-body { + flex: 1; + min-width: 0; +} + +.master-head { + display: flex; + justify-content: space-between; + align-items: baseline; +} + +.master-head .label { + font-weight: 600; + font-size: 18px; +} + +.master-head .value { + font-size: 28px; + font-weight: 700; + font-variant-numeric: tabular-nums; +} + +.sink-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 10px; +} + +.sink { + padding: 12px 16px; + border-radius: var(--radius-sm); + background: var(--surface); + border: 1px solid transparent; +} + +.sink.default { + border-color: color-mix(in srgb, var(--accent) 45%, transparent); +} + +.sink-select { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + min-height: 44px; + text-align: left; +} + +.radio { + width: 20px; + height: 20px; + border-radius: 50%; + border: 2px solid var(--text-faint); + flex: none; +} + +.sink.default .radio { + border-color: var(--accent); + background: radial-gradient(circle, var(--accent) 45%, transparent 50%); +} + +.sink-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 500; +} + +.tag { + font-size: 12px; + color: var(--accent); + font-weight: 600; +} + +/* ------------------------------------------------------------------ */ +/* Pavé tactile */ +/* ------------------------------------------------------------------ */ + +.remote-view { + display: grid; + grid-template-columns: minmax(0, 1.6fr) minmax(280px, 1fr); + gap: 24px; + height: 100%; +} + +.touchpad { + position: relative; + display: grid; + place-items: end center; + padding: 16px; + border-radius: var(--radius); + background: + radial-gradient(circle at 1px 1px, var(--surface-3) 1px, transparent 0) 0 0 / 22px 22px, + var(--surface); + border: 1px solid var(--line); + touch-action: none; + transition: border-color 0.15s, background-color 0.15s; +} + +.touchpad.active { + border-color: color-mix(in srgb, var(--accent) 50%, transparent); +} + +.touchpad.flash { + background-color: var(--surface-2); +} + +.touchpad-hint { + font-size: 13px; + color: var(--text-faint); + text-align: center; + pointer-events: none; +} + +.remote-side { + display: flex; + flex-direction: column; + gap: 20px; + justify-content: center; +} + +.dpad { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-template-areas: + ". up ." + "left ok right" + ". down ."; + gap: 6px; + width: min(100%, 280px); + aspect-ratio: 1; + margin: 0 auto; +} + +.dpad-btn { + display: grid; + place-items: center; + border-radius: var(--radius-sm); + background: var(--surface-2); +} + +.dpad-btn:active, +.key:active, +.launcher:active, +.power-btn:active { + background: var(--surface-3); +} + +.dpad-btn svg { + width: 32px; + height: 32px; +} + +.dpad-btn.up { + grid-area: up; +} + +.dpad-btn.down { + grid-area: down; +} + +.dpad-btn.left { + grid-area: left; +} + +.dpad-btn.right { + grid-area: right; +} + +.dpad-btn.ok { + grid-area: ok; + border-radius: 50%; + background: var(--accent); + color: var(--accent-ink); + font-weight: 800; + font-size: 20px; +} + +.key-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; +} + +.key { + display: grid; + place-items: center; + height: var(--tap); + border-radius: var(--radius-sm); + background: var(--surface-2); + font-weight: 600; + font-size: 15px; +} + +/* ------------------------------------------------------------------ */ +/* Système */ +/* ------------------------------------------------------------------ */ + +.launcher-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); + gap: 12px; +} + +.launcher { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 12px; + aspect-ratio: 1.3; + padding: 12px; + border-radius: var(--radius); + background: var(--surface); + border: 1px solid var(--line); + font-weight: 600; + text-align: center; +} + +.launcher svg { + width: 40px; + height: 40px; + color: var(--accent); +} + +.power-grid { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 12px; +} + +.power-btn { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 22px 8px; + border-radius: var(--radius); + background: var(--surface); + border: 1px solid var(--line); + font-weight: 600; + overflow: hidden; +} + +.power-btn svg { + width: 32px; + height: 32px; +} + +/* Jauge de maintien : se remplit pendant 1 s */ +.power-btn.hold::after { + content: ""; + position: absolute; + left: 0; + bottom: 0; + height: 4px; + width: 0; + background: var(--accent); +} + +.power-btn.hold.holding::after { + width: 100%; + transition: width 1s linear; +} + +.power-btn.danger { + color: var(--danger); +} + +.power-btn.danger::after { + background: var(--danger); +} + +/* ------------------------------------------------------------------ */ +/* Toast et écran sans jeton */ +/* ------------------------------------------------------------------ */ + +.toast { + position: fixed; + left: 50%; + bottom: 104px; + transform: translateX(-50%); + max-width: calc(100vw - 32px); + padding: 12px 20px; + border-radius: 999px; + background: var(--text); + color: var(--bg); + font-weight: 600; + font-size: 15px; + box-shadow: 0 10px 30px rgb(0 0 0 / 0.5); +} + +.toast.error { + background: var(--danger); + color: #fff; +} + +.overlay { + position: fixed; + inset: 0; + display: grid; + place-items: center; + align-content: center; + gap: 12px; + padding: 32px; + background: var(--bg); + text-align: center; + color: var(--text-dim); +} + +.overlay svg { + width: 56px; + height: 56px; + color: var(--accent); +} + +.overlay h1 { + margin: 0; + color: var(--text); +} + +.overlay code { + padding: 8px 14px; + border-radius: var(--radius-sm); + background: var(--surface-2); + color: var(--accent); + user-select: text; +} + +/* ------------------------------------------------------------------ */ +/* Formulaires et dialogues (télécommande et page /admin) */ +/* ------------------------------------------------------------------ */ + +.banner { + margin: 12px 0; + padding: 12px 16px; + border-radius: var(--radius-sm); + background: color-mix(in srgb, var(--danger) 18%, var(--surface)); + border: 1px solid var(--danger); + color: var(--text); +} + +.primary { + min-height: 48px; + padding: 0 24px; + border-radius: 999px; + background: var(--accent); + color: var(--accent-ink); + font-weight: 700; +} + +dialog { + width: min(560px, calc(100vw - 24px)); + max-height: calc(100dvh - 24px); + padding: 20px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); + color: var(--text); +} + +dialog::backdrop { + background: rgb(0 0 0 / 0.65); +} + +dialog h2 { + margin: 0 0 16px; + font-size: 18px; +} + +.field { + display: grid; + gap: 6px; + margin-bottom: 14px; + font-size: 14px; + color: var(--text-dim); +} + +.field-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +input[type="text"], +input[type="password"], +input[type="url"], +input[type="search"], +select, +textarea { + width: 100%; + min-height: 48px; + padding: 10px 12px; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + background: var(--surface-2); + color: var(--text); + font: inherit; +} + +textarea { + font-family: ui-monospace, "DejaVu Sans Mono", monospace; + font-size: 14px; + resize: vertical; +} + +select[size] { + padding: 4px; +} + +input:focus-visible, +select:focus-visible, +textarea:focus-visible, +button:focus-visible, +a:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +textarea:disabled { + opacity: 0.55; +} + +.check { + display: flex; + align-items: center; + gap: 12px; + min-height: 48px; +} + +.check input { + width: 22px; + height: 22px; + accent-color: var(--accent); +} + +.form-actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 10px 12px; + margin-top: 16px; +} + +.form-actions .chip, +.form-actions .primary { + white-space: nowrap; +} + +/* Saisie de texte : fenêtre non modale, fixée en haut pour rester visible au-dessus du clavier tactile */ +dialog.top { + position: fixed; + top: calc(12px + env(safe-area-inset-top)); + bottom: auto; + left: 0; + right: 0; + margin: 0 auto; + z-index: 15; + box-shadow: 0 16px 40px rgb(0 0 0 / 0.55); +} + +input[type="text"], +input[type="password"] { + -webkit-user-select: text; + user-select: text; +} + +.quick-keys { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; + margin: 4px 0 14px; +} + +.key.wide { + grid-column: 1 / -1; + grid-auto-flow: column; + gap: 10px; + justify-content: center; +} + +.key svg { + width: 22px; + height: 22px; +} + +@media (max-width: 520px) { + .field-row { + grid-template-columns: 1fr; + gap: 0; + } +} + +/* ------------------------------------------------------------------ */ +/* Portrait / petits écrans */ +/* ------------------------------------------------------------------ */ + +@media (orientation: portrait), (max-width: 760px) { + .panel { + padding: 8px 16px 16px; + } + + .now-playing { + grid-template-columns: 1fr; + gap: 20px; + align-content: start; + height: auto; + } + + .cover { + width: min(100%, 46dvh); + } + + .remote-view { + grid-template-columns: 1fr; + grid-template-rows: minmax(260px, 1fr) auto; + } + + .power-grid { + grid-template-columns: repeat(2, 1fr); + } + + .master { + padding: 16px; + } +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..50553eb --- /dev/null +++ b/pyproject.toml @@ -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/*"] diff --git a/pyrightconfig.json b/pyrightconfig.json new file mode 100644 index 0000000..5d0741d --- /dev/null +++ b/pyrightconfig.json @@ -0,0 +1,8 @@ +{ + "include": ["mediadeck", "tests"], + "venvPath": ".", + "venv": ".venv", + "pythonVersion": "3.11", + "typeCheckingMode": "standard", + "reportMissingTypeStubs": false +} diff --git a/systemd/mediadeck.service.in b/systemd/mediadeck.service.in new file mode 100644 index 0000000..c4ebd70 --- /dev/null +++ b/systemd/mediadeck.service.in @@ -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 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_admin.py b/tests/test_admin.py new file mode 100644 index 0000000..5ef7654 --- /dev/null +++ b/tests/test_admin.py @@ -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() diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..9c641b8 --- /dev/null +++ b/tests/test_config.py @@ -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() diff --git a/tests/test_launchers.py b/tests/test_launchers.py new file mode 100644 index 0000000..be44c49 --- /dev/null +++ b/tests/test_launchers.py @@ -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() diff --git a/tests/test_parsing.py b/tests/test_parsing.py new file mode 100644 index 0000000..831e2e4 --- /dev/null +++ b/tests/test_parsing.py @@ -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() diff --git a/tests/test_text.py b/tests/test_text.py new file mode 100644 index 0000000..8cd5349 --- /dev/null +++ b/tests/test_text.py @@ -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() diff --git a/tests/test_tls.py b/tests/test_tls.py new file mode 100644 index 0000000..a20c2df --- /dev/null +++ b/tests/test_tls.py @@ -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() diff --git a/tests/xkbsim.py b/tests/xkbsim.py new file mode 100644 index 0000000..fac3447 --- /dev/null +++ b/tests/xkbsim.py @@ -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) diff --git a/udev/60-mediadeck-uinput.rules b/udev/60-mediadeck-uinput.rules new file mode 100644 index 0000000..eafd5f9 --- /dev/null +++ b/udev/60-mediadeck-uinput.rules @@ -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"