diff --git a/.gitignore b/.gitignore index 7b8dd04..a16765a 100644 --- a/.gitignore +++ b/.gitignore @@ -70,3 +70,6 @@ Thumbs.db *.dll *.exe + +# Log de tools/deploy.py +deploy.log diff --git a/.run/Local Deploy.run.xml b/.run/Local Deploy.run.xml new file mode 100644 index 0000000..9f28d61 --- /dev/null +++ b/.run/Local Deploy.run.xml @@ -0,0 +1,26 @@ + + + + + \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md index 5c076dc..acce070 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -A Jellyfin client for the Freebox Player (Revolution), written in pure QML (no C++). The app runs inside the Freebox's QML runtime via the `fbx.application` module, so it cannot be run with a stock `qmlscene` — `import fbx.application 1.0` only resolves on the box or through the Freebox SDK. The UI follows the Jellyfin Android TV app's flow and conventions. UI text is in French. +A Jellyfin client for the Freebox Player (Revolution), written in pure QML (no C++). The app runs inside the Freebox's QML runtime via the `fbx.application` module, The UI follows the Jellyfin Android TV app's flow and conventions. UI text is in French. ## Build / run @@ -15,10 +15,11 @@ There is no build system or test suite. - Prerequisites: `sudo apt install qmlscene qml-module-qtmultimedia qtdeclarative5-dev-tools`, and libfbxqml cloned next to the repo (`../libfbxqml`, override with `LIBFBXQML=`). - `tools/run-local.sh` — 1280×720 window via `tools/preview.qml`; `tools/run-local.sh --fullscreen` runs `Jellyfin.qml` as the box would. - `QT_QPA_PLATFORM=offscreen tools/run-local.sh` — headless run, useful to catch QML warnings. -- Lint: `qmllint Jellyfin.qml Components/*.qml Core/*.qml Views/*.qml` +- Lint: `qmllint Jellyfin.qml Components/*.qml Core/*.qml Shared/*.qml Views/*.qml` +- **Reproduce the box's loading mode**: the Player loads the app over HTTP, which behaves differently from local files (see constraints below). Check with `python3 -m http.server 8765 --directory .` then `QT_QPA_PLATFORM=offscreen qmlscene -I ../libfbxqml http://127.0.0.1:8765/Jellyfin.qml` — it must print no warnings. - The desktop has Qt 5.15 while the box targets QtQuick 2.5: code that runs locally can still use APIs too new for the box. -**Deploying to the Freebox** uses the Freebox SDK's QtCreator plugin: +**Deploying a test build to the Freebox**: `tools/deploy.py` (Python stdlib only; Player must be in developer mode). It discovers the Player via SSDP (`fbx:devel`) or takes `--box `, serves the repo over HTTP, calls JSON-RPC `debug_qml_app` on `http:///pub/devel`, and streams the app's stdout/stderr until it exits. Output is also written to `deploy.log` (repo root, gitignored, overwritten each run) — read it to diagnose on-box failures. The Player fetches files lazily from that HTTP server, so the script must keep running while the app is in use. This replicates the "Run" of the official QtCreator plugin, whose own setup is: - SDK setup: https://dev.freebox.fr/sdk/player.html (Windows: https://github.com/fbx/freebox-qtcreator-plugin/issues/8) - Open `Jellyfin.fbxproject` in QtCreator with the Freebox plugin; the run target deploys to a Freebox Player on the LAN (configured in `Jellyfin.fbxproject.user`, which is machine-specific). @@ -29,7 +30,8 @@ There is no build system or test suite. - `Jellyfin.qml` — root `Application`: logo panel (1/3) + `Navigator` (2/3), owns the single `Session` instance. - `Core/Navigator.qml` — screen stack on a `Loader`. `push("Name")` loads `Views/NameView.qml`; also `replace`, `pop`, `reset`. Every view gets `navigator` and `session` injected, plus any props passed to `push`. Remote Back/Escape pops; at the root it propagates (exits app). After loading, focus goes to the view's `initialFocus`. - `Core/Session.qml` — servers (`ListModel`), `currentServer`, `currentUser`. Network calls are **mocked** via `_simulate()`; each has a `TODO API` comment naming the Jellyfin endpoint. Async functions use `callback(error, result)` — keep that shape when wiring the real API. Views call `session.cancel()` on destruction. -- `Components/` — reusable widgets, exposed through `Components/qmldir` (every new component must be listed there). `Theme` (colors, spacing, fonts) and `Remote` (`isAccept`/`isBack` key mapping) are singletons; files inside `Components/` need `import "."` to see them. +- `Components/` — reusable widgets, listed in `Components/qmldir`. +- `Shared/` — `Theme` singleton (colors, spacing, fonts; the only type in `Shared/qmldir`) and `Remote.js` (`.pragma library`, `isAccept`/`isBack` key mapping, imported `as Remote`). - `Views/` — one screen per file, each rooted in `Page` (title/subtitle header + content area). Current flow: `ServerSelect` → `ServerAdd` → `UserSelect` → `Login` (password or Quick Connect) → `Home` (placeholder). ## Platform constraints @@ -37,4 +39,8 @@ There is no build system or test suite. - Target is QtQuick 2.5 (Qt 5.5 era): **ES5 JavaScript only** (`var`, `function`; no `let`/`const`/arrow functions) and no QtQuick.Controls. - Input is a TV remote: navigation uses `KeyNavigation` + explicit focus. On a `ListView`, set `KeyNavigation.priority: KeyNavigation.AfterItem` so the list handles arrows itself and only hands off at its ends. - In bindings, guard `page.session`/`page.navigator` against null: they are injected after bindings are first evaluated. +- **HTTP loading rules** (the box fetches files over HTTP, so directories can't be listed): + - every imported directory needs a `qmldir` listing all its types (`Core/`, `Components/`, `Shared/`); a missing one gives "X is not a type" only on the box; + - a singleton must not live in the same directory as the components that use it, and a directory must hold at most one singleton — otherwise "Cyclic dependency detected". Put helpers in `.pragma library` JS files instead of new singletons; + - no `import "."` self-imports. - Don't disable (`enabled: false`) a focused control during loading — it loses focus and the remote stops responding; guard with a `busy` flag instead. diff --git a/Components/FocusButton.qml b/Components/FocusButton.qml index d1f6b02..027c874 100644 --- a/Components/FocusButton.qml +++ b/Components/FocusButton.qml @@ -1,5 +1,6 @@ import QtQuick 2.5 -import "." +import "../Shared" +import "../Shared/Remote.js" as Remote // Bouton navigable à la télécommande : surbrillance blanche quand il a le focus. Rectangle { diff --git a/Components/Logo.qml b/Components/Logo.qml index c60c7c2..c28cc1f 100644 --- a/Components/Logo.qml +++ b/Components/Logo.qml @@ -1,5 +1,5 @@ import QtQuick 2.5 -import "." +import "../Shared" // Panneau de gauche avec le logo, affiché sur tous les écrans de connexion. Rectangle { diff --git a/Components/Page.qml b/Components/Page.qml index b937b1b..d629967 100644 --- a/Components/Page.qml +++ b/Components/Page.qml @@ -1,5 +1,5 @@ import QtQuick 2.5 -import "." +import "../Shared" // Base de chaque écran : en-tête (titre + sous-titre) et zone de contenu. // `navigator` et `session` sont injectés par le Navigator au chargement. diff --git a/Components/Remote.qml b/Components/Remote.qml deleted file mode 100644 index ead9949..0000000 --- a/Components/Remote.qml +++ /dev/null @@ -1,14 +0,0 @@ -pragma Singleton -import QtQuick 2.5 - -// Correspondance des touches de la télécommande Freebox. -// Plusieurs codes sont acceptés tant que le mapping exact sur la box n'est pas vérifié. -QtObject { - function isAccept(key) { - return key === Qt.Key_Return || key === Qt.Key_Enter || key === Qt.Key_Select; - } - - function isBack(key) { - return key === Qt.Key_Back || key === Qt.Key_Escape; - } -} diff --git a/Components/ServerItem.qml b/Components/ServerItem.qml index f3c0f3e..97e3128 100644 --- a/Components/ServerItem.qml +++ b/Components/ServerItem.qml @@ -1,5 +1,5 @@ import QtQuick 2.5 -import "." +import "../Shared" // Ligne de la liste des serveurs. Rectangle { diff --git a/Components/TextField.qml b/Components/TextField.qml index 7de07c8..174bc45 100644 --- a/Components/TextField.qml +++ b/Components/TextField.qml @@ -1,5 +1,5 @@ import QtQuick 2.5 -import "." +import "../Shared" // Champ de saisie avec libellé. Haut/Bas ne sont pas consommés par le TextInput // et remontent donc jusqu'au KeyNavigation posé sur ce composant. diff --git a/Components/UserCard.qml b/Components/UserCard.qml index 1dcd57e..1477993 100644 --- a/Components/UserCard.qml +++ b/Components/UserCard.qml @@ -1,5 +1,5 @@ import QtQuick 2.5 -import "." +import "../Shared" // Carte utilisateur (avatar rond + nom). `addCard` affiche la carte « Ajouter un compte ». Item { diff --git a/Components/qmldir b/Components/qmldir index c346c9d..4c45cbe 100644 --- a/Components/qmldir +++ b/Components/qmldir @@ -1,5 +1,3 @@ -singleton Theme 1.0 Theme.qml -singleton Remote 1.0 Remote.qml Page 1.0 Page.qml FocusButton 1.0 FocusButton.qml TextField 1.0 TextField.qml diff --git a/Core/Navigator.qml b/Core/Navigator.qml index 7b5ad69..398c331 100644 --- a/Core/Navigator.qml +++ b/Core/Navigator.qml @@ -1,5 +1,6 @@ import QtQuick 2.5 -import "../Components" +import "../Shared" +import "../Shared/Remote.js" as Remote // Pile de navigation entre les écrans de Views/. // push("ServerAdd") charge Views/ServerAddView.qml ; la touche Retour dépile. diff --git a/Core/qmldir b/Core/qmldir new file mode 100644 index 0000000..7b3bc7d --- /dev/null +++ b/Core/qmldir @@ -0,0 +1,2 @@ +Session 1.0 Session.qml +Navigator 1.0 Navigator.qml diff --git a/Jellyfin.qml b/Jellyfin.qml index 71a85ec..6eb5058 100644 --- a/Jellyfin.qml +++ b/Jellyfin.qml @@ -1,6 +1,7 @@ import QtQuick 2.5 import fbx.application 1.0 import "Components" +import "Shared" import "Core" Application { @@ -31,5 +32,11 @@ Application { } } + // Appelée par le runtime Freebox (ouverture de l'app via une URL / un lien profond). + // Pas encore utilisée : la déclarer évite l'avertissement au démarrage. + function handleUrl(url) { + console.log("handleUrl:", url); + } + Component.onCompleted: navigator.push("ServerSelect") } diff --git a/Shared/Remote.js b/Shared/Remote.js new file mode 100644 index 0000000..fe26e2e --- /dev/null +++ b/Shared/Remote.js @@ -0,0 +1,12 @@ +.pragma library + +// Correspondance des touches de la télécommande Freebox. +// Plusieurs codes sont acceptés tant que le mapping exact sur la box n'est pas vérifié. + +function isAccept(key) { + return key === Qt.Key_Return || key === Qt.Key_Enter || key === Qt.Key_Select; +} + +function isBack(key) { + return key === Qt.Key_Back || key === Qt.Key_Escape; +} diff --git a/Components/Theme.qml b/Shared/Theme.qml similarity index 100% rename from Components/Theme.qml rename to Shared/Theme.qml diff --git a/Shared/qmldir b/Shared/qmldir new file mode 100644 index 0000000..d57fb86 --- /dev/null +++ b/Shared/qmldir @@ -0,0 +1 @@ +singleton Theme 1.0 Theme.qml diff --git a/Views/HomeView.qml b/Views/HomeView.qml index 5f1d42c..5f6a906 100644 --- a/Views/HomeView.qml +++ b/Views/HomeView.qml @@ -1,5 +1,7 @@ import QtQuick 2.5 import "../Components" +import "../Shared" +import "../Shared/Remote.js" as Remote // Écran d'accueil provisoire : confirme la connexion en attendant la vraie bibliothèque. Page { diff --git a/Views/LoginView.qml b/Views/LoginView.qml index 5cd635a..40610d9 100644 --- a/Views/LoginView.qml +++ b/Views/LoginView.qml @@ -1,5 +1,6 @@ import QtQuick 2.5 import "../Components" +import "../Shared" // Écran 4 : connexion par mot de passe ou par Quick Connect. Page { diff --git a/Views/ServerAddView.qml b/Views/ServerAddView.qml index 82bf8fa..7b875bd 100644 --- a/Views/ServerAddView.qml +++ b/Views/ServerAddView.qml @@ -1,5 +1,6 @@ import QtQuick 2.5 import "../Components" +import "../Shared" // Écran 2 : saisie manuelle de l'adresse d'un serveur. Page { diff --git a/Views/ServerSelectView.qml b/Views/ServerSelectView.qml index f0a79a8..6f9989d 100644 --- a/Views/ServerSelectView.qml +++ b/Views/ServerSelectView.qml @@ -1,5 +1,7 @@ import QtQuick 2.5 import "../Components" +import "../Shared" +import "../Shared/Remote.js" as Remote // Écran 1 : choix d'un serveur enregistré ou découvert sur le réseau local. Page { diff --git a/Views/UserSelectView.qml b/Views/UserSelectView.qml index 5333f65..da20bd0 100644 --- a/Views/UserSelectView.qml +++ b/Views/UserSelectView.qml @@ -1,5 +1,7 @@ import QtQuick 2.5 import "../Components" +import "../Shared" +import "../Shared/Remote.js" as Remote // Écran 3 : choix de l'utilisateur parmi les comptes publics du serveur. Page { diff --git a/readme.md b/readme.md index 4ae15cc..09fa422 100644 --- a/readme.md +++ b/readme.md @@ -20,3 +20,13 @@ git clone https://github.com/fbx/libfbxqml.git ../libfbxqml tools/run-local.sh # fenêtre 1280x720 tools/run-local.sh --fullscreen # plein écran, comme sur la box ``` + +## Tester sur la Freebox +Activer le mode développeur du Player (menu Réglages, avec la télécommande), puis : + +```bash +tools/deploy.py # trouve le Player sur le réseau et lance l'app +tools/deploy.py --box 192.168.0.21 # ou en donnant son adresse +``` + +Le script sert les fichiers du projet au Player et affiche les logs de l'application. Il doit rester ouvert pendant le test (Ctrl+C pour arrêter). diff --git a/tools/deploy.py b/tools/deploy.py new file mode 100755 index 0000000..6f1286b --- /dev/null +++ b/tools/deploy.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Lance l'application sur un Freebox Player en mode développeur. + +Reproduit le « Run » du plugin QtCreator Freebox (github.com/fbx/freebox-qtcreator-plugin) : + 1. trouve le Player sur le réseau local (SSDP, type « fbx:devel ») ou utilise --box ; + 2. sert le dossier du projet en HTTP (le Player y télécharge manifest.json et les QML) ; + 3. appelle la méthode JSON-RPC « debug_qml_app » sur http:///pub/devel ; + 4. affiche stdout/stderr de l'application jusqu'à sa fermeture (ou Ctrl+C). + +Usage : tools/deploy.py [--box 192.168.0.21] [--entry main] [--verbose] [--log deploy.log] +La sortie est aussi écrite dans deploy.log (racine du projet), écrasé à chaque lancement. +""" +import argparse +import functools +import http.server +import json +import os +import selectors +import socket +import sys +import threading +import time +import urllib.request + +PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SSDP_ADDR = ("239.255.255.250", 1900) +SSDP_TYPE = "fbx:devel" + + +def discover(timeout=3.0): + """Renvoie l'adresse IP du premier Player en mode développeur qui répond.""" + request = ( + "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + 'MAN: "ssdp:discover"\r\n' + "MX: 1\r\n" + "ST: %s\r\n\r\n" % SSDP_TYPE + ).encode() + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) + sock.settimeout(timeout) + try: + sock.sendto(request, SSDP_ADDR) + while True: + data, (addr, _) = sock.recvfrom(4096) + headers = data.decode(errors="replace").lower() + if "st: %s" % SSDP_TYPE in headers or "nt: %s" % SSDP_TYPE in headers: + return addr + except socket.timeout: + return None + finally: + sock.close() + + +def local_ip_towards(box): + """Adresse de ce PC vue depuis le Player (interface utilisée pour le joindre).""" + with socket.create_connection((box, 80), timeout=3) as sock: + return sock.getsockname()[0] + + +class QuietHandler(http.server.SimpleHTTPRequestHandler): + verbose = False + + def log_message(self, fmt, *args): + if self.verbose: + sys.stderr.write("[http] %s\n" % (fmt % args)) + + +def serve_project(bind_ip, verbose): + QuietHandler.verbose = verbose + handler = functools.partial(QuietHandler, directory=PROJECT_DIR) + server = http.server.ThreadingHTTPServer((bind_ip, 0), handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + +def json_rpc(box, method, params): + body = json.dumps({"jsonrpc": "2.0", "method": method, "params": params, "id": "0"}).encode() + request = urllib.request.Request( + "http://%s/pub/devel" % box, data=body, headers={"Content-Type": "application/json"} + ) + with urllib.request.urlopen(request, timeout=15) as reply: + answer = json.load(reply) + if "error" in answer: + raise RuntimeError(answer["error"].get("message", answer["error"])) + return answer.get("result", {}) + + +def stream_output(box, stdout_port, stderr_port): + """Affiche la sortie de l'app ; se termine quand le Player ferme stdout (app quittée).""" + selector = selectors.DefaultSelector() + streams = {} + for port, target in ((stdout_port, sys.stdout), (stderr_port, sys.stderr)): + if port: + sock = socket.create_connection((box, port), timeout=5) + sock.settimeout(None) + selector.register(sock, selectors.EVENT_READ) + streams[sock] = target + while streams: + for key, _ in selector.select(): + sock = key.fileobj + data = sock.recv(4096) + if not data: + selector.unregister(sock) + sock.close() + if streams.pop(sock) is sys.stdout: + return + continue + streams[sock].write(data.decode(errors="replace")) + streams[sock].flush() + + +class Tee: + """Duplique un flux (stdout/stderr) dans le fichier de log.""" + + def __init__(self, stream, log): + self.stream = stream + self.log = log + + def write(self, text): + self.stream.write(text) + self.stream.flush() + self.log.write(text) + self.log.flush() + + def flush(self): + self.stream.flush() + self.log.flush() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--box", help="adresse IP du Player (sinon découverte SSDP)") + parser.add_argument("--entry", default="main", help="entry point du manifest.json (défaut : main)") + parser.add_argument("--verbose", action="store_true", help="affiche les fichiers téléchargés par le Player") + parser.add_argument("--log", default=os.path.join(PROJECT_DIR, "deploy.log"), + help="fichier de log, écrasé à chaque lancement (défaut : deploy.log ; vide pour désactiver)") + args = parser.parse_args() + + if args.log: + log = open(args.log, "w", encoding="utf-8") + log.write("# deploy.py %s\n" % time.strftime("%Y-%m-%d %H:%M:%S")) + sys.stdout = Tee(sys.stdout, log) + sys.stderr = Tee(sys.stderr, log) + + box = args.box + if not box: + print("Recherche d'un Freebox Player en mode développeur…") + box = discover() + if not box: + sys.exit("Aucun Player trouvé. Vérifiez le mode développeur, ou passez --box .") + print("Player : %s" % box) + + try: + me = local_ip_towards(box) + except OSError as error: + sys.exit("Impossible de joindre %s:80 (%s)." % (box, error)) + + server = serve_project(me, args.verbose) + port = server.server_address[1] + manifest_url = "http://%s:%d/manifest.json" % (me, port) + print("Projet servi sur %s" % manifest_url) + + try: + result = json_rpc(box, "debug_qml_app", { + "manifest_url": manifest_url, + "entry_point": args.entry, + "wait": False, + }) + print("Application lancée. Ctrl+C pour arrêter.\n") + stream_output(box, result.get("stdout_port"), result.get("stderr_port")) + print("\nApplication fermée sur le Player.") + except KeyboardInterrupt: + print("\nArrêt.") + except Exception as error: # erreurs réseau ou JSON-RPC : message lisible + sys.exit("Échec du lancement : %s" % error) + finally: + server.shutdown() + + +if __name__ == "__main__": + main()