Add more behavior with the local test env.

This commit is contained in:
stilobique committed 2026-11-08 11:39:27 +01:00
1 parent acb58142d9
commit df847becc8
10 files changed
+450 -114

No files matched your search

+5 -2
View File
@@ -15,11 +15,12 @@ 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=`). - 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. - `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. - `QT_QPA_PLATFORM=offscreen tools/run-local.sh` — headless run, useful to catch QML warnings.
- HTTPS on the PC works with the system `qmlscene` (Qt 5.15 + OpenSSL 3). PyQt5 wheels from pip bundle a Qt built for OpenSSL 1.x and cannot do TLS here.
- Lint: `qmllint Jellyfin.qml Components/*.qml Core/*.qml Shared/*.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. - **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. - 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 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 <IP>`, serves the repo over HTTP, calls JSON-RPC `debug_qml_app` on `http://<box>/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: **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 <IP>`, serves the repo over HTTP, calls JSON-RPC `debug_qml_app` on `http://<box>/pub/devel`, and streams the app's stdout/stderr until it exits. `--server <host>` and `--user name[:password]` (both repeatable) serve a virtual `dev-config.json` next to the app; at startup `Session.loadDevConfig()` adds each listed server and stores users in `Session.devUsers`, which `UserSelectView` merges with public users (one-click sign-in when a password is given; never log passwords) (only when the app is loaded over HTTP; 404 otherwise, ignored) — the workaround for the lack of persistence in dev mode. 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) - 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). - 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,7 @@ There is no build system or test suite.
- `Jellyfin.qml` — root `Application`: logo panel (1/3) + `Navigator` (2/3), owns the single `Session` instance. - `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/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. - `Core/Session.qml` — Jellyfin API client over `XMLHttpRequest` (`_request()`: JSON, `Authorization: MediaBrowser …` header with `Token` once signed in, per-request timeout via a dynamically created `Timer` since Qt 5.5 XHR has none). Holds saved servers (`ListModel`, persisted through `fbx.application` `Settings` — works on the box only; on the PC `App is not defined` warnings are expected and nothing persists), `currentServer`, `currentUser`, `accessToken`. Endpoints: `/System/Info/Public` (server probe), `/Users/Public`, `/Users/AuthenticateByName`, `/Sessions/Logout`, `/QuickConnect/*`. Async functions call `callback(error, result)` with `error` a user-facing French message. Every public callback is wrapped by `_guard()`; `cancel()` (called by views on destruction) drops pending callbacks and stops Quick Connect polling.
- `Components/` — reusable widgets, listed in `Components/qmldir`. - `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`). - `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). - `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).
@@ -39,6 +40,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. - 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. - 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.
- The box's virtual keyboard lacks `:` (and likely `/`): never require typing a URL scheme or `host:port`. Server entry takes host + optional numeric port; `Session.serverCandidates()` derives the URLs to probe (https, http:8096, https:8920, http). - The box's virtual keyboard lacks `:` (and likely `/`): never require typing a URL scheme or `host:port`. Server entry takes host + optional numeric port; `Session.serverCandidates()` derives the URLs to probe (https, http:8096, https:8920, http).
- **No persistent storage when launched via `tools/deploy.py`** (dev mode, app not installed), even with a Freebox profile open (`profileId=1`): `Settings` saves fail with `profiles.application_data_set` "internal json-rpc error", and `QtQuick.LocalStorage` exists but cannot create `/var/lib/databases/fbxqmltv/Databases`. Expected to work once installed as a FreeStore package (unverified). Code must keep working with nothing persisted.
- The box's native `fbx.application` `Application` differs from libfbxqml's: e.g. it has `profileId` but no `identifier`. Don't rely on libfbxqml-only properties; guard with `typeof`.
- In bindings, guard `page.session`/`page.navigator` against null: they are injected after bindings are first evaluated. - 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): - **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; - 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;
+1 -24
View File
@@ -7,7 +7,6 @@ Rectangle {
property string name: "" property string name: ""
property string address: "" property string address: ""
property bool discovered: false
property bool highlighted: false property bool highlighted: false
signal clicked() signal clicked()
@@ -42,7 +41,7 @@ Rectangle {
anchors { anchors {
left: icon.right left: icon.right
leftMargin: Theme.spacingM leftMargin: Theme.spacingM
right: root.discovered ? tag.left : parent.right right: parent.right
rightMargin: Theme.spacingM rightMargin: Theme.spacingM
verticalCenter: parent.verticalCenter verticalCenter: parent.verticalCenter
} }
@@ -65,28 +64,6 @@ Rectangle {
} }
} }
Rectangle {
id: tag
visible: root.discovered
anchors {
right: parent.right
rightMargin: Theme.spacingM
verticalCenter: parent.verticalCenter
}
width: tagText.implicitWidth + Theme.spacingM
height: tagText.implicitHeight + Theme.spacingS
radius: height / 2
color: Theme.accentAlt
Text {
id: tagText
anchors.centerIn: parent
text: "Réseau local"
color: Theme.text
font.pixelSize: Theme.fontSmall
}
}
MouseArea { MouseArea {
anchors.fill: parent anchors.fill: parent
onClicked: root.clicked() onClicked: root.clicked()
+309 -69
View File
@@ -1,29 +1,55 @@
import QtQuick 2.5 import QtQuick 2.5
import fbx.application 1.0
// État de connexion : serveurs connus, serveur et utilisateur courants. // État de connexion et appels à l'API Jellyfin : serveurs enregistrés,
// Les appels réseau sont SIMULÉS (_simulate) : à remplacer par l'API Jellyfin // serveur et utilisateur courants, jeton d'accès.
// en gardant la forme des callbacks `callback(erreur, résultat)`. // Les fonctions asynchrones appellent `callback(erreur, résultat)` ; `erreur` est un
// message prêt à afficher. cancel() ignore les réponses encore en attente.
QtObject { QtObject {
id: session id: session
property ListModel servers: ListModel { readonly property string clientName: "Jellyfin Freebox"
// Données fictives readonly property string clientVersion: "0.1.0"
ListElement { name: "Maison"; address: "http://192.168.1.20:8096"; discovered: false } readonly property string deviceName: "Freebox Player"
ListElement { name: "jellyfin-nas"; address: "http://192.168.1.42:8096"; discovered: true }
}
property var currentServer: null // { name, address } // Serveurs enregistrés : { name, address, id }
property var currentUser: null // { name } property ListModel servers: ListModel {}
property var currentServer: null // { name, address, id }
property var currentUser: null // { name, id }
property string accessToken: ""
// Comptes de test fournis par tools/deploy.py --user : { name, password? }
property var devUsers: []
// ---------------------------------------------------------------- Serveurs
function selectServer(index) { function selectServer(index) {
var server = servers.get(index); var server = servers.get(index);
currentServer = { name: server.name, address: server.address }; currentServer = { name: server.name, address: server.address, id: server.id };
} }
// Ajoute (ou retrouve) un serveur à partir de l'hôte saisi et d'un port facultatif. function removeServer(index) {
servers.remove(index);
_saveServers();
}
// Ajoute (ou met à jour) un serveur à partir de l'hôte saisi et d'un port facultatif.
// Le clavier de la box n'a ni « : » ni « / » : le protocole et le port sont // Le clavier de la box n'a ni « : » ni « / » : le protocole et le port sont
// détectés en essayant chaque adresse de serverCandidates() dans l'ordre. // détectés en essayant chaque adresse de serverCandidates() dans l'ordre.
function connectToServer(host, port, callback) { function connectToServer(host, port, callback) {
callback = _guard(callback);
_addServer(host, port, function (err) {
if (err) {
callback(err);
return;
}
selectServer(0);
callback(null, currentServer);
});
}
// Ajoute le serveur en tête de liste (sans le sélectionner) ; non lié à cancel().
function _addServer(host, port, callback) {
if ((host || "").trim() === "") { if ((host || "").trim() === "") {
callback("Veuillez saisir l'adresse du serveur."); callback("Veuillez saisir l'adresse du serveur.");
return; return;
@@ -33,21 +59,45 @@ QtObject {
callback("Le port doit être un nombre entre 1 et 65535."); callback("Le port doit être un nombre entre 1 et 65535.");
return; return;
} }
_probeCandidates(serverCandidates(host, portText), 0, function (err, address) { _probeCandidates(serverCandidates(host, portText), 0, function (err, server) {
if (err) { if (err) {
callback(err); callback(err);
return; return;
} }
var index = _indexOfServer(address); var index = _indexOfServer(server.id);
if (index < 0) { if (index >= 0)
servers.insert(0, { name: _hostOf(address), address: address, discovered: false }); servers.remove(index);
index = 0; servers.insert(0, server);
} _saveServers();
selectServer(index); callback(null, server);
callback(null, currentServer);
}); });
} }
// Test sur la box : tools/deploy.py --server <adresse> --user <nom[:mdp]> sert
// dev-config.json à côté de l'app ; chaque serveur listé est ajouté et les comptes
// sont proposés sur « Qui regarde ? ». Absent (404) hors test : rien ne se passe.
function loadDevConfig(url) {
if (!/^https?:/i.test(url))
return; // app chargée depuis le disque (aperçu PC) : pas de dev-config
_request("GET", "", null, function (err, config) {
if (err || !config)
return;
if (config.users && config.users.length > 0) {
devUsers = config.users;
console.log("dev-config : " + config.users.length + " utilisateur(s) de test");
}
var hosts = config.servers || [];
for (var i = 0; i < hosts.length; i++) {
(function (host) {
_addServer(host, "", function (err2, server) {
console.log(err2 ? "dev-config : " + host + " → " + err2
: "dev-config : serveur ajouté " + server.address);
});
})(String(hosts[i]));
}
}, { baseUrl: url, timeout: 3000 });
}
// Adresses à essayer, de la plus probable à la moins probable // Adresses à essayer, de la plus probable à la moins probable
// (même logique que les clients Jellyfin officiels). // (même logique que les clients Jellyfin officiels).
function serverCandidates(host, port) { function serverCandidates(host, port) {
@@ -73,19 +123,6 @@ QtObject {
]; ];
} }
// Essaie les adresses une par une ; renvoie la première qui répond.
// TODO API : GET <adresse>/System/Info/Public, accepter si la réponse contient un Id,
// et utiliser ServerName comme nom. Simulation : la première adresse « répond ».
function _probeCandidates(candidates, index, callback) {
if (index >= candidates.length) {
callback("Aucun serveur Jellyfin trouvé à cette adresse.");
return;
}
_simulate(function () {
callback(null, candidates[index]);
});
}
function isValidPort(text) { function isValidPort(text) {
if (!/^\d+$/.test(text)) if (!/^\d+$/.test(text))
return false; return false;
@@ -93,71 +130,274 @@ QtObject {
return value >= 1 && value <= 65535; return value >= 1 && value <= 65535;
} }
// TODO API : GET /Users/Public // ------------------------------------------------------------ Utilisateurs
function publicUsers() {
return [ // Comptes affichés sur l'écran de connexion du serveur (peut être vide).
{ name: "Alice", hasPassword: true }, function loadPublicUsers(callback) {
{ name: "Bob", hasPassword: false }, callback = _guard(callback);
{ name: "Enfants", hasPassword: false } _request("GET", "/Users/Public", null, function (err, data) {
]; if (err) {
callback(_describe(err));
return;
}
var users = [];
for (var i = 0; i < (data || []).length; i++)
users.push({ name: data[i].Name, id: data[i].Id, hasPassword: data[i].HasPassword });
callback(null, users);
});
} }
// TODO API : POST /Users/AuthenticateByName
function authenticate(username, password, callback) { function authenticate(username, password, callback) {
callback = _guard(callback);
var name = (username || "").trim(); var name = (username || "").trim();
if (name === "") { if (name === "") {
callback("Veuillez saisir votre nom d'utilisateur."); callback("Veuillez saisir votre nom d'utilisateur.");
return; return;
} }
_simulate(function () { _request("POST", "/Users/AuthenticateByName", { Username: name, Pw: password || "" }, function (err, data) {
currentUser = { name: name }; if (err) {
callback(null, currentUser); callback(err.status === 401 ? "Nom d'utilisateur ou mot de passe incorrect." : _describe(err));
return;
}
callback(null, _signedIn(data));
}); });
} }
// TODO API : POST /QuickConnect/Initiate puis interroger /QuickConnect/Connect
function startQuickConnect() {
var code = "";
for (var i = 0; i < 6; i++)
code += Math.floor(Math.random() * 10);
return code;
}
function logout() { function logout() {
if (accessToken !== "")
_request("POST", "/Sessions/Logout", null, function () {});
accessToken = "";
currentUser = null; currentUser = null;
} }
// ----------------------------------------------------------- Quick Connect
function isQuickConnectEnabled(callback) {
callback = _guard(callback);
_request("GET", "/QuickConnect/Enabled", null, function (err, data) {
callback(null, !err && data === true);
});
}
// onCode(erreur, code) : code à afficher ; onSignedIn(erreur, utilisateur) : autorisation reçue.
function startQuickConnect(onCode, onSignedIn) {
stopQuickConnect();
onCode = _guard(onCode);
_quickConnect.onSignedIn = _guard(onSignedIn);
_request("POST", "/QuickConnect/Initiate", null, function (err, data) {
if (err || !data || !data.Secret) {
onCode(err && err.status === 401
? "Quick Connect est désactivé sur ce serveur."
: _describe(err || { kind: "invalid" }));
return;
}
_quickConnect.secret = data.Secret;
_quickConnectPoll.start();
onCode(null, data.Code);
});
}
function stopQuickConnect() {
_quickConnectPoll.stop();
_quickConnect.secret = "";
}
property var _quickConnect: ({ secret: "", onSignedIn: null })
property Timer _quickConnectPoll: Timer {
interval: 5000
repeat: true
onTriggered: session._pollQuickConnect()
}
function _pollQuickConnect() {
var secret = _quickConnect.secret;
if (secret === "")
return;
_request("GET", "/QuickConnect/Connect?Secret=" + encodeURIComponent(secret), null, function (err, data) {
if (secret !== _quickConnect.secret || err || !data || !data.Authenticated)
return;
stopQuickConnect();
_request("POST", "/Users/AuthenticateWithQuickConnect", { Secret: secret }, function (err2, auth) {
var done = _quickConnect.onSignedIn;
if (!done)
return;
if (err2)
done(_describe(err2));
else
done(null, _signedIn(auth));
});
});
}
// ------------------------------------------------------------------ Divers
// Ignore les réponses en attente (appelé quand un écran est détruit).
function cancel() { function cancel() {
_pending = null; _generation++;
_latency.stop(); stopQuickConnect();
}
property int _generation: 0
function _guard(callback) {
var generation = _generation;
return function () {
if (generation === session._generation && callback)
callback.apply(null, arguments);
};
}
function _signedIn(data) {
accessToken = data.AccessToken;
currentUser = { name: data.User.Name, id: data.User.Id };
return currentUser;
}
// Essaie les adresses une par une ; renvoie la première qui répond comme un serveur Jellyfin.
function _probeCandidates(candidates, index, callback) {
if (index >= candidates.length) {
callback("Aucun serveur Jellyfin trouvé à cette adresse.");
return;
}
var address = candidates[index];
_request("GET", "/System/Info/Public", null, function (err, info) {
if (!err && info && info.Id) {
callback(null, { name: info.ServerName || _hostOf(address), address: address, id: info.Id });
return;
}
_probeCandidates(candidates, index + 1, callback);
}, { baseUrl: address, timeout: 5000 });
}
function _describe(err) {
if (!err)
return "";
if (err.kind === "timeout")
return "Le serveur ne répond pas.";
if (err.kind === "network")
return "Impossible de contacter le serveur.";
if (err.kind === "invalid")
return "Réponse inattendue du serveur.";
return "Erreur du serveur (" + err.status + ").";
}
function _authorization() {
var value = 'MediaBrowser Client="' + clientName + '", Device="' + deviceName
+ '", DeviceId="' + _settings.deviceId + '", Version="' + clientVersion + '"';
if (accessToken !== "")
value += ', Token="' + accessToken + '"';
return value;
}
// Requête JSON. callback(erreur, données) avec erreur = { kind, status } :
// kind vaut "timeout", "network" (pas de réponse), "http" (statut != 2xx) ou "invalid".
function _request(method, path, body, callback, options) {
options = options || {};
var url = (options.baseUrl || (currentServer ? currentServer.address : "")) + path;
var xhr = new XMLHttpRequest();
var finished = false;
var timer = _timerComponent.createObject(session, { interval: options.timeout || 15000 });
function finish(err, data) {
if (finished)
return;
finished = true;
timer.stop();
timer.destroy();
callback(err, data);
}
timer.triggered.connect(function () {
finish({ kind: "timeout", status: 0 });
xhr.abort();
});
xhr.onreadystatechange = function () {
if (xhr.readyState !== XMLHttpRequest.DONE || finished)
return;
if (xhr.status === 0) {
finish({ kind: "network", status: 0 });
} else if (xhr.status < 200 || xhr.status >= 300) {
finish({ kind: "http", status: xhr.status });
} else if (xhr.responseText === "") {
finish(null, null);
} else {
try {
finish(null, JSON.parse(xhr.responseText));
} catch (e) {
finish({ kind: "invalid", status: xhr.status });
}
}
};
xhr.open(method, url);
xhr.setRequestHeader("Authorization", _authorization());
timer.start();
if (body) {
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(body));
} else {
xhr.send();
}
}
property Component _timerComponent: Component {
Timer {}
} }
function _hostOf(address) { function _hostOf(address) {
return address.replace(/^https?:\/\//i, "").split(/[:\/]/)[0]; return address.replace(/^https?:\/\//i, "").split(/[:\/]/)[0];
} }
function _indexOfServer(address) { function _indexOfServer(id) {
for (var i = 0; i < servers.count; i++) { for (var i = 0; i < servers.count; i++) {
if (servers.get(i).address === address) if (servers.get(i).id === id)
return i; return i;
} }
return -1; return -1;
} }
// Simulation de latence réseau. // ------------------------------------------------------------ Persistance
property var _pending: null
property Timer _latency: Timer { // Stockage de la box (fbx.application Settings) ; sans effet sur PC.
interval: 700 property Settings _settings: Settings {
onTriggered: { property string serverList: ""
var callback = session._pending; property string deviceId: ""
session._pending = null; onReady: session._restore()
if (callback)
callback();
}
} }
function _simulate(callback) { function _restore() {
_pending = callback; if (_settings.deviceId === "")
_latency.restart(); _settings.deviceId = _randomId();
if (servers.count > 0)
return;
var list = [];
try {
// Encodé (voir _saveServers) ; ancien format JSON brut accepté.
var raw = _settings.serverList;
list = JSON.parse(raw.charAt(0) === "%" ? decodeURIComponent(raw) : (raw || "[]"));
} catch (e) {
} }
for (var i = 0; i < list.length; i++)
servers.append({ name: list[i].name, address: list[i].address, id: list[i].id });
}
function _saveServers() {
var list = [];
for (var i = 0; i < servers.count; i++) {
var s = servers.get(i);
list.push({ name: s.name, address: s.address, id: s.id });
}
// Encodé (%XX) pour n'enregistrer que des caractères simples.
_settings.serverList = encodeURIComponent(JSON.stringify(list));
}
function _randomId() {
var id = "";
for (var i = 0; i < 32; i++)
id += Math.floor(Math.random() * 16).toString(16);
return id;
}
Component.onCompleted: _restore()
} }
+4 -1
View File
@@ -38,5 +38,8 @@ Application {
console.log("handleUrl:", url); console.log("handleUrl:", url);
} }
Component.onCompleted: navigator.push("ServerSelect") Component.onCompleted: {
navigator.push("ServerSelect");
appSession.loadDevConfig(Qt.resolvedUrl("dev-config.json"));
}
} }
+30 -5
View File
@@ -8,6 +8,7 @@ Page {
property string username: "" property string username: ""
property bool quickConnect: false property bool quickConnect: false
property bool quickConnectAvailable: false
property string quickConnectCode: "" property string quickConnectCode: ""
property bool busy: false property bool busy: false
property string error: "" property string error: ""
@@ -39,13 +40,34 @@ Page {
error = ""; error = "";
quickConnect = enabled; quickConnect = enabled;
if (enabled) { if (enabled) {
quickConnectCode = page.session.startQuickConnect(); quickConnectCode = "";
passwordModeButton.forceActiveFocus(); passwordModeButton.forceActiveFocus();
page.session.startQuickConnect(function (err, code) {
if (err) {
page.error = err;
return;
}
page.quickConnectCode = code;
}, function (err) {
if (err) {
page.error = err;
return;
}
page.navigator.reset("Home");
});
} else { } else {
page.session.stopQuickConnect();
page.initialFocus.forceActiveFocus(); page.initialFocus.forceActiveFocus();
} }
} }
// Le bouton Quick Connect n'est proposé que si le serveur l'autorise.
Component.onCompleted: {
page.session.isQuickConnectEnabled(function (err, enabled) {
page.quickConnectAvailable = enabled;
});
}
Component.onDestruction: if (page.session) page.session.cancel() Component.onDestruction: if (page.session) page.session.cancel()
Column { Column {
@@ -90,12 +112,13 @@ Page {
primary: true primary: true
text: page.busy ? "Connexion…" : "Se connecter" text: page.busy ? "Connexion…" : "Se connecter"
KeyNavigation.up: passwordField KeyNavigation.up: passwordField
KeyNavigation.right: quickConnectButton KeyNavigation.right: page.quickConnectAvailable ? quickConnectButton : null
onClicked: page.signIn() onClicked: page.signIn()
} }
FocusButton { FocusButton {
id: quickConnectButton id: quickConnectButton
visible: page.quickConnectAvailable
text: "Utiliser Quick Connect" text: "Utiliser Quick Connect"
KeyNavigation.up: passwordField KeyNavigation.up: passwordField
KeyNavigation.left: signInButton KeyNavigation.left: signInButton
@@ -119,7 +142,7 @@ Page {
} }
Text { Text {
text: page.quickConnectCode text: page.quickConnectCode !== "" ? page.quickConnectCode : "…"
color: Theme.accent color: Theme.accent
font.pixelSize: Theme.fontCode font.pixelSize: Theme.fontCode
font.bold: true font.bold: true
@@ -127,8 +150,10 @@ Page {
} }
Text { Text {
text: "En attente d'autorisation…" width: parent.width
color: Theme.textMuted text: page.error !== "" ? page.error : "En attente d'autorisation…"
color: page.error !== "" ? Theme.error : Theme.textMuted
wrapMode: Text.WordWrap
font.pixelSize: Theme.fontSmall font.pixelSize: Theme.fontSmall
} }
+1 -1
View File
@@ -74,7 +74,7 @@ Page {
FocusButton { FocusButton {
id: connectButton id: connectButton
primary: true primary: true
text: page.busy ? "Connexion…" : "Se connecter" text: page.busy ? "Recherche du serveur…" : "Se connecter"
KeyNavigation.up: portField KeyNavigation.up: portField
onClicked: page.connect() onClicked: page.connect()
} }
+8 -1
View File
@@ -31,11 +31,18 @@ Page {
spacing: Theme.spacingS spacing: Theme.spacingS
model: page.session ? page.session.servers : null model: page.session ? page.session.servers : null
// Serveur ajouté après l'affichage (dev-config) : on y place le focus.
onCountChanged: {
if (count > 0 && addButton.activeFocus) {
currentIndex = 0;
forceActiveFocus();
}
}
delegate: ServerItem { delegate: ServerItem {
width: serverList.width width: serverList.width
name: model.name name: model.name
address: model.address address: model.address
discovered: model.discovered
highlighted: ListView.isCurrentItem && serverList.activeFocus highlighted: ListView.isCurrentItem && serverList.activeFocus
onClicked: { onClicked: {
serverList.currentIndex = index; serverList.currentIndex = index;
+49 -8
View File
@@ -4,10 +4,15 @@ import "../Shared"
import "../Shared/Remote.js" as Remote import "../Shared/Remote.js" as Remote
// Écran 3 : choix de l'utilisateur parmi les comptes publics du serveur. // Écran 3 : choix de l'utilisateur parmi les comptes publics du serveur.
// Si le serveur masque ses comptes, seule la carte « Ajouter un compte » est proposée,
// plus les comptes de test éventuels (tools/deploy.py --user).
Page { Page {
id: page id: page
property var users: page.session ? page.session.publicUsers() : [] property var publicUsers: []
// Comptes publics + comptes de test absents de la liste publique.
property var users: mergeUsers(publicUsers, page.session ? page.session.devUsers : [])
property bool loading: true
property bool busy: false property bool busy: false
property string error: "" property string error: ""
@@ -17,6 +22,31 @@ Page {
: "" : ""
initialFocus: userList initialFocus: userList
function mergeUsers(publicList, devList) {
var result = publicList.slice();
for (var i = 0; i < devList.length; i++) {
var known = false;
for (var j = 0; j < publicList.length; j++)
known = known || publicList[j].name.toLowerCase() === devList[i].name.toLowerCase();
if (!known)
result.push({ name: devList[i].name, hasPassword: true, devPassword: devList[i].password });
}
return result;
}
function signInAs(name, password) {
error = "";
busy = true;
page.session.authenticate(name, password, function (err) {
page.busy = false;
if (err) {
page.error = err;
return;
}
page.navigator.reset("Home");
});
}
function openUser(index) { function openUser(index) {
if (busy) if (busy)
return; return;
@@ -26,20 +56,27 @@ Page {
return; return;
} }
var user = users[index]; var user = users[index];
// Compte de test avec mot de passe fourni : connexion directe.
if (user.devPassword !== undefined) {
signInAs(user.name, user.devPassword);
return;
}
if (user.hasPassword) { if (user.hasPassword) {
page.navigator.push("Login", { username: user.name }); page.navigator.push("Login", { username: user.name });
return; return;
} }
// Compte sans mot de passe : connexion directe, comme sur Android TV. // Compte sans mot de passe : connexion directe, comme sur Android TV.
error = ""; signInAs(user.name, "");
busy = true; }
page.session.authenticate(user.name, "", function (err) {
page.busy = false; Component.onCompleted: {
page.session.loadPublicUsers(function (err, users) {
page.loading = false;
if (err) { if (err) {
page.error = err; page.error = err;
return; return;
} }
page.navigator.reset("Home"); page.publicUsers = users;
}); });
} }
@@ -85,8 +122,12 @@ Page {
right: parent.right right: parent.right
} }
visible: text !== "" visible: text !== ""
text: page.busy ? "Connexion…" : page.error text: page.busy ? "Connexion…"
color: page.busy ? Theme.textMuted : Theme.error : page.loading ? "Chargement des utilisateurs…"
: page.error !== "" ? page.error
: page.users.length === 0 ? "Les comptes de ce serveur ne sont pas affichés publiquement : choisissez « Ajouter un compte » pour vous connecter."
: ""
color: page.error !== "" && !page.busy ? Theme.error : Theme.textMuted
font.pixelSize: Theme.fontBody font.pixelSize: Theme.fontBody
wrapMode: Text.WordWrap wrapMode: Text.WordWrap
} }
+6
View File
@@ -27,6 +27,12 @@ Activer le mode développeur du Player (menu Réglages, avec la télécommande),
```bash ```bash
tools/deploy.py # trouve le Player sur le réseau et lance l'app 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 tools/deploy.py --box 192.168.0.21 # ou en donnant son adresse
tools/deploy.py --server media.example.com # l'app ajoute ce serveur au démarrage
tools/deploy.py --server media.example.com --user alice:motdepasse --user bob
``` ```
En mode développement, la box n'enregistre aucune donnée de l'application. Pour éviter de tout ressaisir à chaque test :
- `--server <adresse>` : le serveur est ajouté automatiquement à la liste ;
- `--user <nom>[:<mot de passe>]` (répétable) : le compte apparaît sur « Qui regarde ? », même si le serveur masque ses comptes. Avec un mot de passe, la connexion se fait en un clic ; sans, l'écran de connexion s'ouvre avec le nom pré-rempli. Le mot de passe n'apparaît pas dans les logs, mais il transite en clair sur le réseau local.
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). 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).
+37 -3
View File
@@ -7,7 +7,9 @@ Reproduit le « Run » du plugin QtCreator Freebox (github.com/fbx/freebox-qtcre
3. appelle la méthode JSON-RPC « debug_qml_app » sur http://<box>/pub/devel ; 3. appelle la méthode JSON-RPC « debug_qml_app » sur http://<box>/pub/devel ;
4. affiche stdout/stderr de l'application jusqu'à sa fermeture (ou Ctrl+C). 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] Usage : tools/deploy.py [--box 192.168.0.21] [--server media.example.com] [--user nom[:mdp]] [--entry main] [--verbose] [--log deploy.log]
--server : l'app ajoute ce serveur au démarrage (utile car la box n'enregistre rien en mode développement).
--user nom[:mot_de_passe] : compte proposé sur « Qui regarde ? » (le mot de passe transite en clair sur le réseau local).
La sortie est aussi écrite dans deploy.log (racine du projet), écrasé à chaque lancement. La sortie est aussi écrite dans deploy.log (racine du projet), écrasé à chaque lancement.
""" """
import argparse import argparse
@@ -58,16 +60,32 @@ def local_ip_towards(box):
return sock.getsockname()[0] return sock.getsockname()[0]
DEV_CONFIG_PATH = "/dev-config.json"
class QuietHandler(http.server.SimpleHTTPRequestHandler): class QuietHandler(http.server.SimpleHTTPRequestHandler):
verbose = False verbose = False
dev_config = None # dict servi sur DEV_CONFIG_PATH (jamais écrit sur disque)
def do_GET(self):
if self.path.split("?")[0] == DEV_CONFIG_PATH and self.dev_config is not None:
body = json.dumps(self.dev_config).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
super().do_GET()
def log_message(self, fmt, *args): def log_message(self, fmt, *args):
if self.verbose: if self.verbose:
sys.stderr.write("[http] %s\n" % (fmt % args)) sys.stderr.write("[http] %s\n" % (fmt % args))
def serve_project(bind_ip, verbose): def serve_project(bind_ip, verbose, dev_config=None):
QuietHandler.verbose = verbose QuietHandler.verbose = verbose
QuietHandler.dev_config = dev_config
handler = functools.partial(QuietHandler, directory=PROJECT_DIR) handler = functools.partial(QuietHandler, directory=PROJECT_DIR)
server = http.server.ThreadingHTTPServer((bind_ip, 0), handler) server = http.server.ThreadingHTTPServer((bind_ip, 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start() threading.Thread(target=server.serve_forever, daemon=True).start()
@@ -133,6 +151,12 @@ def main():
parser.add_argument("--box", help="adresse IP du Player (sinon découverte SSDP)") 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("--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("--verbose", action="store_true", help="affiche les fichiers téléchargés par le Player")
parser.add_argument("--server", action="append", default=[], metavar="ADRESSE",
help="serveur Jellyfin ajouté automatiquement par l'app au démarrage "
"(ex. media.stilobique.com ; option répétable)")
parser.add_argument("--user", action="extend", nargs="+", default=[], metavar="NOM[:MOT_DE_PASSE]",
help="compte(s) affiché(s) sur l'écran « Qui regarde ? » ; avec mot de passe, "
"connexion en un clic (ex. --user alice:mdp bob, ou --user répété)")
parser.add_argument("--log", default=os.path.join(PROJECT_DIR, "deploy.log"), 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)") help="fichier de log, écrasé à chaque lancement (défaut : deploy.log ; vide pour désactiver)")
args = parser.parse_args() args = parser.parse_args()
@@ -156,10 +180,20 @@ def main():
except OSError as error: except OSError as error:
sys.exit("Impossible de joindre %s:80 (%s)." % (box, error)) sys.exit("Impossible de joindre %s:80 (%s)." % (box, error))
server = serve_project(me, args.verbose) users = []
for spec in args.user:
name, sep, password = spec.partition(":")
users.append({"name": name, "password": password} if sep else {"name": name})
dev_config = {"servers": args.server, "users": users} if (args.server or users) else None
server = serve_project(me, args.verbose, dev_config)
port = server.server_address[1] port = server.server_address[1]
manifest_url = "http://%s:%d/manifest.json" % (me, port) manifest_url = "http://%s:%d/manifest.json" % (me, port)
print("Projet servi sur %s" % manifest_url) print("Projet servi sur %s" % manifest_url)
if args.server:
print("Serveurs de test proposés à l'app : %s" % ", ".join(args.server))
if users: # les mots de passe ne sont jamais affichés
print("Utilisateurs de test : %s" % ", ".join(
u["name"] + (" (mot de passe fourni)" if "password" in u else "") for u in users))
try: try:
result = json_rpc(box, "debug_qml_app", { result = json_rpc(box, "debug_qml_app", {