Compare commits

..
11 Commits
Author SHA1 Message Date
stilobique 4b54797246 Update configuration
CI / Vérifications et paquet (push) Successful in 1m50s
CI / Release Gitea (push) Skipped
2026-11-15 10:29:09 +01:00
stilobiqueandClaude Opus 5.5 1b2acae316 Add test suite (box rules, Python, QML against a fake Jellyfin server) and local preview jobs
CI / Vérifications et paquet (push) Successful in 48s
CI / Release Gitea (push) Skipped
- freebox-jellyfin test: box-only rules (ES5, QtQuick 2.5, qmldir, singletons),
  tooling unit tests, qmltestrunner on tests/qml against fake_server.py
- freebox-jellyfin fake-server and preview --fake-server
- package enforces the box rules; CI runs the tests
- JetBrains run configs: Local Preview, Local Preview (faux serveur), Tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:08:03 +01:00
stilobiqueandClaude Opus 5.5 d0d019ac1e Release 0.1.1
CI / Release Gitea (push) Successful in 13s
CI / Vérifications et paquet (push) Successful in 1m56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 23:48:39 +01:00
stilobiqueandClaude Opus 5.5 4f6c8a254e Update CLAUDE.md, stop tracking machine-specific QtCreator config
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 23:47:09 +01:00
stilobique b1ca2a7cff Refactoring: move all apps inside a sub folder
CI / Release Gitea (push) Successful in 32s
CI / Vérifications et paquet (push) Successful in 47s
2026-11-08 14:28:28 +01:00
stilobique 33e4fe0c4e Refactoring, create a src folders with the python toolchain 2026-11-08 14:22:51 +01:00
stilobique 2790d92a60 Ignore jetbrains folder
CI / Vérifications et paquet (push) Successful in 27s
CI / Release Gitea (push) Skipped
2026-11-08 14:09:50 +01:00
stilobique 3d61740f5a Add simple CI 2026-11-08 14:08:59 +01:00
stilobique 20b8fcc1c1 More setup about the deployment 2026-11-08 12:17:13 +01:00
stilobique 821332508f Add basic setup about the package generation 2026-11-08 12:12:37 +01:00
stilobique 8e6392a84c Add basic behavior to play, show catalog and more basic feature 2026-11-08 12:06:15 +01:00
63 changed files with 4090 additions and 273 deletions

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
# Tests et vérifications à chaque push / pull request, et release Gitea avec le paquet FreeStore
# sur un tag « vX.Y.Z » (qui doit correspondre à « version » dans app/manifest.json).
# Le téléversement sur la console FreeFactory reste manuel (pas d'API connue).
name: CI
on:
push:
branches: ["**"]
tags: ["v*"]
pull_request:
jobs:
check:
name: Vérifications et paquet
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Dépendances (Qt 5, qmllint, libfbxqml)
run: |
SUDO=$(command -v sudo || true)
$SUDO apt-get update -qq
DEBIAN_FRONTEND=noninteractive $SUDO apt-get install -y -qq --no-install-recommends \
curl git ca-certificates qmlscene qtdeclarative5-dev-tools \
qml-module-qtquick2 qml-module-qtquick-window2 qml-module-qtmultimedia qml-module-qttest
git clone --depth 1 https://github.com/fbx/libfbxqml.git ../libfbxqml
- name: uv (outils Python du dépôt)
run: |
curl -LsSf https://astral.sh/uv/0.12.9/install.sh | sh
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: Tests (règles de la box, outillage Python, QML contre un faux serveur Jellyfin)
run: uv run --locked freebox-jellyfin test
- name: Manifest, syntaxe QML/JS et paquet FreeStore
run: uv run --locked freebox-jellyfin package
- name: Chargement en HTTP, comme sur la box
run: uv run --locked freebox-jellyfin check
- name: Paquet en artefact
uses: actions/upload-artifact@v3
with:
name: freestore-package
path: dist/*.tar.gz
release:
name: Release Gitea
needs: check
if: startsWith(gitea.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Dépendances
run: |
SUDO=$(command -v sudo || true)
$SUDO apt-get update -qq
DEBIAN_FRONTEND=noninteractive $SUDO apt-get install -y -qq --no-install-recommends \
python3 curl ca-certificates
- name: Le tag correspond à la version du manifest
env:
TAG: ${{ gitea.ref_name }}
run: |
VERSION=$(python3 -c "import json; print(json.load(open('app/manifest.json'))['version'])")
if [ "$TAG" != "v$VERSION" ]; then
echo "Le tag $TAG ne correspond pas à la version du manifest (v$VERSION)."
exit 1
fi
- uses: actions/download-artifact@v3
with:
name: freestore-package
path: dist
- name: Créer la release et joindre le paquet
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}
TAG: ${{ gitea.ref_name }}
run: |
FILE=$(ls dist/*.tar.gz)
BODY=$(python3 -c "import json,sys; print(json.dumps({'tag_name': sys.argv[1], 'name': sys.argv[1], 'body': 'Paquet FreeStore à téléverser sur la console FreeFactory (http://factory.free.fr).'}))" "$TAG")
ID=$(curl -sSf -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
"$API/releases" -d "$BODY" | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])")
curl -sSf -X POST -H "Authorization: token $TOKEN" -F "attachment=@$FILE" \
"$API/releases/$ID/assets?name=$(basename "$FILE")" > /dev/null
echo "Release $TAG créée avec $(basename "$FILE")."
+11 -1
View File
@@ -71,5 +71,15 @@ Thumbs.db
*.exe *.exe
# Log de tools/deploy.py # Log de freebox-jellyfin deploy
deploy.log deploy.log
# Paquets FreeStore (freebox-jellyfin package)
dist/
# Environnement Python local (Rider)
.venv/
.idea/**
# Cible de déploiement QtCreator, propre à chaque machine
app/Jellyfin.fbxproject.user
+1
View File
@@ -0,0 +1 @@
3.14
+4 -4
View File
@@ -12,13 +12,13 @@
<option name="IS_MODULE_SDK" value="true" /> <option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" /> <option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" /> <option name="ADD_SOURCE_ROOTS" value="true" />
<option name="DEBUG_JUST_MY_CODE" value="false" />
<option name="RUN_TOOL" value="" /> <option name="RUN_TOOL" value="" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/tools/deploy.py" /> <option name="RUN_AS_SCRIPT" value="false" />
<option name="PARAMETERS" value="" /> <option name="SCRIPT_NAME" value="freebox_jellyfin" />
<option name="PARAMETERS" value="deploy" />
<option name="SHOW_COMMAND_LINE" value="false" /> <option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" /> <option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" /> <option name="MODULE_MODE" value="true" />
<option name="REDIRECT_INPUT" value="false" /> <option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" /> <option name="INPUT_FILE" value="" />
<method v="2" /> <method v="2" />
+26
View File
@@ -0,0 +1,26 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Local Preview (faux serveur)" type="PythonConfigurationType" factoryName="Python">
<module name="rider.module" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="RUN_TOOL" value="" />
<option name="RUN_AS_SCRIPT" value="false" />
<option name="SCRIPT_NAME" value="freebox_jellyfin" />
<option name="PARAMETERS" value="preview --fake-server" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="true" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
+27
View File
@@ -0,0 +1,27 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Local Preview" type="PythonConfigurationType" factoryName="Python">
<module name="rider.module" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="SDK_NAME" value="Jellyfin-Freebox" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="RUN_TOOL" value="" />
<option name="RUN_AS_SCRIPT" value="false" />
<option name="SCRIPT_NAME" value="freebox_jellyfin" />
<option name="PARAMETERS" value="preview" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="true" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
+26
View File
@@ -0,0 +1,26 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Tests" type="PythonConfigurationType" factoryName="Python">
<module name="rider.module" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="RUN_TOOL" value="" />
<option name="RUN_AS_SCRIPT" value="false" />
<option name="SCRIPT_NAME" value="freebox_jellyfin" />
<option name="PARAMETERS" value="test" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="true" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
+33 -16
View File
@@ -6,45 +6,62 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
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. 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.
## Layout
- `app/` — the application itself, the only directory served to / packaged for the Player (`manifest.json`, `Jellyfin.qml`, `icon.png`, `Components/`, `Core/`, `Shared/`, `Views/`, plus the QtCreator project `Jellyfin.fbxproject`). Paths in the Architecture section are relative to `app/`.
- `src/freebox_jellyfin/` — Python dev tooling; `tests/` — QML tests (`tests/qml/`) and tooling tests (`tests/python/`), never packaged; `tools/preview.qml` — desktop preview wrapper; `dist/`, `deploy.log` — generated at the repo root.
## Build / run ## Build / run
There is no build system or test suite. There is no build system. Automated guards: `freebox-jellyfin test` and `check` (both in CI); what they can't cover (real playback, the box's Qt 5.5 runtime, persistence) is verified on the box with `deploy`.
**Local preview on the PC** (no Freebox needed): `fbx.application` from [libfbxqml](https://github.com/fbx/libfbxqml) is pure QML (a fullscreen `Window` scaled to a 720p virtual height), so the app runs with Qt 5's `qmlscene`. **Local preview on the PC** (no Freebox needed): `fbx.application` from [libfbxqml](https://github.com/fbx/libfbxqml) is pure QML (a fullscreen `Window` scaled to a 720p virtual height), so the app runs with Qt 5's `qmlscene`.
- 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 qml-module-qttest`, 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. - Dev tooling is the Python package `freebox_jellyfin` (`src/freebox_jellyfin/`, uv project, Python 3.14, stdlib only): `uv sync`, then `uv run freebox-jellyfin <preview|check|test|fake-server|package|deploy>` (also `python -m freebox_jellyfin`).
- `QT_QPA_PLATFORM=offscreen tools/run-local.sh` — headless run, useful to catch QML warnings. - `uv run freebox-jellyfin preview` — 1280×720 window via `tools/preview.qml`; `--fullscreen` runs `app/Jellyfin.qml` as the box would; `--fake-server` also starts the fake Jellyfin below on `127.0.0.1:8096` for the session. JetBrains run configs in `.run/`: Local Preview, Local Preview (faux serveur), Tests, Local Deploy.
- `QT_QPA_PLATFORM=offscreen uv run freebox-jellyfin preview` — 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. - 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: `cd app && 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. - `uv run freebox-jellyfin test` — three stages, stops at the first failure: (1) `boxrules.py`, the box-only rules the desktop doesn't catch (ES5 syntax, QtQuick ≤ 2.5, no QtQuick.Controls, `qmldir` completeness, singleton cycles, no `import "."`; also enforced by `package`); (2) `tests/python/` (unittest); (3) `qmltestrunner` on `tests/qml/tst_*.qml`, offscreen, against `fake_server.py`. Single file: `--qml tst_session.qml`; single function: `freebox-jellyfin test Session::test_logout` (TestCase `name` + function).
- **QML tests**: `tst_helpers` (Format/Remote/DeviceProfile), `tst_session` (Session API against the fake server: probing, auth header, catalog, PlaybackInfo, Quick Connect, `cancel()`, errors/timeouts), `tst_player` (PlayerView reporting rules, with a fake session and `VideoSurface` driven by hand), `tst_flow` (remote-control journeys through Navigator + real views + real Session). Extend `JellyfinTestCase.qml` (helpers: `waitCallback`, `requests`, `mock`, `resetServer`, `findChild`); the fake server's URL comes from the generated `TestEnv` module (`Env.baseUrl/host/port`). Tests run on Qt 5.15, so `tests/` is exempt from the ES5 rule. **A `TestCase` is invisible and `KeyNavigation` skips invisible items**: put UI under a visible root `Item` next to the `TestCase`, not inside it. Set state in the order `VideoSurface._poll()` does (position, then `playerState`).
- `uv run freebox-jellyfin fake-server [--port 8096]` — the same fake Jellyfin (`fake_server.py`: users alice/secret and bob without password, Films with 25 movies incl. direct/transcode/unplayable ones, a series with 2 seasons, Quick Connect code 123456) for working in `preview` without a real server: add server `127.0.0.1`, port `8096`. Control endpoints for tests: `/__reset`, `/__requests`, `/__mock`, `/__quickconnect/authorize`.
- `uv run freebox-jellyfin check` — serves `app/` over HTTP and loads it with `qmlscene` (offscreen, software renderer) like the box does; fails on any Qt warning not coming from libfbxqml. This reproduces the box's HTTP loading mode, which behaves differently from local files (see constraints below): run it after touching imports, `qmldir` files or singletons.
- 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. `--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: **CI** (`.gitea/workflows/ci.yml`, Gitea Actions on the `ubuntu-latest` runner image): installs uv (pinned 0.12.9, which fetches Python 3.14) and on every push/PR runs `uv run --locked freebox-jellyfin test`, `… package` (manifest + box rules + qmllint + archive) and `… check`; package uploaded as artifact (`upload-artifact@v3`/`download-artifact@v3`: v4 only works on recent Gitea versions). On tag `vX.Y.Z` matching `manifest.json` `version`, creates a Gitea release with the package attached (API calls with the job's `GITHUB_TOKEN`).
**Releasing**: bump `version` in `app/manifest.json` **and** `clientVersion` in `app/Core/Session.qml` (`package` refuses to build if they differ), then push a `vX.Y.Z` tag.
**FreeStore package**: `freebox-jellyfin package` → `dist/<identifier>-<version>.tar.gz` (gitignored). Replicates the QtCreator plugin's "Make FreeStore Package": same file selection as `Jellyfin.fbxproject` (QML/JS/images/fonts/`qmldir`/`manifest.json` under `app/`, hidden dirs excluded; archive paths relative to `app/`), manifest checks (identifier `\w+(\.\w+)+`, `version` x.y.z equal to `Session.clientVersion`, entry-point files present), `qmllint` on all sources, ustar tar with directory entries, gzipped. Upload is manual on the FreeFactory console (http://factory.free.fr), followed by Free's review.
**Deploying a test build to the Freebox**: `freebox-jellyfin deploy` (`src/freebox_jellyfin/deploy.py`; Player must be in developer mode). It discovers the Player via SSDP (`fbx:devel`) or takes `--box <IP>`, serves `app/` 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. This is the only way to see the app's `console.log`: an app installed from the FreeStore sends no logs anywhere (server-side, only the Jellyfin dashboard's activity and server logs are available). 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 `app/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).
- `Jellyfin.fbxproject` packages every QML/JS/image/font/`qmldir` file under the repo root plus `manifest.json` — new files are picked up automatically. - `Jellyfin.fbxproject` packages every QML/JS/image/font/`qmldir` file under `app/` plus `manifest.json` — new files are picked up automatically.
## Architecture ## Architecture
- `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. The logo panel hides when the current page sets `fullscreen: true` (catalog and player screens).
- `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`. `openItem(item)` routes a catalog item to `Library` / `Season` / `Details`.
- `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. - `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: all candidates in parallel, first success in priority order wins so a slow first TLS handshake doesn't fall back to http), `/Users/Public`, `/Users/AuthenticateByName`, `/Sessions/Logout`, `/QuickConnect/*`; catalog `/UserViews`, `/UserItems/Resume`, `/Items/Latest`, `/Items`, `/Shows/{id}/Seasons|Episodes`; playback `/Items/{id}/PlaybackInfo` and `/Sessions/Playing[/Progress|/Stopped]`. API items are flattened by `_toItem()` (no `index` key: reserved role name in `ListModel`). Image URLs via `posterUrl()` / `thumbUrl()` / `backdropUrl()`. 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`. - `Core/DeviceProfile.js` — what the Freebox Player can play, sent in `PlaybackInfo`: direct play H.264 only (the Revolution has no HEVC), otherwise HLS transcode. Text subtitles must stay declared `External` and `SubtitleStreamIndex: -1` sent, or Jellyfin transcodes to burn them in (`SubtitleCodecNotSupported`).
- `Shared/` — `Theme` singleton (colors, spacing, fonts; the only type in `Shared/qmldir`) and `Remote.js` (`.pragma library`, `isAccept`/`isBack` key mapping, imported `as Remote`). - `Components/` — reusable widgets, listed in `Components/qmldir`. `MediaCard` / `MediaRow` for catalog cards and horizontal rows. `VideoSurface` wraps the player: it tries the Freebox native `fbx.media` `VideoPlayer` then QtMultimedia `Video`, both created with `Qt.createQmlObject` so a missing module doesn't break loading; it polls the backend and exposes `position`/`duration` (ms) and `playerState`. **On the box, `fbx.media` is not installed: QtMultimedia is what plays** (verified: HLS transcode, seek/resume, pause, positions in ms). The fbx branch is kept as a fallback but is untested.
- `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). - `Shared/` — `Theme` singleton (colors, spacing, fonts, card sizes; the only type in `Shared/qmldir`), `Remote.js` (`isAccept`/`isBack` key mapping) and `Format.js` (durations, ticks↔ms, card labels), both `.pragma library`.
- `Views/` — one screen per file, each rooted in `Page` (title/subtitle header + content area). Flow: `ServerSelect` → `ServerAdd` → `UserSelect` → `Login` (password or Quick Connect) → `Home` (rows: Reprendre, Mes médias, latest per library) → `Library` (paged poster grid) / `Details` (movie, episode, or series with seasons) → `Season` (episodes) → `Player` (`PlayerView` is a plain `FocusScope`, not a `Page`).
## Platform constraints ## Platform constraints
- 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. - **No persistent storage when launched via `freebox-jellyfin deploy`** (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`. - 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;
- 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; - 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. - no `import "."` self-imports.
- **Playback reporting must never clobber the server's resume point**: `PlayerView` reports start/progress/stop only once playback actually started *and* the resume position was reached, and never with position 0. (A failed playback reporting a stop at 0 wipes the user's resume position.)
- Don't disable (`enabled: false`) a focused control during loading — it loses focus and the remote stops responding; guard with a `busy` flag instead. - Don't disable (`enabled: false`) a focused control during loading — it loses focus and the remote stops responding; guard with a `busy` flag instead.
-141
View File
@@ -1,141 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 4.3.0, 2024-08-12T17:50:51. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
<value type="QByteArray">{82daaaf9-c426-482c-8459-9906e026a767}</value>
</data>
<data>
<variable>ProjectExplorer.Project.ActiveTarget</variable>
<value type="int">0</value>
</data>
<data>
<variable>ProjectExplorer.Project.EditorSettings</variable>
<valuemap type="QVariantMap">
<value type="bool" key="EditorConfiguration.AutoIndent">true</value>
<value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value>
<value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">CppGlobal</value>
</valuemap>
</valuemap>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1">
<value type="QString" key="language">QmlJS</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value>
</valuemap>
</valuemap>
<value type="int" key="EditorConfiguration.CodeStyle.Count">2</value>
<value type="QByteArray" key="EditorConfiguration.Codec">UTF-8</value>
<value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
<value type="int" key="EditorConfiguration.IndentSize">4</value>
<value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
<value type="int" key="EditorConfiguration.MarginColumn">80</value>
<value type="bool" key="EditorConfiguration.MouseHiding">true</value>
<value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
<value type="int" key="EditorConfiguration.PaddingMode">1</value>
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value>
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
<value type="int" key="EditorConfiguration.TabSize">8</value>
<value type="bool" key="EditorConfiguration.UseGlobal">true</value>
<value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value>
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
<value type="bool" key="EditorConfiguration.cleanIndentation">true</value>
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
<value type="bool" key="EditorConfiguration.inEntireDocument">false</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.PluginSettings</variable>
<valuemap type="QVariantMap"/>
</data>
<data>
<variable>ProjectExplorer.Project.Target.0</variable>
<valuemap type="QVariantMap">
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Freebox (192.168.0.20)</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Freebox (192.168.0.20)</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{2fffcf57-628c-4672-8f03-a48ccdb2ddbd}</value>
<value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">-1</value>
<value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">-1</value>
<value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">0</value>
<value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.PluginSettings"/>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
<value type="bool" key="Analyzer.QmlProfiler.AggregateTraces">false</value>
<value type="bool" key="Analyzer.QmlProfiler.FlushEnabled">false</value>
<value type="uint" key="Analyzer.QmlProfiler.FlushInterval">1000</value>
<value type="QString" key="Analyzer.QmlProfiler.LastTraceFile"></value>
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.AddedSuppressionFiles"/>
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectBusEvents">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectSystime">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableBranchSim">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableCacheSim">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableEventToolTips">true</value>
<value type="double" key="Analyzer.Valgrind.Callgrind.MinimumCostRatio">0.01</value>
<value type="double" key="Analyzer.Valgrind.Callgrind.VisualisationMinimumCostRatio">10</value>
<value type="bool" key="Analyzer.Valgrind.FilterExternalIssues">true</value>
<value type="int" key="Analyzer.Valgrind.LeakCheckOnFinish">1</value>
<value type="int" key="Analyzer.Valgrind.NumCallers">25</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.RemovedSuppressionFiles"/>
<value type="int" key="Analyzer.Valgrind.SelfModifyingCodeDetection">1</value>
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.Valgrind.ShowReachable">false</value>
<value type="bool" key="Analyzer.Valgrind.TrackOrigins">true</value>
<value type="QString" key="Analyzer.Valgrind.ValgrindExecutable">valgrind</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.VisibleErrorKinds">
<value type="int">0</value>
<value type="int">1</value>
<value type="int">2</value>
<value type="int">3</value>
<value type="int">4</value>
<value type="int">5</value>
<value type="int">6</value>
<value type="int">7</value>
<value type="int">8</value>
<value type="int">9</value>
<value type="int">10</value>
<value type="int">11</value>
<value type="int">12</value>
<value type="int">13</value>
<value type="int">14</value>
</valuelist>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="QString" key="ProjectExplorer.CustomExecutableRunConfiguration.Arguments"></value>
<value type="QString" key="ProjectExplorer.CustomExecutableRunConfiguration.Executable"></value>
<value type="QString" key="ProjectExplorer.CustomExecutableRunConfiguration.WorkingDirectory">%{sourceDir}</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Custom Executable</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
<value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</value>
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseMultiProcess">false</value>
<value type="bool" key="RunConfiguration.UseQmlDebugger">false</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.TargetCount</variable>
<value type="int">1</value>
</data>
<data>
<variable>ProjectExplorer.Project.Updater.FileVersion</variable>
<value type="int">18</value>
</data>
<data>
<variable>Version</variable>
<value type="int">18</value>
</data>
</qtcreator>
-54
View File
@@ -1,54 +0,0 @@
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 {
id: page
title: page.session && page.session.currentUser
? "Bonjour " + page.session.currentUser.name
: "Accueil"
subtitle: page.session && page.session.currentServer
? "Connecté à " + page.session.currentServer.name + "."
: ""
initialFocus: backButton
// La pile a été réinitialisée à la connexion : on reconstruit Serveurs > Utilisateurs
// pour revenir au choix de l'utilisateur.
function goBack() {
page.navigator.reset("ServerSelect");
page.navigator.push("UserSelect");
}
// La touche Retour de la télécommande fait la même chose que le bouton
// (sinon, à la racine de la pile, elle fermerait l'application).
Keys.onPressed: {
if (Remote.isBack(event.key)) {
event.accepted = true;
page.goBack();
}
}
Row {
spacing: Theme.spacingM
FocusButton {
id: backButton
text: "Retour"
KeyNavigation.right: logoutButton
onClicked: page.goBack()
}
FocusButton {
id: logoutButton
text: "Se déconnecter"
KeyNavigation.left: backButton
onClicked: {
page.session.logout();
page.goBack();
}
}
}
}
File renamed without changes.
File renamed without changes.
+115
View File
@@ -0,0 +1,115 @@
import QtQuick 2.5
import "../Shared"
// Carte du catalogue : image (affiche ou vignette), titre, sous-titre, avancement.
Item {
id: card
property string title: ""
property string subtitle: ""
property url imageSource: ""
property int imageHeight: Theme.posterHeight
property real progress: 0
property bool played: false
property bool highlighted: false
property bool showText: true
signal clicked()
height: imageHeight + (showText ? Theme.cardTextHeight : 0)
z: highlighted ? 1 : 0
Rectangle {
id: frame
width: parent.width
height: card.imageHeight
radius: Theme.radius
color: Theme.surface
border.width: card.highlighted ? 3 : 0
border.color: Theme.focusBackground
scale: card.highlighted ? 1.06 : 1
Behavior on scale { NumberAnimation { duration: Theme.animFast } }
// Initiale tant que l'image n'est pas chargée (ou absente).
Text {
anchors.centerIn: parent
visible: image.status !== Image.Ready
text: card.title.charAt(0).toUpperCase()
color: Theme.textMuted
font.pixelSize: 48
font.bold: true
}
Image {
id: image
anchors.fill: parent
anchors.margins: frame.border.width
source: card.imageSource
fillMode: Image.PreserveAspectCrop
asynchronous: true
clip: true
sourceSize.height: card.imageHeight
}
Rectangle {
visible: card.progress > 0.01 && !card.played
anchors { left: parent.left; right: parent.right; bottom: parent.bottom; margins: 8 }
height: 4
radius: 2
color: "#99000000"
Rectangle {
width: parent.width * Math.min(1, card.progress)
height: parent.height
radius: 2
color: Theme.accent
}
}
Rectangle {
visible: card.played
anchors { top: parent.top; right: parent.right; margins: 8 }
width: playedText.implicitWidth + Theme.spacingS * 2
height: playedText.implicitHeight + 4
radius: height / 2
color: Theme.accent
Text {
id: playedText
anchors.centerIn: parent
text: "VU"
color: Theme.text
font.pixelSize: 11
font.bold: true
}
}
}
Column {
visible: card.showText
anchors { top: frame.bottom; topMargin: Theme.spacingS; left: parent.left; right: parent.right }
Text {
width: parent.width
text: card.title
elide: Text.ElideRight
color: card.highlighted ? Theme.text : Theme.textMuted
font.pixelSize: Theme.fontSmall + 1
font.bold: card.highlighted
}
Text {
width: parent.width
visible: text !== ""
text: card.subtitle
elide: Text.ElideRight
color: Theme.textMuted
font.pixelSize: Theme.fontSmall - 1
}
}
MouseArea {
anchors.fill: parent
onClicked: card.clicked()
}
}
+73
View File
@@ -0,0 +1,73 @@
import QtQuick 2.5
import "../Shared"
import "../Shared/Remote.js" as Remote
import "../Shared/Format.js" as Format
// Rangée horizontale de cartes avec un titre (accueil, saisons…).
// `items` : éléments aplatis par Session._toItem().
FocusScope {
id: row
property string title: ""
property var items: []
property bool landscape: false
property var session: null
property alias currentIndex: list.currentIndex
signal activated(var item)
readonly property int cardWidth: landscape ? Theme.thumbWidth : Theme.posterWidth
readonly property int imageHeight: landscape ? Theme.thumbHeight : Theme.posterHeight
height: titleText.height + Theme.spacingM + imageHeight + Theme.cardTextHeight + Theme.spacingM
Text {
id: titleText
text: row.title
color: row.activeFocus ? Theme.text : Theme.textMuted
font.pixelSize: Theme.fontBody
font.bold: true
}
ListView {
id: list
anchors {
top: titleText.bottom
topMargin: Theme.spacingM
left: parent.left
right: parent.right
bottom: parent.bottom
}
orientation: ListView.Horizontal
spacing: Theme.spacingM
focus: true
// Marge pour la carte agrandie (scale) au bord gauche.
leftMargin: 8
rightMargin: 8
highlightMoveDuration: 150
model: row.items
delegate: MediaCard {
width: row.cardWidth
imageHeight: row.imageHeight
title: Format.cardTitle(modelData)
subtitle: Format.cardSubtitle(modelData)
imageSource: !row.session ? ""
: row.landscape ? row.session.thumbUrl(modelData)
: row.session.posterUrl(modelData)
progress: Format.progress(modelData)
played: modelData.played
highlighted: ListView.isCurrentItem && list.activeFocus
onClicked: {
list.currentIndex = index;
row.activated(modelData);
}
}
Keys.onPressed: {
if (Remote.isAccept(event.key) && currentIndex >= 0) {
event.accepted = true;
row.activated(row.items[currentIndex]);
}
}
}
}
@@ -10,11 +10,24 @@ FocusScope {
property var session: null property var session: null
// Élément qui reçoit le focus quand l'écran s'affiche. // Élément qui reçoit le focus quand l'écran s'affiche.
property Item initialFocus: null property Item initialFocus: null
// true : masque le panneau du logo (écrans du catalogue).
property bool fullscreen: false
// Image de fond facultative (assombrie).
property alias backdrop: backdropImage.source
property alias title: titleText.text property alias title: titleText.text
property alias subtitle: subtitleText.text property alias subtitle: subtitleText.text
default property alias content: body.data default property alias content: body.data
Image {
id: backdropImage
anchors.fill: parent
visible: status === Image.Ready
fillMode: Image.PreserveAspectCrop
asynchronous: true
opacity: 0.25
}
Column { Column {
id: header id: header
anchors { anchors {
File renamed without changes.
File renamed without changes.
File renamed without changes.
+162
View File
@@ -0,0 +1,162 @@
import QtQuick 2.5
// Surface vidéo avec une interface unique, quel que soit le lecteur disponible :
// - "fbx" : VideoPlayer de libfbxqml (fbx.media) — absent du Freebox Player testé,
// conservé en premier choix au cas où, mais jamais vérifié ;
// - "qtmultimedia" : Video de QtMultimedia — c'est lui qui lit sur la box (HLS, reprise,
// pause et déplacement vérifiés ; positions en millisecondes).
// Les deux sont créés dynamiquement : un module absent ne fait pas échouer le chargement.
//
// position / duration en millisecondes ; playerState : "idle", "loading", "playing",
// "paused", "ended" ou "error". Les états bruts du lecteur sont écrits dans le log.
Item {
id: root
property string source: ""
property real position: 0
property real duration: 0
property string playerState: "idle"
property string errorString: ""
property string backendName: ""
signal ended()
property var _backend: null
property string _lastRaw: ""
function play() {
if (_backend)
_backend.play();
}
function pause() {
if (_backend)
_backend.pause();
}
function togglePause() {
if (playerState === "playing")
pause();
else
play();
}
function seek(ms) {
if (!_backend)
return;
var target = Math.max(0, duration > 0 ? Math.min(ms, duration - 1000) : ms);
console.log("Lecteur : déplacement à " + Math.round(target / 1000) + " s");
_backend.seek(target);
}
function stop() {
if (!_backend)
return;
_backend.stop();
if (backendName === "fbx" && _backend.close)
_backend.close();
}
function _create() {
var attempts = [
{ name: "fbx", qml: 'import QtQuick 2.5; import fbx.media 1.0; VideoPlayer { anchors.fill: parent }' },
{ name: "qtmultimedia", qml: 'import QtQuick 2.5; import QtMultimedia 5.0; '
+ 'Video { anchors.fill: parent; fillMode: VideoOutput.PreserveAspectFit }' }
];
for (var i = 0; i < attempts.length && !_backend; i++) {
try {
_backend = Qt.createQmlObject(attempts[i].qml, root, "VideoSurface-" + attempts[i].name);
backendName = attempts[i].name;
} catch (e) {
console.log("Lecteur " + attempts[i].name + " indisponible : " + e);
}
}
if (!_backend) {
_fail("Aucun lecteur vidéo disponible.");
return;
}
console.log("Lecteur vidéo : " + backendName);
if (backendName === "fbx" && _backend.error) {
_backend.error.connect(function (message, fatal) {
console.log("Lecteur fbx : erreur " + message + (fatal ? " (fatale)" : ""));
if (fatal)
_fail(String(message));
});
}
if (source !== "")
_open();
}
function _open() {
errorString = "";
playerState = "loading";
_backend.source = source;
_backend.play();
}
function _fail(message) {
errorString = message;
playerState = "error";
}
// Lecture périodique de l'état du lecteur (identique pour les deux backends).
function _poll() {
if (!_backend || playerState === "error")
return;
var raw;
if (backendName === "fbx") {
raw = "mediaState=" + _backend.mediaState + " playbackState=" + _backend.playbackState
+ " status=" + _backend.status;
position = _backend.position || 0;
duration = _backend.duration || 0;
var media = String(_backend.mediaState);
var playback = String(_backend.playbackState);
if (media === "ended")
_setState("ended");
else if (playback === "playing")
_setState("playing");
else if (playback === "paused")
_setState("paused");
else
_setState("loading");
} else {
// Valeurs de MediaPlayer : playbackState 1 = lecture, 2 = pause ;
// status 7 = fin du média, 8 = média invalide.
raw = "status=" + _backend.status + " playbackState=" + _backend.playbackState;
position = _backend.position || 0;
duration = _backend.duration > 0 ? _backend.duration : 0;
if (_backend.status === 8 || (_backend.errorString && _backend.error !== 0))
_fail(_backend.errorString || "Média illisible.");
else if (_backend.status === 7)
_setState("ended");
else if (_backend.playbackState === 1)
_setState(_backend.status === 4 || _backend.status === 5 ? "loading" : "playing");
else if (_backend.playbackState === 2)
_setState("paused");
}
if (raw !== _lastRaw) {
_lastRaw = raw;
console.log("Lecteur " + backendName + " : " + raw + " position=" + Math.round(position)
+ " durée=" + Math.round(duration));
}
}
function _setState(state) {
if (state === playerState)
return;
playerState = state;
if (state === "ended")
ended();
}
onSourceChanged: if (_backend && source !== "") _open()
Timer {
interval: 250
repeat: true
running: root._backend !== null && root.source !== ""
onTriggered: root._poll()
}
Component.onCompleted: _create()
Component.onDestruction: stop()
}
@@ -4,3 +4,6 @@ TextField 1.0 TextField.qml
ServerItem 1.0 ServerItem.qml ServerItem 1.0 ServerItem.qml
UserCard 1.0 UserCard.qml UserCard 1.0 UserCard.qml
Logo 1.0 Logo.qml Logo 1.0 Logo.qml
MediaCard 1.0 MediaCard.qml
MediaRow 1.0 MediaRow.qml
VideoSurface 1.0 VideoSurface.qml
+44
View File
@@ -0,0 +1,44 @@
.pragma library
// Ce que le Freebox Player (Revolution) sait lire, déclaré à Jellyfin dans PlaybackInfo.
// Jellyfin choisit alors : lecture directe si le fichier convient, sinon transcodage HLS.
// Hypothèses prudentes (H.264 seulement : pas de HEVC sur la Revolution), à ajuster
// d'après les essais sur la box.
var maxBitrate = 20000000;
function profile() {
return {
Name: "Freebox Player",
MaxStreamingBitrate: maxBitrate,
MaxStaticBitrate: maxBitrate,
DirectPlayProfiles: [
{ Type: "Video", Container: "mp4,m4v,mkv,ts,mov", VideoCodec: "h264", AudioCodec: "aac,mp3,ac3" }
],
TranscodingProfiles: [
{
Type: "Video", Container: "ts", Protocol: "hls", Context: "Streaming",
VideoCodec: "h264", AudioCodec: "aac,ac3", MaxAudioChannels: "6",
MinSegments: 1, BreakOnNonKeyFrames: true
}
],
CodecProfiles: [
{
Type: "Video", Codec: "h264",
Conditions: [
{ Condition: "LessThanEqual", Property: "Width", Value: "1920" },
{ Condition: "LessThanEqual", Property: "VideoBitDepth", Value: "8" }
]
}
],
// Sous-titres texte déclarés « externes » : sans ça, Jellyfin transcode pour les
// incruster (SubtitleCodecNotSupported). Le lecteur ne les affiche pas encore.
SubtitleProfiles: [
{ Format: "srt", Method: "External" },
{ Format: "subrip", Method: "External" },
{ Format: "ass", Method: "External" },
{ Format: "ssa", Method: "External" },
{ Format: "vtt", Method: "External" }
]
};
}
@@ -10,6 +10,7 @@ FocusScope {
property var session: null property var session: null
property int depth: 0 property int depth: 0
readonly property bool fullscreen: loader.item !== null && loader.item.fullscreen === true
property var _stack: [] property var _stack: []
function push(name, props) { function push(name, props) {
@@ -36,6 +37,17 @@ FocusScope {
push(name, props); push(name, props);
} }
// Ouvre l'écran adapté à un élément du catalogue (Session._toItem()).
function openItem(item) {
if (item.type === "CollectionFolder")
push("Library", { library: { id: item.id, name: item.name, collectionType: item.collectionType } });
else if (item.type === "Season")
push("Season", { seriesId: item.seriesId, seasonId: item.id, seasonName: item.name,
seriesName: item.seriesName });
else
push("Details", { itemId: item.id });
}
function _load() { function _load() {
var entry = _stack[_stack.length - 1]; var entry = _stack[_stack.length - 1];
var props = { navigator: root, session: root.session }; var props = { navigator: root, session: root.session };
+243 -13
View File
@@ -1,5 +1,6 @@
import QtQuick 2.5 import QtQuick 2.5
import fbx.application 1.0 import fbx.application 1.0
import "DeviceProfile.js" as DeviceProfile
// État de connexion et appels à l'API Jellyfin : serveurs enregistrés, // État de connexion et appels à l'API Jellyfin : serveurs enregistrés,
// serveur et utilisateur courants, jeton d'accès. // serveur et utilisateur courants, jeton d'accès.
@@ -9,7 +10,8 @@ QtObject {
id: session id: session
readonly property string clientName: "Jellyfin Freebox" readonly property string clientName: "Jellyfin Freebox"
readonly property string clientVersion: "0.1.0" // Doit rester égale à « version » dans manifest.json (vérifié par freebox-jellyfin package).
readonly property string clientVersion: "0.1.1"
readonly property string deviceName: "Freebox Player" readonly property string deviceName: "Freebox Player"
// Serveurs enregistrés : { name, address, id } // Serveurs enregistrés : { name, address, id }
@@ -18,7 +20,7 @@ QtObject {
property var currentServer: null // { name, address, id } property var currentServer: null // { name, address, id }
property var currentUser: null // { name, id } property var currentUser: null // { name, id }
property string accessToken: "" property string accessToken: ""
// Comptes de test fournis par tools/deploy.py --user : { name, password? } // Comptes de test fournis par freebox-jellyfin deploy --user : { name, password? }
property var devUsers: [] property var devUsers: []
// ---------------------------------------------------------------- Serveurs // ---------------------------------------------------------------- Serveurs
@@ -59,7 +61,7 @@ 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, server) { _probeCandidates(serverCandidates(host, portText), function (err, server) {
if (err) { if (err) {
callback(err); callback(err);
return; return;
@@ -73,7 +75,7 @@ QtObject {
}); });
} }
// Test sur la box : tools/deploy.py --server <adresse> --user <nom[:mdp]> sert // Test sur la box : freebox-jellyfin deploy --server <adresse> --user <nom[:mdp]> sert
// dev-config.json à côté de l'app ; chaque serveur listé est ajouté et les comptes // 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. // sont proposés sur « Qui regarde ? ». Absent (404) hors test : rien ne se passe.
function loadDevConfig(url) { function loadDevConfig(url) {
@@ -229,6 +231,207 @@ QtObject {
}); });
} }
// --------------------------------------------------------------- Catalogue
// Les éléments renvoyés sont « aplatis » par _toItem() (voir ses champs) pour
// pouvoir aller tels quels dans un ListModel ou un modèle JS.
// Bibliothèques de l'utilisateur : Films, Séries…
function loadLibraries(callback) {
callback = _guard(callback);
_request("GET", "/UserViews?" + _query({ userId: currentUser.id }), null, function (err, data) {
callback(err ? _describe(err) : null, err ? [] : _toItems(data.Items));
});
}
// « Reprendre » : vidéos commencées.
function loadResume(callback) {
callback = _guard(callback);
_request("GET", "/UserItems/Resume?" + _query({
userId: currentUser.id, limit: 20, mediaTypes: "Video", enableTotalRecordCount: false
}), null, function (err, data) {
callback(err ? _describe(err) : null, err ? [] : _toItems(data.Items));
});
}
// Derniers ajouts d'une bibliothèque.
function loadLatest(libraryId, callback) {
callback = _guard(callback);
_request("GET", "/Items/Latest?" + _query({ userId: currentUser.id, parentId: libraryId, limit: 20 }),
null, function (err, data) {
callback(err ? _describe(err) : null, err ? [] : _toItems(data));
});
}
// Contenu d'une bibliothèque, par pages. callback(err, items, total)
function loadLibraryItems(library, startIndex, limit, callback) {
callback = _guard(callback);
var types = library.collectionType === "tvshows" ? "Series"
: library.collectionType === "movies" ? "Movie" : "Movie,Series,Video";
_request("GET", "/Items?" + _query({
userId: currentUser.id, parentId: library.id, recursive: true, includeItemTypes: types,
sortBy: "SortName", sortOrder: "Ascending", startIndex: startIndex, limit: limit,
fields: "PrimaryImageAspectRatio"
}), null, function (err, data) {
if (err)
callback(_describe(err), [], 0);
else
callback(null, _toItems(data.Items), data.TotalRecordCount || 0);
});
}
function loadItem(itemId, callback) {
callback = _guard(callback);
_request("GET", "/Items/" + itemId + "?" + _query({ userId: currentUser.id }), null, function (err, data) {
callback(err ? _describe(err) : null, err ? null : _toItem(data));
});
}
function loadSeasons(seriesId, callback) {
callback = _guard(callback);
_request("GET", "/Shows/" + seriesId + "/Seasons?" + _query({ userId: currentUser.id }), null,
function (err, data) {
callback(err ? _describe(err) : null, err ? [] : _toItems(data.Items));
});
}
function loadEpisodes(seriesId, seasonId, callback) {
callback = _guard(callback);
_request("GET", "/Shows/" + seriesId + "/Episodes?" + _query({
userId: currentUser.id, seasonId: seasonId, fields: "Overview"
}), null, function (err, data) {
callback(err ? _describe(err) : null, err ? [] : _toItems(data.Items));
});
}
// URL d'image (pas d'authentification nécessaire). kind : "Primary", "Backdrop", "Thumb".
function imageUrl(itemId, kind, tag, maxHeight) {
if (!currentServer || !itemId || !tag)
return "";
return currentServer.address + "/Items/" + itemId + "/Images/" + kind + "?"
+ _query({ tag: tag, maxHeight: maxHeight || 360, quality: 90 });
}
// Affiche : celle de l'élément, sinon celle de sa série.
function posterUrl(item, maxHeight) {
if (item.imageTag)
return imageUrl(item.id, "Primary", item.imageTag, maxHeight);
return imageUrl(item.seriesId, "Primary", item.seriesPrimaryTag, maxHeight);
}
// Vignette 16:9 : image principale des bibliothèques/épisodes, sinon Thumb, sinon fond.
function thumbUrl(item, maxHeight) {
maxHeight = maxHeight || 300;
if ((item.type === "CollectionFolder" || item.type === "Episode") && item.imageTag)
return imageUrl(item.id, "Primary", item.imageTag, maxHeight);
if (item.thumbTag)
return imageUrl(item.id, "Thumb", item.thumbTag, maxHeight);
return backdropUrl(item, maxHeight) || posterUrl(item, maxHeight);
}
function backdropUrl(item, maxHeight) {
if (item.backdropTag)
return imageUrl(item.id, "Backdrop", item.backdropTag, maxHeight || 720);
return imageUrl(item.parentBackdropItemId, "Backdrop", item.parentBackdropTag, maxHeight || 720);
}
// ----------------------------------------------------------------- Lecture
// Demande à Jellyfin comment lire l'élément pour ce Player (profil DeviceProfile.js).
// callback(err, { url, itemId, mediaSourceId, playSessionId, playMethod })
function preparePlayback(itemId, callback) {
callback = _guard(callback);
_request("POST", "/Items/" + itemId + "/PlaybackInfo?" + _query({ userId: currentUser.id }),
// SubtitleStreamIndex -1 : pas de sous-titres (évite leur incrustation par transcodage).
{ DeviceProfile: DeviceProfile.profile(), MaxStreamingBitrate: DeviceProfile.maxBitrate,
SubtitleStreamIndex: -1 },
function (err, data) {
if (err) {
callback(_describe(err));
return;
}
var source = data.MediaSources && data.MediaSources[0];
if (data.ErrorCode || !source) {
callback("Lecture impossible (" + (data.ErrorCode || "aucune source") + ").");
return;
}
var info = { itemId: itemId, mediaSourceId: source.Id, playSessionId: data.PlaySessionId };
if (source.SupportsDirectPlay || source.SupportsDirectStream) {
info.playMethod = source.SupportsDirectPlay ? "DirectPlay" : "DirectStream";
info.url = currentServer.address + "/Videos/" + itemId + "/stream?" + _query({
static: true, mediaSourceId: source.Id, playSessionId: data.PlaySessionId,
deviceId: _settings.deviceId, api_key: accessToken
});
} else if (source.SupportsTranscoding && source.TranscodingUrl) {
info.playMethod = "Transcode";
info.url = currentServer.address + source.TranscodingUrl;
} else {
callback("Ce média ne peut pas être lu sur la Freebox.");
return;
}
console.log("Lecture : " + info.playMethod + " (" + (source.Container || "?") + ")");
callback(null, info);
});
}
// Suivi de lecture côté serveur (reprise, « vu »). event : "start", "progress", "stop".
function reportPlayback(event, info, positionMs, paused) {
var path = event === "start" ? "/Sessions/Playing"
: event === "stop" ? "/Sessions/Playing/Stopped" : "/Sessions/Playing/Progress";
_request("POST", path, {
ItemId: info.itemId, MediaSourceId: info.mediaSourceId, PlaySessionId: info.playSessionId,
PlayMethod: info.playMethod, PositionTicks: Math.floor((positionMs || 0) * 10000),
IsPaused: !!paused, CanSeek: true
}, function () {});
}
function _query(params) {
var parts = [];
for (var key in params) {
if (params[key] !== undefined && params[key] !== null && params[key] !== "")
parts.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
}
return parts.join("&");
}
function _toItems(list) {
var items = [];
for (var i = 0; i < (list || []).length; i++)
items.push(_toItem(list[i]));
return items;
}
function _toItem(i) {
var userData = i.UserData || {};
return {
id: i.Id,
name: i.Name || "",
type: i.Type || "",
collectionType: i.CollectionType || "",
isFolder: !!i.IsFolder,
year: i.ProductionYear || 0,
overview: i.Overview || "",
runtimeTicks: i.RunTimeTicks || 0,
rating: i.OfficialRating || "",
communityRating: i.CommunityRating || 0,
imageTag: (i.ImageTags && i.ImageTags.Primary) || "",
thumbTag: (i.ImageTags && i.ImageTags.Thumb) || "",
backdropTag: (i.BackdropImageTags && i.BackdropImageTags[0]) || "",
parentBackdropItemId: i.ParentBackdropItemId || "",
parentBackdropTag: (i.ParentBackdropImageTags && i.ParentBackdropImageTags[0]) || "",
seriesId: i.SeriesId || "",
seriesName: i.SeriesName || "",
seriesPrimaryTag: i.SeriesPrimaryImageTag || "",
seasonId: i.SeasonId || "",
// (pas de champ « index » : rôle réservé dans les ListModel)
indexNumber: i.IndexNumber || 0,
parentIndexNumber: i.ParentIndexNumber || 0,
childCount: i.ChildCount || 0,
positionTicks: userData.PlaybackPositionTicks || 0,
playedPercentage: userData.PlayedPercentage || 0,
played: !!userData.Played
};
}
// ------------------------------------------------------------------ Divers // ------------------------------------------------------------------ Divers
// Ignore les réponses en attente (appelé quand un écran est détruit). // Ignore les réponses en attente (appelé quand un écran est détruit).
@@ -253,20 +456,47 @@ QtObject {
return currentUser; return currentUser;
} }
// Essaie les adresses une par une ; renvoie la première qui répond comme un serveur Jellyfin. // Essaie toutes les adresses en parallèle et retient la première, dans l'ordre de
function _probeCandidates(candidates, index, callback) { // priorité, qui répond comme un serveur Jellyfin. Une adresse moins prioritaire (http)
if (index >= candidates.length) { // n'est retenue qu'une fois les plus prioritaires (https) réellement en échec : un
// premier échange TLS lent (chargement des certificats, CPU de la box) ne doit pas
// faire basculer sur http.
function _probeCandidates(candidates, callback) {
var results = [];
var settled = false;
function settle() {
if (settled)
return;
for (var i = 0; i < candidates.length; i++) {
if (results[i] === undefined)
return; // une adresse plus prioritaire n'a pas encore répondu
if (results[i]) {
settled = true;
callback(null, results[i]);
return;
}
}
settled = true;
callback("Aucun serveur Jellyfin trouvé à cette adresse.");
}
if (candidates.length === 0) {
callback("Aucun serveur Jellyfin trouvé à cette adresse."); callback("Aucun serveur Jellyfin trouvé à cette adresse.");
return; return;
} }
var address = candidates[index]; for (var i = 0; i < candidates.length; i++) {
(function (index, address) {
_request("GET", "/System/Info/Public", null, function (err, info) { _request("GET", "/System/Info/Public", null, function (err, info) {
if (!err && info && info.Id) { results[index] = !err && info && info.Id
callback(null, { name: info.ServerName || _hostOf(address), address: address, id: info.Id }); ? { name: info.ServerName || _hostOf(address), address: address, id: info.Id }
return; : null;
if (!results[index])
console.log("Serveur : " + address + " ne répond pas (" + (err ? err.kind + " " + err.status : "réponse inattendue") + ")");
settle();
}, { baseUrl: address, timeout: 10000 });
})(i, candidates[i]);
} }
_probeCandidates(candidates, index + 1, callback);
}, { baseUrl: address, timeout: 5000 });
} }
function _describe(err) { function _describe(err) {
View File
File renamed without changes.
File renamed without changes.
+3 -1
View File
@@ -17,9 +17,11 @@ Application {
Row { Row {
anchors.fill: parent anchors.fill: parent
// Masqué sur les écrans du catalogue (Page.fullscreen).
Logo { Logo {
id: logo id: logo
width: parent.width / 3 visible: !navigator.fullscreen
width: visible ? parent.width / 3 : 0
height: parent.height height: parent.height
} }
+77
View File
@@ -0,0 +1,77 @@
.pragma library
// Mise en forme des durées et des libellés de médias.
var TICKS_PER_MS = 10000; // Jellyfin compte en « ticks » de 100 ns
function ticksToMs(ticks) {
return Math.floor((ticks || 0) / TICKS_PER_MS);
}
function msToTicks(ms) {
return Math.floor((ms || 0) * TICKS_PER_MS);
}
// « 1 h 34 min », « 52 min »
function runtime(ticks) {
var minutes = Math.round(ticksToMs(ticks) / 60000);
if (minutes <= 0)
return "";
if (minutes < 60)
return minutes + " min";
var m = minutes % 60;
return Math.floor(minutes / 60) + " h" + (m > 0 ? " " + (m < 10 ? "0" : "") + m + " min" : "");
}
// « 1:02:03 », « 4:05 »
function clock(ms) {
var total = Math.max(0, Math.floor((ms || 0) / 1000));
var h = Math.floor(total / 3600);
var m = Math.floor((total % 3600) / 60);
var s = total % 60;
var mm = h > 0 && m < 10 ? "0" + m : String(m);
return (h > 0 ? h + ":" : "") + mm + ":" + (s < 10 ? "0" : "") + s;
}
// « S1 · É3 » pour un épisode
function episodeCode(item) {
if (!item || item.type !== "Episode")
return "";
return "S" + (item.parentIndexNumber || 0) + " · É" + (item.indexNumber || 0);
}
// Libellés des cartes du catalogue.
function cardTitle(item) {
return item.type === "Episode" && item.seriesName ? item.seriesName : item.name;
}
function cardSubtitle(item) {
if (item.type === "Episode")
return episodeCode(item) + " – " + item.name;
if (item.type === "Series" && item.childCount)
return item.childCount + " saison" + (item.childCount > 1 ? "s" : "");
return item.year ? String(item.year) : "";
}
// Avancement 0..1 (pour la barre de progression des cartes).
function progress(item) {
if (item.playedPercentage)
return item.playedPercentage / 100;
return item.runtimeTicks ? item.positionTicks / item.runtimeTicks : 0;
}
// Ligne d'informations : « 1997 · 1 h 34 min · Tous publics »
function infoLine(item) {
var parts = [];
if (item.type === "Episode")
parts.push(episodeCode(item));
if (item.year)
parts.push(String(item.year));
if (item.runtimeTicks)
parts.push(runtime(item.runtimeTicks));
if (item.rating)
parts.push(item.rating);
if (item.communityRating)
parts.push(item.communityRating.toFixed(1).replace(".", ",") + "/10");
return parts.join(" · ");
}
File renamed without changes.
@@ -31,6 +31,13 @@ QtObject {
readonly property int fontTitle: 32 readonly property int fontTitle: 32
readonly property int fontCode: 56 readonly property int fontCode: 56
// Cartes du catalogue (affiche 2:3, vignette 16:9)
readonly property int posterWidth: 150
readonly property int posterHeight: 225
readonly property int thumbWidth: 267
readonly property int thumbHeight: 150
readonly property int cardTextHeight: 52
// Contrôles // Contrôles
readonly property int controlHeight: 48 readonly property int controlHeight: 48
readonly property int radius: 6 readonly property int radius: 6
View File
File renamed without changes.
+123
View File
@@ -0,0 +1,123 @@
import QtQuick 2.5
import "../Components"
import "../Shared"
import "../Shared/Format.js" as Format
// Fiche d'un film, d'un épisode ou d'une série (saisons).
Page {
id: page
property string itemId: ""
property var item: null
property var seasons: []
property string error: ""
readonly property bool isSeries: item !== null && item.type === "Series"
readonly property real resumeMs: item ? Format.ticksToMs(item.positionTicks) : 0
fullscreen: true
title: item ? item.name : ""
subtitle: item ? (item.type === "Episode" && item.seriesName ? item.seriesName + " · " : "")
+ Format.infoLine(item) : ""
backdrop: item && page.session ? page.session.backdropUrl(item, 720) : ""
initialFocus: playButton
function play(startMs) {
var label = item.type === "Episode"
? item.seriesName + " · " + Format.episodeCode(item) + " – " + item.name : item.name;
page.navigator.push("Player", { itemId: item.id, title: label, startMs: startMs });
}
Component.onCompleted: {
page.session.loadItem(itemId, function (err, loaded) {
if (err) {
page.error = err;
return;
}
page.item = loaded;
if (loaded.type === "Series") {
page.session.loadSeasons(loaded.id, function (e, list) {
page.seasons = list;
seasonsRow.forceActiveFocus();
});
} else {
playButton.forceActiveFocus();
}
});
}
Component.onDestruction: if (page.session) page.session.cancel()
Rectangle {
id: poster
width: 200
height: 300
radius: Theme.radius
color: Theme.surface
Image {
anchors.fill: parent
// Épisode : affiche de la série (l'image de l'épisode est en 16:9).
source: !page.item || !page.session ? ""
: page.item.type === "Episode" && page.item.seriesPrimaryTag
? page.session.imageUrl(page.item.seriesId, "Primary", page.item.seriesPrimaryTag, 450)
: page.session.posterUrl(page.item, 450)
fillMode: Image.PreserveAspectCrop
asynchronous: true
sourceSize.height: 300
}
}
Column {
anchors {
left: poster.right
leftMargin: Theme.spacingXL
right: parent.right
top: parent.top
}
spacing: Theme.spacingL
Text {
width: parent.width
visible: text !== ""
text: page.error !== "" ? page.error : page.item ? page.item.overview : "Chargement…"
color: page.error !== "" ? Theme.error : Theme.text
font.pixelSize: Theme.fontBody
wrapMode: Text.WordWrap
maximumLineCount: page.isSeries ? 4 : 8
elide: Text.ElideRight
lineHeight: 1.15
}
Row {
spacing: Theme.spacingM
visible: page.item !== null && !page.isSeries
FocusButton {
id: playButton
primary: true
text: page.resumeMs > 0 ? "Reprendre à " + Format.clock(page.resumeMs) : "Lire"
KeyNavigation.right: restartButton.visible ? restartButton : null
onClicked: page.play(page.resumeMs)
}
FocusButton {
id: restartButton
visible: page.resumeMs > 0
text: "Lire depuis le début"
KeyNavigation.left: playButton
onClicked: page.play(0)
}
}
MediaRow {
id: seasonsRow
width: parent.width
visible: page.seasons.length > 0
title: "Saisons"
items: page.seasons
session: page.session
onActivated: page.navigator.openItem(item)
}
}
}
+144
View File
@@ -0,0 +1,144 @@
import QtQuick 2.5
import "../Components"
import "../Shared"
import "../Shared/Remote.js" as Remote
// Accueil : rangées « Reprendre », « Mes médias » et derniers ajouts de chaque bibliothèque.
// Toutes les rangées sont chargées avant affichage, pour ne pas déplacer le focus en cours de route.
Page {
id: page
property var rows: []
property bool loading: true
property string error: ""
fullscreen: true
title: page.session && page.session.currentUser ? "Bonjour " + page.session.currentUser.name : "Accueil"
subtitle: page.session && page.session.currentServer ? page.session.currentServer.name : ""
initialFocus: switchUserButton
// La pile a été réinitialisée à la connexion : on reconstruit Serveurs > Utilisateurs.
function goBack() {
page.navigator.reset("ServerSelect");
page.navigator.push("UserSelect");
}
function load() {
page.session.loadLibraries(function (err, libraries) {
if (err) {
page.error = err;
page.loading = false;
return;
}
var resume = [];
var latest = [];
var pending = 1 + libraries.length;
function done() {
if (--pending === 0)
page.build(libraries, resume, latest);
}
page.session.loadResume(function (e, items) {
resume = items;
done();
});
for (var i = 0; i < libraries.length; i++) {
(function (index) {
page.session.loadLatest(libraries[index].id, function (e, items) {
latest[index] = items;
done();
});
})(i);
}
});
}
function build(libraries, resume, latest) {
var list = [];
if (resume.length > 0)
list.push({ title: "Reprendre", items: resume, landscape: true });
if (libraries.length > 0)
list.push({ title: "Mes médias", items: libraries, landscape: true });
for (var i = 0; i < libraries.length; i++) {
if (latest[i] && latest[i].length > 0)
list.push({ title: "Ajouts récents · " + libraries[i].name, items: latest[i], landscape: false });
}
rows = list;
loading = false;
if (list.length > 0)
rowsList.forceActiveFocus();
}
Component.onCompleted: load()
Component.onDestruction: if (page.session) page.session.cancel()
// Retour : choix de l'utilisateur (sinon, à la racine de la pile, l'app se fermerait).
Keys.onPressed: {
if (Remote.isBack(event.key)) {
event.accepted = true;
page.goBack();
}
}
Row {
id: actions
spacing: Theme.spacingM
FocusButton {
id: switchUserButton
text: "Changer d'utilisateur"
KeyNavigation.right: logoutButton
KeyNavigation.down: rowsList
onClicked: page.goBack()
}
FocusButton {
id: logoutButton
text: "Se déconnecter"
KeyNavigation.left: switchUserButton
KeyNavigation.down: rowsList
onClicked: {
page.session.logout();
page.goBack();
}
}
}
ListView {
id: rowsList
anchors {
top: actions.bottom
topMargin: Theme.spacingL
left: parent.left
right: parent.right
bottom: parent.bottom
}
clip: true
spacing: Theme.spacingS
model: page.rows
delegate: MediaRow {
width: rowsList.width
title: modelData.title
items: modelData.items
landscape: modelData.landscape
session: page.session
onActivated: page.navigator.openItem(item)
}
// La rangée courante reste en haut de la zone visible.
onCurrentIndexChanged: positionViewAtIndex(currentIndex, ListView.Beginning)
KeyNavigation.priority: KeyNavigation.AfterItem
KeyNavigation.up: switchUserButton
}
Text {
anchors.centerIn: rowsList
visible: text !== ""
text: page.loading ? "Chargement…"
: page.error !== "" ? page.error
: page.rows.length === 0 ? "Aucun média disponible pour ce compte." : ""
color: page.error !== "" ? Theme.error : Theme.textMuted
font.pixelSize: Theme.fontBody
}
}
+91
View File
@@ -0,0 +1,91 @@
import QtQuick 2.5
import "../Components"
import "../Shared"
import "../Shared/Remote.js" as Remote
import "../Shared/Format.js" as Format
// Contenu d'une bibliothèque en grille d'affiches, chargé par pages à mesure qu'on descend.
Page {
id: page
property var library: null // { id, name, collectionType }
property int total: 0
property bool loading: false
property string error: ""
readonly property int pageSize: 60
fullscreen: true
title: library ? library.name : ""
subtitle: total > 0 ? total + " élément" + (total > 1 ? "s" : "") : ""
initialFocus: grid
function loadMore() {
if (loading || (total > 0 && itemsModel.count >= total))
return;
loading = true;
page.session.loadLibraryItems(library, itemsModel.count, pageSize, function (err, items, count) {
page.loading = false;
if (err) {
page.error = err;
return;
}
page.total = count;
for (var i = 0; i < items.length; i++)
itemsModel.append(items[i]);
});
}
Component.onCompleted: loadMore()
Component.onDestruction: if (page.session) page.session.cancel()
ListModel {
id: itemsModel
}
GridView {
id: grid
anchors.fill: parent
clip: true
focus: true
// Marges pour la carte agrandie (scale).
leftMargin: 8
topMargin: 8
cellWidth: Theme.posterWidth + Theme.spacingL
cellHeight: Theme.posterHeight + Theme.cardTextHeight + Theme.spacingL
model: itemsModel
delegate: MediaCard {
width: Theme.posterWidth
title: model.name
subtitle: Format.cardSubtitle(model)
imageSource: page.session ? page.session.posterUrl(model) : ""
progress: Format.progress(model)
played: model.played
highlighted: GridView.isCurrentItem && grid.activeFocus
onClicked: {
grid.currentIndex = index;
page.navigator.openItem(itemsModel.get(index));
}
}
// Page suivante quand on approche de la fin.
onCurrentIndexChanged: if (currentIndex >= count - 14) page.loadMore()
Keys.onPressed: {
if (Remote.isAccept(event.key) && currentIndex >= 0) {
event.accepted = true;
page.navigator.openItem(itemsModel.get(currentIndex));
}
}
}
Text {
anchors.centerIn: parent
visible: text !== ""
text: page.error !== "" ? page.error
: itemsModel.count === 0 ? (page.loading ? "Chargement…" : "Cette bibliothèque est vide.") : ""
color: page.error !== "" ? Theme.error : Theme.textMuted
font.pixelSize: Theme.fontBody
}
}
File renamed without changes.
+244
View File
@@ -0,0 +1,244 @@
import QtQuick 2.5
import "../Components"
import "../Shared"
import "../Shared/Remote.js" as Remote
import "../Shared/Format.js" as Format
// Lecteur plein écran.
// Télécommande : OK = lecture/pause, Gauche/Droite = -10 s/+30 s, Haut/Bas = afficher les
// informations, Retour = quitter (géré par le Navigator).
// La progression est signalée au serveur (reprise, « vu ») au démarrage, toutes les 10 s et à l'arrêt.
FocusScope {
id: player
// Injectés par le Navigator
property var navigator: null
property var session: null
property Item initialFocus: null
property bool fullscreen: true
// Paramètres de push("Player", …)
property string itemId: ""
property string title: ""
property real startMs: 0
property var info: null // résultat de Session.preparePlayback()
property bool started: false // lecture effectivement démarrée et signalée
property bool resumed: false
// Reprise atteinte (ou lecture depuis le début) : avant ça, on ne signale rien, pour
// ne pas écraser le point de reprise si le déplacement initial échoue.
property bool resumeReached: startMs <= 0
property bool finished: false
property string error: ""
function showOsd() {
osd.shown = true;
osdTimer.restart();
}
function seekBy(deltaMs) {
if (video.duration <= 0)
return;
video.seek(video.position + deltaMs);
showOsd();
}
// Rien n'est signalé tant que la lecture n'a pas réellement démarré : un arrêt
// signalé à la position 0 effacerait le point de reprise sur le serveur.
function report(event) {
if (!player.info || !player.started)
return;
if (event !== "start" && video.position <= 0)
return;
player.session.reportPlayback(event, player.info, video.position, video.playerState === "paused");
}
// Signale le démarrage une fois la lecture lancée ET la position de reprise atteinte.
function maybeReportStart() {
if (player.started || !player.info || video.playerState !== "playing" || !player.resumeReached)
return;
player.started = true;
player.report("start");
}
function finish() {
if (finished)
return;
finished = true;
report("stop");
player.navigator.pop();
}
Component.onCompleted: {
showOsd();
player.session.preparePlayback(itemId, function (err, playback) {
if (err) {
player.error = err;
return;
}
player.info = playback;
video.source = playback.url;
});
}
// Retour (le Navigator dépile) ou fin : on signale l'arrêt au serveur.
Component.onDestruction: {
if (!finished) {
finished = true;
report("stop");
}
}
Keys.onPressed: {
var key = event.key;
if (Remote.isAccept(key) || key === Qt.Key_Space || key === Qt.Key_MediaTogglePlayPause
|| key === Qt.Key_MediaPlay || key === Qt.Key_MediaPause) {
video.togglePause();
showOsd();
} else if (key === Qt.Key_Left || key === Qt.Key_AudioRewind) {
seekBy(-10000);
} else if (key === Qt.Key_Right || key === Qt.Key_AudioForward) {
seekBy(30000);
} else if (key === Qt.Key_Up || key === Qt.Key_Down) {
showOsd();
} else {
return;
}
event.accepted = true;
}
Rectangle {
anchors.fill: parent
color: "black"
}
VideoSurface {
id: video
anchors.fill: parent
onPlayerStateChanged: {
player.maybeReportStart();
if (playerState === "paused")
player.showOsd();
}
// Reprise : déplacement une fois la durée connue.
onDurationChanged: {
if (!player.resumed && player.startMs > 0 && duration > 0) {
player.resumed = true;
seek(player.startMs);
}
}
onPositionChanged: {
if (!player.resumeReached && position >= player.startMs - 15000) {
player.resumeReached = true;
player.maybeReportStart();
}
}
onEnded: player.finish()
}
Timer {
interval: 10000
repeat: true
running: player.started && !player.finished
onTriggered: player.report("progress")
}
// Messages au centre : chargement / erreur.
Text {
anchors.centerIn: parent
width: parent.width * 0.7
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.WordWrap
visible: text !== ""
text: player.error !== "" ? player.error + "\nAppuyez sur Retour pour quitter."
: video.playerState === "error" ? video.errorString + "\nAppuyez sur Retour pour quitter."
: video.playerState === "loading" || video.playerState === "idle" ? "Chargement…" : ""
color: player.error !== "" || video.playerState === "error" ? Theme.error : Theme.text
font.pixelSize: Theme.fontBody
style: Text.Outline
styleColor: "black"
}
// Informations de lecture (masquées après 4 s, sauf en pause).
Item {
id: osd
property bool shown: true
anchors.fill: parent
opacity: shown || video.playerState === "paused" ? 1 : 0
Behavior on opacity { NumberAnimation { duration: 200 } }
Rectangle {
anchors { left: parent.left; right: parent.right; bottom: parent.bottom }
height: 170
gradient: Gradient {
GradientStop { position: 0; color: "transparent" }
GradientStop { position: 1; color: "#E0000000" }
}
}
Column {
anchors {
left: parent.left
right: parent.right
bottom: parent.bottom
margins: Theme.pageMargin
}
spacing: Theme.spacingS
Text {
width: parent.width
text: player.title
elide: Text.ElideRight
color: Theme.text
font.pixelSize: Theme.fontTitle - 6
font.bold: true
}
Rectangle {
width: parent.width
height: 6
radius: 3
color: "#55FFFFFF"
Rectangle {
width: video.duration > 0 ? parent.width * Math.min(1, video.position / video.duration) : 0
height: parent.height
radius: 3
color: Theme.accent
}
}
Item {
width: parent.width
height: stateText.implicitHeight
Text {
id: stateText
text: video.playerState === "paused" ? "Pause"
: video.playerState === "playing" ? "Lecture"
: video.playerState === "loading" ? "Chargement…" : ""
color: Theme.text
font.pixelSize: Theme.fontSmall
font.bold: true
}
Text {
anchors.right: parent.right
text: Format.clock(video.position) + " / " + Format.clock(video.duration)
color: Theme.text
font.pixelSize: Theme.fontSmall
}
}
}
}
Timer {
id: osdTimer
interval: 4000
onTriggered: osd.shown = false
}
}
+134
View File
@@ -0,0 +1,134 @@
import QtQuick 2.5
import "../Components"
import "../Shared"
import "../Shared/Remote.js" as Remote
import "../Shared/Format.js" as Format
// Épisodes d'une saison ; OK ouvre la fiche de l'épisode.
Page {
id: page
property string seriesId: ""
property string seasonId: ""
property string seasonName: ""
property string seriesName: ""
property var episodes: []
property bool loading: true
property string error: ""
fullscreen: true
title: seriesName
subtitle: seasonName
initialFocus: list
Component.onCompleted: {
page.session.loadEpisodes(seriesId, seasonId, function (err, items) {
page.loading = false;
if (err) {
page.error = err;
return;
}
page.episodes = items;
list.forceActiveFocus();
});
}
Component.onDestruction: if (page.session) page.session.cancel()
ListView {
id: list
anchors.fill: parent
clip: true
focus: true
spacing: Theme.spacingS
model: page.episodes
delegate: Rectangle {
id: row
readonly property bool highlighted: ListView.isCurrentItem && list.activeFocus
width: list.width
height: 150
radius: Theme.radius
color: highlighted ? Theme.focusBackground : "transparent"
MediaCard {
id: thumb
anchors { left: parent.left; leftMargin: Theme.spacingS; verticalCenter: parent.verticalCenter }
width: 240
height: 135
imageHeight: 135
showText: false
imageSource: page.session ? page.session.thumbUrl(modelData) : ""
progress: Format.progress(modelData)
played: modelData.played
title: modelData.name
}
Column {
anchors {
left: thumb.right
leftMargin: Theme.spacingL
right: parent.right
rightMargin: Theme.spacingM
verticalCenter: parent.verticalCenter
}
spacing: 4
Text {
width: parent.width
text: modelData.name
elide: Text.ElideRight
color: row.highlighted ? Theme.textOnFocus : Theme.text
font.pixelSize: Theme.fontBody
font.bold: true
}
Text {
width: parent.width
visible: text !== ""
text: "Épisode " + modelData.indexNumber
+ (modelData.runtimeTicks ? " · " + Format.runtime(modelData.runtimeTicks) : "")
color: row.highlighted ? Theme.textOnFocusMuted : Theme.textMuted
font.pixelSize: Theme.fontSmall
}
Text {
width: parent.width
text: modelData.overview
wrapMode: Text.WordWrap
maximumLineCount: 3
elide: Text.ElideRight
color: row.highlighted ? Theme.textOnFocusMuted : Theme.textMuted
font.pixelSize: Theme.fontSmall
}
}
MouseArea {
anchors.fill: parent
onClicked: {
list.currentIndex = index;
page.navigator.openItem(modelData);
}
}
}
Keys.onPressed: {
if (Remote.isAccept(event.key) && currentIndex >= 0) {
event.accepted = true;
page.navigator.openItem(page.episodes[currentIndex]);
}
}
}
Text {
anchors.centerIn: parent
visible: text !== ""
text: page.loading ? "Chargement…"
: page.error !== "" ? page.error
: page.episodes.length === 0 ? "Aucun épisode." : ""
color: page.error !== "" ? Theme.error : Theme.textMuted
font.pixelSize: Theme.fontBody
}
}
File renamed without changes.
File renamed without changes.
@@ -5,7 +5,7 @@ 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, // 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). // plus les comptes de test éventuels (freebox-jellyfin deploy --user).
Page { Page {
id: page id: page
View File
File renamed without changes.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

+1
View File
@@ -1,6 +1,7 @@
{ {
"name": "Jellyfin", "name": "Jellyfin",
"identifier": "com.stilobique.jellyfin", "identifier": "com.stilobique.jellyfin",
"version": "0.1.1",
"description": "Jellyfin for Freebox", "description": "Jellyfin for Freebox",
"icon": "icon.png", "icon": "icon.png",
"capabilities": { "capabilities": {
+17
View File
@@ -0,0 +1,17 @@
[project]
name = "freebox-jellyfin"
version = "0.1.0"
description = "Outils de développement du client Jellyfin pour Freebox Player (aperçu, vérification, paquet FreeStore, déploiement)"
readme = "readme.md"
authors = [
{ name = "stilobique", email = "contact@aurelien-vaillant.net" }
]
requires-python = ">=3.14"
dependencies = []
[project.scripts]
freebox-jellyfin = "freebox_jellyfin:main"
[build-system]
requires = ["uv_build>=0.12.9,<0.13.0"]
build-backend = "uv_build"
+53 -9
View File
@@ -7,32 +7,76 @@
Cette application permet d'utiliser jellyfin sur la freebox. Cette application permet d'utiliser jellyfin sur la freebox.
# Configurer un environement de travail L'application (QML envoyé au Player) est dans `app/` ; le reste du dépôt est l'outillage de développement.
# Configurer un environment de travail
[Documentation pour le SDK de la freebox](https://dev.freebox.fr/sdk/player.html). [Documentation pour le SDK de la freebox](https://dev.freebox.fr/sdk/player.html).
Pour Windows, [voir ce billet sur Github](https://github.com/fbx/freebox-qtcreator-plugin/issues/8). Pour Windows, [voir ce billet sur Github](https://github.com/fbx/freebox-qtcreator-plugin/issues/8).
Les outils (aperçu, vérification, paquet, déploiement) sont regroupés dans le module Python `freebox_jellyfin` (`src/`), géré avec [uv](https://docs.astral.sh/uv/) :
```bash
uv sync # crée .venv (Python 3.14) et installe la commande freebox-jellyfin
uv run freebox-jellyfin # liste les commandes
```
## Aperçu sur PC (Linux) ## Aperçu sur PC (Linux)
Sans Freebox, l'application tourne avec `qmlscene` (Qt 5) et la bibliothèque [libfbxqml](https://github.com/fbx/libfbxqml) : Sans Freebox, l'application tourne avec `qmlscene` (Qt 5) et la bibliothèque [libfbxqml](https://github.com/fbx/libfbxqml) :
```bash ```bash
sudo apt install qmlscene qml-module-qtmultimedia qtdeclarative5-dev-tools sudo apt install qmlscene qml-module-qtmultimedia qtdeclarative5-dev-tools qml-module-qttest
git clone https://github.com/fbx/libfbxqml.git ../libfbxqml git clone https://github.com/fbx/libfbxqml.git ../libfbxqml
tools/run-local.sh # fenêtre 1280x720 uv run freebox-jellyfin preview # fenêtre 1280x720
tools/run-local.sh --fullscreen # plein écran, comme sur la box uv run freebox-jellyfin preview --fullscreen # plein écran, comme sur la box
uv run freebox-jellyfin preview --fake-server # avec le faux serveur Jellyfin (127.0.0.1, port 8096)
uv run freebox-jellyfin check # chargement en HTTP comme le Player, échoue sur tout avertissement Qt
``` ```
## Tests
```bash
uv run freebox-jellyfin test # règles de la box, tests Python et QML
uv run freebox-jellyfin test --qml tst_session.qml # un seul fichier de tests (tests/qml/)
uv run freebox-jellyfin test Session::test_logout # une seule fonction
uv run freebox-jellyfin fake-server # faux serveur Jellyfin sur 127.0.0.1:8096
```
`test` vérifie d'abord les règles propres au Freebox Player que le PC ne signale pas (JavaScript ES5, QtQuick 2.5 au plus, `qmldir` complets, singletons), puis lance les tests QML (`tests/qml/`) contre un faux serveur Jellyfin : connexion, catalogue, lecture, Quick Connect, règles de reprise du lecteur et parcours complets à la télécommande.
`fake-server` lance ce même faux serveur pour travailler dans l'aperçu sans vrai serveur : ajouter le serveur `127.0.0.1`, port `8096`, puis se connecter avec `alice` / `secret` ou `bob` (sans mot de passe).
## Tester sur la Freebox ## Tester sur la Freebox
Activer le mode développeur du Player (menu Réglages, avec la télécommande), puis : Activer le mode développeur du Player (menu Réglages, avec la télécommande), puis :
```bash ```bash
tools/deploy.py # trouve le Player sur le réseau et lance l'app uv run freebox-jellyfin deploy # trouve le Player sur le réseau et lance l'app
tools/deploy.py --box 192.168.0.21 # ou en donnant son adresse uv run freebox-jellyfin deploy --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 uv run freebox-jellyfin deploy --server media.example.com # l'app ajoute ce serveur au démarrage
tools/deploy.py --server media.example.com --user alice:motdepasse --user bob uv run freebox-jellyfin deploy --server media.example.com --user alice:motdepasse bob
``` ```
En mode développement, la box n'enregistre aucune donnée de l'application. Pour éviter de tout ressaisir à chaque test : 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 ; - `--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. - `--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). La commande 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).
## Publier sur le FreeStore
```bash
uv run freebox-jellyfin package # crée dist/com.stilobique.jellyfin-<version>.tar.gz
```
Pour une nouvelle version, modifier `version` dans `app/manifest.json` **et** `clientVersion` dans `app/Core/Session.qml` (la commande refuse de créer le paquet si elles diffèrent).
La commande reproduit « Make FreeStore Package » du plugin QtCreator : elle vérifie `app/manifest.json` et la syntaxe QML/JS (`qmllint`), puis crée l'archive à téléverser sur la console [FreeFactory](http://factory.free.fr) (compte développeur requis, validation par Free avant publication).
## Intégration continue
Le workflow Gitea Actions `.gitea/workflows/ci.yml` :
- à chaque push / pull request : vérifie le manifest et la syntaxe QML/JS, charge l'application en HTTP comme le Player (`freebox-jellyfin check`) et publie le paquet en artefact ;
- sur un tag `vX.Y.Z` (égal à la version du manifest) : crée une release Gitea avec le paquet FreeStore en pièce jointe.
```bash
git tag v0.1.0 && git push origin v0.1.0
```
Le téléversement sur la console FreeFactory reste manuel.
+35
View File
@@ -0,0 +1,35 @@
"""Outils de développement du client Jellyfin pour Freebox Player.
freebox-jellyfin preview [--fullscreen] aperçu sur le PC (qmlscene + libfbxqml)
freebox-jellyfin check chargement en HTTP comme sur la box (CI)
freebox-jellyfin test [--qml FICHIER] règles de la box, tests Python et QML
freebox-jellyfin fake-server [--port N] faux serveur Jellyfin pour l'aperçu
freebox-jellyfin package paquet FreeStore dans dist/
freebox-jellyfin deploy [--box IP] … lancement sur un Player en mode développeur
"""
import sys
COMMANDS = ("preview", "check", "test", "fake-server", "package", "deploy")
def main(argv=None):
argv = sys.argv[1:] if argv is None else argv
if not argv or argv[0] not in COMMANDS:
print(__doc__.strip())
print("\nAide d'une commande : freebox-jellyfin <commande> --help")
return 0 if argv and argv[0] in ("-h", "--help") else 2
command, rest = argv[0], argv[1:]
# Imports à la demande : chaque commande ne charge que son module.
if command == "preview":
from .preview import main as run
elif command == "check":
from .check_load import main as run
elif command == "test":
from .test import main as run
elif command == "fake-server":
from .fake_server import main as run
elif command == "package":
from .package import main as run
else:
from .deploy import main as run
return run(rest)
+5
View File
@@ -0,0 +1,5 @@
import sys
from . import main
sys.exit(main())
+154
View File
@@ -0,0 +1,154 @@
"""Règles du Freebox Player que qmlscene (Qt 5.15) et qmllint ne signalent pas sur le PC.
- JavaScript ES5 seulement (Qt 5.5) : ni let/const, ni fonctions fléchées, ni gabarits `…`,
ni class, for…of ou opérateur « ... » ;
- QtQuick 2.5 au plus, pas de QtQuick.Controls, pas d'import "." ;
- chargement HTTP : chaque dossier importé a un qmldir qui liste tous ses types (et seulement
des fichiers existants), au plus un singleton par dossier, et aucun composant du dossier
d'un singleton ne l'utilise (« Cyclic dependency detected »).
Utilisé par `freebox-jellyfin test` et `freebox-jellyfin package`.
"""
import re
from pathlib import Path
ES5_RULES = [
(re.compile(r"\blet\s+[A-Za-z_$\[{]"), "« let » (ES6) : utiliser var"),
(re.compile(r"\bconst\s+[A-Za-z_$\[{]"), "« const » (ES6) : utiliser var"),
(re.compile(r"=>"), "fonction fléchée (ES6) : utiliser function"),
(re.compile(r"`"), "gabarit `…` (ES6) : concaténer des chaînes"),
(re.compile(r"\bclass\s+[A-Za-z_$]"), "class (ES6)"),
(re.compile(r"\bfor\s*\(\s*(?:var\s+)?[A-Za-z_$][\w$]*\s+of\b"), "for…of (ES6)"),
(re.compile(r"\.\.\.[A-Za-z_$\[{(]"), "opérateur « ... » (ES6)"),
]
QTQUICK_MAX = (2, 5)
IMPORT_RE = re.compile(r'^\s*import\s+(?:"([^"]+)"|([\w.]+)\s+(\d+)\.(\d+))', re.M)
def strip_code(text):
"""Remplace commentaires et contenu des chaînes par des espaces (lignes conservées).
Les littéraux d'expression régulière sont gardés tels quels : « // » n'y est pris pour un
commentaire que s'il n'est pas précédé d'une barre oblique inverse.
"""
out = []
i, n = 0, len(text)
while i < n:
c = text[i]
if c == "/" and i + 1 < n and text[i + 1] == "/" and (i == 0 or text[i - 1] != "\\"):
end = text.find("\n", i)
end = n if end < 0 else end
out.append(" " * (end - i))
i = end
elif c == "/" and i + 1 < n and text[i + 1] == "*":
end = text.find("*/", i + 2)
end = n if end < 0 else end + 2
out.append(re.sub(r"[^\n]", " ", text[i:end]))
i = end
elif c in "\"'":
j = i + 1
while j < n and text[j] != c and text[j] != "\n":
j += 2 if text[j] == "\\" else 1
out.append(c + " " * (min(j, n) - i - 1) + (c if j < n and text[j] == c else ""))
i = j + 1 if j < n and text[j] == c else j
else:
out.append(c)
i += 1
return "".join(out)
def check_es5(path, text):
problems = []
for number, line in enumerate(strip_code(text).splitlines(), 1):
for pattern, message in ES5_RULES:
if pattern.search(line):
problems.append("%s:%d: %s" % (path, number, message))
return problems
def check_imports(path, text):
problems = []
for match in IMPORT_RE.finditer(text): # une ligne commentée ne commence pas par « import »
line = text.count("\n", 0, match.start()) + 1
target, module = match.group(1), match.group(2)
if target is not None:
if target in (".", "./"):
problems.append("%s:%d: import \".\" interdit (cycle en chargement HTTP)" % (path, line))
continue
version = (int(match.group(3)), int(match.group(4)))
if module == "QtQuick" and version > QTQUICK_MAX:
problems.append("%s:%d: QtQuick %d.%d trop récent pour la box (2.5 au plus)"
% (path, line, version[0], version[1]))
if module.startswith("QtQuick.Controls"):
problems.append("%s:%d: QtQuick.Controls absent de la box" % (path, line))
return problems
def _qmldir_entries(qmldir):
"""[(type, singleton?, fichier)] d'un fichier qmldir."""
entries = []
for raw in qmldir.read_text(encoding="utf-8").splitlines():
parts = raw.split("#")[0].split()
if not parts or parts[0] in ("module", "plugin", "classname", "typeinfo", "depends", "designersupported"):
continue
singleton = parts[0] == "singleton"
if singleton:
parts = parts[1:]
if len(parts) >= 3:
entries.append((parts[0], singleton, parts[-1]))
return entries
def check_directories(app_dir):
"""Dossiers importés par chemin : qmldir complet, singletons sans cycle."""
app_dir = Path(app_dir)
problems = []
imported = set()
for qml in app_dir.rglob("*.qml"):
for match in IMPORT_RE.finditer(qml.read_text(encoding="utf-8")):
target = match.group(1)
if target and not target.endswith(".js") and target not in (".", "./"):
imported.add((qml.parent / target).resolve())
for folder in sorted(imported):
rel = folder.relative_to(app_dir.resolve()) if folder.is_relative_to(app_dir.resolve()) else folder
qmldir = folder / "qmldir"
if not qmldir.is_file():
problems.append("%s/: importé mais sans qmldir (« X is not a type » sur la box)" % rel)
continue
entries = _qmldir_entries(qmldir)
listed = {file for _, _, file in entries}
for name, _, file in entries:
if not (folder / file).is_file():
problems.append("%s/qmldir: %s → %s introuvable" % (rel, name, file))
for qml in sorted(folder.glob("*.qml")):
if qml.name[0].isupper() and qml.name not in listed:
problems.append("%s/qmldir: %s absent (« %s is not a type » sur la box)"
% (rel, qml.name, qml.stem))
singletons = [(name, file) for name, singleton, file in entries if singleton]
if len(singletons) > 1:
problems.append("%s/: plusieurs singletons (%s) : « Cyclic dependency detected » sur la box"
% (rel, ", ".join(n for n, _ in singletons)))
for name, file in singletons:
uses = re.compile(r"\b%s\." % re.escape(name))
for qml in sorted(folder.glob("*.qml")):
if qml.name != file and uses.search(strip_code(qml.read_text(encoding="utf-8"))):
problems.append("%s/%s: utilise le singleton %s de son propre dossier "
"(« Cyclic dependency detected » sur la box)" % (rel, qml.name, name))
return problems
def check_app(app_dir):
"""Toutes les règles sur le dossier de l'application ; renvoie la liste des problèmes."""
app_dir = Path(app_dir)
problems = []
for path in sorted(list(app_dir.rglob("*.qml")) + list(app_dir.rglob("*.js"))):
if any(part.startswith(".") for part in path.relative_to(app_dir).parts):
continue
rel = path.relative_to(app_dir)
text = path.read_text(encoding="utf-8")
problems += check_es5(rel, text)
if path.suffix == ".qml":
problems += check_imports(rel, text)
problems += check_directories(app_dir)
return problems
+75
View File
@@ -0,0 +1,75 @@
"""Charge l'application comme le Freebox Player (fichiers servis en HTTP) et échoue si Qt
signale une erreur ou un avertissement venant de l'app.
En HTTP, Qt ne peut pas lister les dossiers : c'est là qu'apparaissent les « X is not a type »
(qmldir manquant) ou « Cyclic dependency » (singletons), invisibles en lançant depuis le disque.
"""
import argparse
import functools
import http.server
import os
import subprocess
import sys
import tempfile
import threading
from .project import APP_DIR, libfbxqml, qmlscene
# Messages attendus hors de la box : Settings de libfbxqml (pas d'objet App sur PC).
EXPECTED = ("/libfbxqml/", "qml: Setting", "qml: Getting settings failed")
class _Quiet(http.server.SimpleHTTPRequestHandler):
def log_message(self, *args):
pass
class _Server(http.server.ThreadingHTTPServer):
def handle_error(self, request, client_address):
pass # qmlscene qui s'arrête en plein téléchargement (BrokenPipe) : sans intérêt
def problems(output):
"""Lignes de sortie de qmlscene qui ne sont pas attendues."""
return [line for line in output.splitlines()
if line.strip() and not any(marker in line for marker in EXPECTED)]
def run(duration):
lib, scene = libfbxqml(), qmlscene()
server = _Server(
("127.0.0.1", 0), functools.partial(_Quiet, directory=str(APP_DIR)))
threading.Thread(target=server.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/Jellyfin.qml" % server.server_address[1]
print("Chargement de %s pendant %g s…" % (url, duration), flush=True)
try:
with tempfile.TemporaryDirectory() as runtime:
os.chmod(runtime, 0o700)
# Rendu logiciel : la CI (conteneur) n'a pas d'OpenGL.
env = dict(os.environ, XDG_RUNTIME_DIR=runtime,
QT_QPA_PLATFORM="offscreen", QT_QUICK_BACKEND="software")
try:
result = subprocess.run([scene, "-I", str(lib), url], env=env, timeout=duration,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
output = result.stdout
except subprocess.TimeoutExpired as expired: # cas normal : l'app reste ouverte
output = expired.stdout or ""
if isinstance(output, bytes):
output = output.decode(errors="replace")
finally:
server.shutdown()
unexpected = problems(output)
if unexpected:
print("Échec : messages inattendus au chargement :", file=sys.stderr)
print("\n".join(unexpected), file=sys.stderr)
return 1
print("OK : chargement sans erreur.")
return 0
def main(argv=None):
parser = argparse.ArgumentParser(prog="freebox-jellyfin check", description=__doc__.splitlines()[0])
parser.add_argument("--duration", type=float, default=6, help="durée du chargement en secondes (défaut : 6)")
args = parser.parse_args(argv)
return run(args.duration)
@@ -1,13 +1,12 @@
#!/usr/bin/env python3
"""Lance l'application sur un Freebox Player en mode développeur. """Lance l'application sur un Freebox Player en mode développeur.
Reproduit le « Run » du plugin QtCreator Freebox (github.com/fbx/freebox-qtcreator-plugin) : 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 ; 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) ; 2. sert le dossier app/ 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://<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] [--server media.example.com] [--user nom[:mdp]] [--entry main] [--verbose] [--log deploy.log] Usage : freebox-jellyfin deploy [--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). --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). --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.
@@ -24,7 +23,9 @@ import threading
import time import time
import urllib.request import urllib.request
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) from .project import APP_DIR, REPO_DIR
APP_DIR, REPO_DIR = str(APP_DIR), str(REPO_DIR)
SSDP_ADDR = ("239.255.255.250", 1900) SSDP_ADDR = ("239.255.255.250", 1900)
SSDP_TYPE = "fbx:devel" SSDP_TYPE = "fbx:devel"
@@ -86,7 +87,7 @@ class QuietHandler(http.server.SimpleHTTPRequestHandler):
def serve_project(bind_ip, verbose, dev_config=None): def serve_project(bind_ip, verbose, dev_config=None):
QuietHandler.verbose = verbose QuietHandler.verbose = verbose
QuietHandler.dev_config = dev_config QuietHandler.dev_config = dev_config
handler = functools.partial(QuietHandler, directory=PROJECT_DIR) handler = functools.partial(QuietHandler, directory=APP_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()
return server return server
@@ -146,8 +147,8 @@ class Tee:
self.log.flush() self.log.flush()
def main(): def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser = argparse.ArgumentParser(prog="freebox-jellyfin deploy", description=__doc__.splitlines()[0])
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")
@@ -157,13 +158,13 @@ def main():
parser.add_argument("--user", action="extend", nargs="+", default=[], metavar="NOM[:MOT_DE_PASSE]", 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, " 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é)") "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(REPO_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(argv)
if args.log: if args.log:
log = open(args.log, "w", encoding="utf-8") log = open(args.log, "w", encoding="utf-8")
log.write("# deploy.py %s\n" % time.strftime("%Y-%m-%d %H:%M:%S")) log.write("# freebox-jellyfin deploy %s\n" % time.strftime("%Y-%m-%d %H:%M:%S"))
sys.stdout = Tee(sys.stdout, log) sys.stdout = Tee(sys.stdout, log)
sys.stderr = Tee(sys.stderr, log) sys.stderr = Tee(sys.stderr, log)
@@ -188,7 +189,7 @@ def main():
server = serve_project(me, args.verbose, dev_config) 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("Application servie sur %s" % manifest_url)
if args.server: if args.server:
print("Serveurs de test proposés à l'app : %s" % ", ".join(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 if users: # les mots de passe ne sont jamais affichés
@@ -211,6 +212,3 @@ def main():
finally: finally:
server.shutdown() server.shutdown()
if __name__ == "__main__":
main()
+347
View File
@@ -0,0 +1,347 @@
"""Faux serveur Jellyfin (HTTP, données fixes) pour les tests QML et l'aperçu sur PC.
Données : comptes « alice » (mot de passe « secret ») et « bob » (sans mot de passe),
bibliothèques Films (25 films, dont « Film direct », « Film transcodé », « Film illisible »)
et Séries (« Série test », 2 saisons). Quick Connect activé (code 123456).
Points d'entrée de contrôle, réservés aux tests (jamais enregistrés dans /__requests) :
POST /__reset état initial, journal des requêtes vidé
GET /__requests requêtes reçues : [{method, path, query, auth, body}]
POST /__mock {path, method?, status?, body?, raw?, delay?} : réponse imposée
POST /__quickconnect/authorize autorise la demande Quick Connect en cours
freebox-jellyfin fake-server [--port 8096]
"""
import argparse
import http.server
import json
import re
import struct
import threading
import time
import urllib.parse
import zlib
SERVER_ID = "fakeserver0000000000000000000001"
SERVER_NAME = "Serveur de test"
USERS = [
{"Name": "alice", "Id": "user-alice", "HasPassword": True, "password": "secret"},
{"Name": "bob", "Id": "user-bob", "HasPassword": False, "password": ""},
]
QUICK_CONNECT = {"Secret": "qc-secret", "Code": "123456"}
TICKS_PER_MS = 10000
def _png(width=2, height=3, rgb=(0x55, 0x5a, 0x66)):
"""PNG uni (réponse à toutes les demandes d'image)."""
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
rows = b"".join(b"\x00" + bytes(rgb) * width for _ in range(height))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b""))
PNG = _png()
def _item(item_id, name, item_type, **extra):
item = {"Id": item_id, "Name": name, "Type": item_type, "ImageTags": {"Primary": "tag-" + item_id},
"BackdropImageTags": [], "UserData": {"PlaybackPositionTicks": 0, "Played": False}}
item.update(extra)
return item
def _catalog():
libraries = [
_item("lib-movies", "Films", "CollectionFolder", CollectionType="movies", IsFolder=True),
_item("lib-shows", "Séries", "CollectionFolder", CollectionType="tvshows", IsFolder=True),
]
two_hours = 2 * 3600 * 1000 * TICKS_PER_MS
movies = [
_item("movie-direct", "Film direct", "Movie", ProductionYear=1997, RunTimeTicks=two_hours,
OfficialRating="Tous publics", CommunityRating=7.5, Overview="Lu tel quel (H.264).",
BackdropImageTags=["bd-movie-direct"],
UserData={"PlaybackPositionTicks": 10 * 60 * 1000 * TICKS_PER_MS, "PlayedPercentage": 8.3,
"Played": False}),
_item("movie-transcode", "Film transcodé", "Movie", ProductionYear=2015, RunTimeTicks=two_hours),
_item("movie-broken", "Film illisible", "Movie", ProductionYear=2001, RunTimeTicks=two_hours),
]
movies += [_item("movie-%02d" % n, "Film %02d" % n, "Movie", ProductionYear=2000 + n, RunTimeTicks=two_hours)
for n in range(1, 23)]
for movie in movies:
movie["ParentId"] = "lib-movies"
series = _item("series-1", "Série test", "Series", ProductionYear=2020, ChildCount=2, ParentId="lib-shows")
seasons, episodes = [], []
for number, count in ((1, 2), (2, 1)):
season_id = "season-%d" % number
seasons.append(_item(season_id, "Saison %d" % number, "Season", IndexNumber=number,
SeriesId="series-1", SeriesName="Série test",
SeriesPrimaryImageTag="tag-series-1"))
for episode in range(1, count + 1):
episodes.append(_item(
"ep-%d-%d" % (number, episode), "Épisode %d" % episode, "Episode",
IndexNumber=episode, ParentIndexNumber=number, SeasonId=season_id, SeriesId="series-1",
SeriesName="Série test", SeriesPrimaryImageTag="tag-series-1",
RunTimeTicks=45 * 60 * 1000 * TICKS_PER_MS, Overview="Résumé de l'épisode."))
return {"libraries": libraries, "movies": movies, "series": [series], "seasons": seasons,
"episodes": episodes}
class State:
def __init__(self):
self.lock = threading.Lock()
self.reset()
def reset(self):
self.catalog = _catalog()
self.requests = []
self.mocks = []
self.quick_connect_authorized = False
def all_items(self):
c = self.catalog
return c["libraries"] + c["movies"] + c["series"] + c["seasons"] + c["episodes"]
def find(self, item_id):
for item in self.all_items():
if item["Id"] == item_id:
return item
return None
class Handler(http.server.BaseHTTPRequestHandler):
server_version = "FakeJellyfin/1.0"
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
# ------------------------------------------------------------ réponses
def _send(self, status, body=None, content_type="application/json"):
if body is None:
data = b""
elif isinstance(body, bytes):
data = body
elif isinstance(body, str):
data = body.encode()
else:
data = json.dumps(body).encode()
self.send_response(status)
if data:
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(data)
def do_GET(self):
self._dispatch()
def do_POST(self):
self._dispatch()
def do_DELETE(self):
self._dispatch()
def _dispatch(self):
state = self.server.state
parsed = urllib.parse.urlsplit(self.path)
path = parsed.path
query = {k: v[0] for k, v in urllib.parse.parse_qs(parsed.query, keep_blank_values=True).items()}
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
try:
body = json.loads(raw) if raw else None
except ValueError:
body = raw.decode(errors="replace")
if path.startswith("/__"):
self._control(state, path, body)
return
with state.lock:
state.requests.append({"method": self.command, "path": path, "query": query,
"auth": self.headers.get("Authorization", ""), "body": body})
mock = next((m for m in state.mocks if m["path"] == path
and m.get("method", self.command) == self.command), None)
if mock:
if mock.get("delay"):
time.sleep(mock["delay"] / 1000.0)
if "raw" in mock:
self._send(mock.get("status", 200), mock["raw"], "text/plain")
else:
self._send(mock.get("status", 200), mock.get("body"))
return
try:
status, response = self._route(state, path, query, body)
except Exception as error: # bug du faux serveur : visible dans la réponse
status, response = 500, {"error": repr(error)}
if isinstance(response, bytes):
self._send(status, response, "image/png")
else:
self._send(status, response)
def _control(self, state, path, body):
with state.lock:
if path == "/__reset":
state.reset()
self._send(204)
elif path == "/__requests":
self._send(200, state.requests)
elif path == "/__mock":
state.mocks.insert(0, body)
self._send(204)
elif path == "/__quickconnect/authorize":
state.quick_connect_authorized = True
self._send(204)
else:
self._send(404, {"error": "contrôle inconnu"})
# --------------------------------------------------------- API Jellyfin
def _user_for_token(self):
match = re.search(r'Token="([^"]+)"', self.headers.get("Authorization", ""))
token = match and match.group(1)
return next((u for u in USERS if token == "token-" + u["Id"]), None)
def _signed_in(self, user):
return 200, {"AccessToken": "token-" + user["Id"], "ServerId": SERVER_ID,
"User": {"Name": user["Name"], "Id": user["Id"], "ServerId": SERVER_ID}}
def _route(self, state, path, query, body):
# --- public
if path == "/System/Info/Public":
return 200, {"Id": SERVER_ID, "ServerName": SERVER_NAME, "Version": "10.10.0",
"LocalAddress": "http://%s:%d" % self.server.server_address[:2]}
if path == "/Users/Public":
return 200, [{"Name": u["Name"], "Id": u["Id"], "HasPassword": u["HasPassword"]} for u in USERS]
if path == "/Users/AuthenticateByName":
body = body or {}
user = next((u for u in USERS if u["Name"].lower() == str(body.get("Username", "")).lower()), None)
if not user or body.get("Pw", "") != user["password"]:
return 401, "Error processing request."
return self._signed_in(user)
if path == "/QuickConnect/Enabled":
return 200, True
if path == "/QuickConnect/Initiate":
return 200, dict(QUICK_CONNECT, Authenticated=False)
if path == "/QuickConnect/Connect":
if query.get("Secret") != QUICK_CONNECT["Secret"]:
return 404, None
return 200, dict(QUICK_CONNECT, Authenticated=state.quick_connect_authorized)
if path == "/Users/AuthenticateWithQuickConnect":
if not state.quick_connect_authorized or (body or {}).get("Secret") != QUICK_CONNECT["Secret"]:
return 401, None
return self._signed_in(USERS[0])
if path == "/dev-config.json":
host, port = self.server.server_address[:2]
return 200, {"servers": ["%s:%d" % (host, port)],
"users": [{"name": "carol", "password": "test"}]}
if re.match(r"^/Items/[^/]+/Images/", path):
return 200, PNG
# --- authentifié
user = self._user_for_token()
if not user:
return 401, None
with state.lock:
return self._catalog_route(state, path, query, body)
def _catalog_route(self, state, path, query, body):
c = state.catalog
if path == "/Sessions/Logout":
return 204, None
if path == "/UserViews":
return 200, {"Items": c["libraries"], "TotalRecordCount": len(c["libraries"])}
if path == "/UserItems/Resume":
items = [i for i in c["movies"] + c["episodes"] if i["UserData"].get("PlaybackPositionTicks")]
return 200, {"Items": items, "TotalRecordCount": len(items)}
if path == "/Items/Latest":
parent = query.get("parentId")
items = c["movies"] if parent == "lib-movies" else c["series"] if parent == "lib-shows" else []
return 200, items[:int(query.get("limit") or 20)]
if path == "/Items":
parent = query.get("parentId")
items = c["movies"] if parent == "lib-movies" else c["series"] if parent == "lib-shows" else []
types = query.get("includeItemTypes", "").split(",")
items = [i for i in items if not types[0] or i["Type"] in types]
items = sorted(items, key=lambda i: i["Name"])
start = int(query.get("startIndex") or 0)
limit = int(query.get("limit") or len(items))
return 200, {"Items": items[start:start + limit], "TotalRecordCount": len(items),
"StartIndex": start}
match = re.match(r"^/Shows/([^/]+)/(Seasons|Episodes)$", path)
if match:
if match.group(2) == "Seasons":
items = [s for s in c["seasons"] if s["SeriesId"] == match.group(1)]
else:
items = [e for e in c["episodes"] if e["SeriesId"] == match.group(1)
and (not query.get("seasonId") or e["SeasonId"] == query["seasonId"])]
return 200, {"Items": items, "TotalRecordCount": len(items)}
match = re.match(r"^/Items/([^/]+)/PlaybackInfo$", path)
if match:
return self._playback_info(match.group(1))
match = re.match(r"^/Items/([^/]+)$", path)
if match:
item = state.find(match.group(1))
return (200, item) if item else (404, None)
if path in ("/Sessions/Playing", "/Sessions/Playing/Progress", "/Sessions/Playing/Stopped"):
body = body or {}
item = state.find(body.get("ItemId"))
if item is not None and path == "/Sessions/Playing/Stopped":
item["UserData"]["PlaybackPositionTicks"] = body.get("PositionTicks", 0)
return 204, None
return 404, None
def _playback_info(self, item_id):
session = "play-" + item_id
if item_id == "movie-broken":
return 200, {"MediaSources": [], "PlaySessionId": session, "ErrorCode": "NoCompatibleStream"}
source = {"Id": "src-" + item_id, "Container": "mkv", "SupportsDirectPlay": True,
"SupportsDirectStream": True, "SupportsTranscoding": True}
if item_id == "movie-transcode":
source.update(Container="mkv", SupportsDirectPlay=False, SupportsDirectStream=False,
TranscodingUrl="/videos/%s/master.m3u8?MediaSourceId=src-%s&PlaySessionId=%s"
% (item_id, item_id, session))
return 200, {"MediaSources": [source], "PlaySessionId": session}
class FakeServer(http.server.ThreadingHTTPServer):
daemon_threads = True
def __init__(self, address=("127.0.0.1", 0)):
super().__init__(address, Handler)
self.state = State()
def handle_error(self, request, client_address):
pass # client qui coupe (BrokenPipe) ou poignée de main TLS sur ce serveur HTTP
@property
def url(self):
return "http://%s:%d" % self.server_address[:2]
def start(address=("127.0.0.1", 0)):
"""Démarre le serveur dans un thread ; renvoie l'instance (server.url, server.shutdown())."""
server = FakeServer(address)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def main(argv=None):
parser = argparse.ArgumentParser(prog="freebox-jellyfin fake-server", description=__doc__.splitlines()[0])
parser.add_argument("--host", default="127.0.0.1", help="adresse d'écoute (défaut : 127.0.0.1)")
parser.add_argument("--port", type=int, default=8096, help="port (défaut : 8096)")
args = parser.parse_args(argv)
server = FakeServer((args.host, args.port))
print("Faux serveur Jellyfin sur %s (Ctrl+C pour arrêter)" % server.url, flush=True)
print("Dans l'app : adresse %s, port %d ; comptes alice / secret et bob (sans mot de passe)."
% (args.host, args.port), flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
return 0
+153
View File
@@ -0,0 +1,153 @@
"""Fabrique le paquet FreeStore (.tar.gz) à téléverser sur la console FreeFactory.
Reproduit « Outils > Freebox SDK > Make FreeStore Package » du plugin QtCreator Freebox
(github.com/fbx/freebox-qtcreator-plugin, src/freestorepackager.cc) :
- fichiers inclus comme dans Jellyfin.fbxproject : QML, JS, images, polices, qmldir et
manifest.json, pris dans app/ uniquement (l'outillage PC n'a rien à faire sur la box) ;
- vérifications : manifest.json (identifiant, version identique à Session.clientVersion,
points d'entrée existants), JSON valides, règles du Player (boxrules : ES5, QtQuick 2.5,
qmldir, singletons), syntaxe QML/JS (qmllint, s'il est installé) ;
- archive tar (format ustar, avec les entrées de dossiers) compressée en gzip.
Usage : freebox-jellyfin package [--output dist/paquet.tar.gz]
"""
import argparse
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import time
from . import boxrules
from .project import APP_DIR, REPO_DIR
APP_DIR, REPO_DIR = str(APP_DIR), str(REPO_DIR)
# Types de fichiers repris de Jellyfin.fbxproject (QmlFiles, JavaScriptFiles, ImageFiles, Files).
EXTENSIONS = {".qml", ".js", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".bmp", ".webp",
".ttf", ".otf", ".woff"}
NAMES = {"qmldir", "manifest.json"}
def collect_files():
files = []
for root, dirs, names in os.walk(APP_DIR):
rel_root = os.path.relpath(root, APP_DIR)
dirs[:] = sorted(d for d in dirs if not d.startswith(".")) # dossiers cachés exclus
for name in sorted(names):
if name in NAMES or os.path.splitext(name)[1].lower() in EXTENSIONS:
files.append(os.path.normpath(os.path.join(rel_root, name)))
return files
def check_manifest(files):
"""Mêmes règles que fileformat/manifest.cc du plugin. Renvoie le manifest."""
path = os.path.join(APP_DIR, "manifest.json")
if not os.path.exists(path):
raise ValueError("manifest.json manquant")
with open(path, encoding="utf-8") as stream:
manifest = json.load(stream)
identifier = manifest.get("identifier")
if not isinstance(identifier, str) or not re.fullmatch(r"\w+(\.\w+)+", identifier):
raise ValueError("manifest.json : « identifier » absent ou invalide (forme attendue : a.b.c)")
entry_points = manifest.get("entryPoints")
if not isinstance(entry_points, dict) or not entry_points:
raise ValueError("manifest.json : « entryPoints » absent ou invalide")
defaults = 0
for key, entry in entry_points.items():
if not isinstance(entry, dict) or not isinstance(entry.get("file"), str):
raise ValueError("manifest.json : entryPoints.%s.file doit être un fichier" % key)
if not re.fullmatch(r"[/\w.+~-]+", entry["file"]):
raise ValueError("manifest.json : caractères invalides dans entryPoints.%s.file" % key)
if entry["file"] not in files:
raise ValueError("manifest.json : entryPoints.%s.file « %s » absent du paquet" % (key, entry["file"]))
if "uiFlavor" in entry and entry["uiFlavor"] not in ("multi", "classic"):
raise ValueError("manifest.json : entryPoints.%s.uiFlavor doit valoir multi ou classic" % key)
if entry.get("default") is True:
defaults += 1
if defaults > 1:
raise ValueError("manifest.json : un seul point d'entrée peut avoir « default »: true")
version = manifest.get("version")
if not isinstance(version, str) or not re.fullmatch(r"\d+\.\d+\.\d+", version):
raise ValueError("manifest.json : « version » absente ou invalide (forme attendue : 1.2.3)")
# La version envoyée à Jellyfin (Session.clientVersion) doit rester la même.
with open(os.path.join(APP_DIR, "Core", "Session.qml"), encoding="utf-8") as stream:
session = stream.read()
client = re.search(r'clientVersion:\s*"([^"]*)"', session)
if not client or client.group(1) != version:
raise ValueError("version du manifest (%s) différente de Session.clientVersion (%s)"
% (version, client.group(1) if client else "introuvable"))
icon = manifest.get("icon")
if icon and icon not in files:
raise ValueError("manifest.json : icône « %s » absente du paquet" % icon)
return manifest
def check_sources(files):
for name in files:
if name.endswith(".json"):
with open(os.path.join(APP_DIR, name), encoding="utf-8") as stream:
json.load(stream)
problems = boxrules.check_app(APP_DIR)
if problems:
raise ValueError("règles du Freebox Player non respectées :\n" + "\n".join(problems))
qmllint = shutil.which("qmllint")
if not qmllint:
print("Attention : qmllint introuvable, syntaxe QML/JS non vérifiée.")
return
sources = [os.path.join(APP_DIR, f) for f in files if f.endswith((".qml", ".js"))]
result = subprocess.run([qmllint] + sources, capture_output=True, text=True)
if result.returncode != 0:
raise ValueError("erreurs de syntaxe QML/JS :\n" + (result.stdout + result.stderr).strip())
def build_archive(files, output):
def info(name, is_dir, size=0):
entry = tarfile.TarInfo(name + ("/" if is_dir else ""))
entry.type = tarfile.DIRTYPE if is_dir else tarfile.REGTYPE
entry.mode = 0o755 if is_dir else 0o644
entry.size = size
entry.mtime = int(time.time())
entry.uid = entry.gid = 0
entry.uname = entry.gname = ""
return entry
os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True)
seen_dirs = set()
with tarfile.open(output, "w:gz", format=tarfile.USTAR_FORMAT) as archive:
for name in files:
# Entrées de dossiers (comme le plugin), du parent vers l'enfant.
parts = name.split(os.sep)[:-1]
for depth in range(1, len(parts) + 1):
directory = "/".join(parts[:depth])
if directory not in seen_dirs:
seen_dirs.add(directory)
archive.addfile(info(directory, True))
with open(os.path.join(APP_DIR, name), "rb") as stream:
data = stream.read()
archive.addfile(info(name.replace(os.sep, "/"), False, len(data)), io.BytesIO(data))
def main(argv=None):
parser = argparse.ArgumentParser(prog="freebox-jellyfin package", description=__doc__.splitlines()[0])
parser.add_argument("--output", help="archive à créer (défaut : dist/<identifier>-<version>.tar.gz)")
args = parser.parse_args(argv)
files = collect_files()
try:
manifest = check_manifest(files)
check_sources(files)
except (ValueError, json.JSONDecodeError) as error:
sys.exit("Paquet non créé : %s" % error)
output = args.output or os.path.join(
REPO_DIR, "dist", "%s-%s.tar.gz" % (manifest["identifier"], manifest["version"]))
build_archive(files, output)
print("Paquet créé : %s — version %s (%d fichiers, %.1f Ko)" % (
os.path.relpath(output, os.getcwd()), manifest["version"], len(files), os.path.getsize(output) / 1024))
print("À téléverser sur la console FreeFactory (http://factory.free.fr).")
+37
View File
@@ -0,0 +1,37 @@
"""Lance l'application sur le PC avec qmlscene (Qt 5) et libfbxqml."""
import argparse
import os
import subprocess
import sys
from .project import APP_DIR, REPO_DIR, libfbxqml, qmlscene
def main(argv=None):
parser = argparse.ArgumentParser(prog="freebox-jellyfin preview", description=__doc__)
parser.add_argument("--fullscreen", action="store_true",
help="lance Jellyfin.qml en plein écran, comme sur la box (sinon fenêtre 1280x720)")
parser.add_argument("--fake-server", action="store_true",
help="démarre aussi le faux serveur Jellyfin (127.0.0.1, port --fake-port)")
parser.add_argument("--fake-port", type=int, default=8096, help="port du faux serveur (défaut : 8096)")
args = parser.parse_args(argv)
lib, scene = libfbxqml(), qmlscene()
qml = APP_DIR / "Jellyfin.qml" if args.fullscreen else REPO_DIR / "tools" / "preview.qml"
command = [scene, "-I", str(lib), str(qml)]
if not args.fake_server:
os.execv(scene, command)
from . import fake_server
try:
server = fake_server.start(("127.0.0.1", args.fake_port))
except OSError as error:
sys.exit("Faux serveur : port %d indisponible (%s). Essayer --fake-port." % (args.fake_port, error))
print("Faux serveur Jellyfin sur %s : dans l'app, adresse 127.0.0.1, port %d ;"
" comptes alice / secret et bob (sans mot de passe)." % (server.url, args.fake_port), flush=True)
try:
return subprocess.call(command)
except KeyboardInterrupt:
return 130
finally:
server.shutdown()
server.server_close()
+38
View File
@@ -0,0 +1,38 @@
"""Emplacements partagés par les commandes : dépôt, application QML, libfbxqml et qmlscene.
REPO_DIR : racine du dépôt (outils, dist/, deploy.log) ;
APP_DIR : REPO_DIR/app, seul dossier envoyé au Freebox Player (manifest.json, QML, images).
"""
import os
import shutil
import sys
from pathlib import Path
def _find_root() -> Path:
"""Dossier contenant app/manifest.json : depuis le dossier courant, sinon depuis ce module."""
for start in (Path.cwd(), Path(__file__).resolve().parent):
for folder in (start, *start.parents):
if (folder / "app" / "manifest.json").is_file() and (folder / "pyproject.toml").is_file():
return folder
sys.exit("Projet introuvable : lancez la commande depuis le dépôt Jellyfin-Freebox.")
REPO_DIR = _find_root()
APP_DIR = REPO_DIR / "app"
def libfbxqml() -> Path:
"""libfbxqml (module fbx.application en QML pur) : ../libfbxqml, ou $LIBFBXQML."""
path = Path(os.environ.get("LIBFBXQML", REPO_DIR.parent / "libfbxqml"))
if not (path / "fbx").is_dir():
sys.exit("libfbxqml introuvable : git clone https://github.com/fbx/libfbxqml.git %s" % path)
return path
def qmlscene() -> str:
"""qmlscene de Qt 5 : $QMLSCENE, le PATH, ou l'emplacement Debian/Ubuntu."""
path = os.environ.get("QMLSCENE") or shutil.which("qmlscene") or "/usr/lib/qt5/bin/qmlscene"
if not os.path.exists(path) and not shutil.which(path):
sys.exit("qmlscene introuvable : sudo apt install qmlscene")
return path
+102
View File
@@ -0,0 +1,102 @@
"""Tests de l'application, sur le PC, en trois étapes (arrêt à la première en échec) :
1. règles du Freebox Player (boxrules : ES5, QtQuick 2.5, qmldir, singletons) ;
2. tests Python de l'outillage (tests/python, unittest) ;
3. tests QML (tests/qml/tst_*.qml, qmltestrunner) contre le faux serveur Jellyfin
(fake_server.py), dont l'adresse est fournie aux tests par le module QML TestEnv.
freebox-jellyfin test tout
freebox-jellyfin test --qml tst_session.qml un seul fichier de tests QML
freebox-jellyfin test Session::test_logout une seule fonction (nom du TestCase::fonction)
"""
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from . import boxrules, fake_server
from .project import APP_DIR, REPO_DIR, libfbxqml
TESTS_DIR = REPO_DIR / "tests"
QML_TESTS = TESTS_DIR / "qml"
PYTHON_TESTS = TESTS_DIR / "python"
def qmltestrunner():
path = os.environ.get("QMLTESTRUNNER") or shutil.which("qmltestrunner") or "/usr/lib/qt5/bin/qmltestrunner"
if not shutil.which(path) and not os.path.exists(path):
sys.exit("qmltestrunner introuvable : sudo apt install qtdeclarative5-dev-tools qml-module-qttest")
return path
def run_rules():
problems = boxrules.check_app(APP_DIR)
if problems:
print("Échec : règles du Freebox Player non respectées :", file=sys.stderr)
print("\n".join(problems), file=sys.stderr)
return False
print("Règles du Freebox Player : OK")
return True
def run_python():
if not PYTHON_TESTS.is_dir():
return True
suite = unittest.defaultTestLoader.discover(str(PYTHON_TESTS), top_level_dir=str(PYTHON_TESTS))
result = unittest.TextTestRunner(verbosity=1).run(suite)
return result.wasSuccessful()
def _test_env(folder, server):
"""Module QML TestEnv : Env.baseUrl / Env.host / Env.port du faux serveur."""
module = Path(folder) / "TestEnv"
module.mkdir()
host, port = server.server_address[:2]
(module / "qmldir").write_text("module TestEnv\nEnv 1.0 Env.js\n", encoding="utf-8")
(module / "Env.js").write_text(
'.pragma library\nvar baseUrl = "%s";\nvar host = "%s";\nvar port = %d;\n' % (server.url, host, port),
encoding="utf-8")
def run_qml(qml_file, functions):
runner, lib = qmltestrunner(), libfbxqml()
target = QML_TESTS / qml_file if qml_file else QML_TESTS
if not target.exists():
sys.exit("Tests QML introuvables : %s" % target)
server = fake_server.start()
try:
with tempfile.TemporaryDirectory() as folder:
os.chmod(folder, 0o700)
_test_env(folder, server)
runtime = Path(folder) / "runtime"
runtime.mkdir(mode=0o700)
# Rendu logiciel hors écran : comme check, fonctionne en CI (pas d'OpenGL).
env = dict(os.environ, XDG_RUNTIME_DIR=str(runtime), QT_QPA_PLATFORM="offscreen",
QT_QUICK_BACKEND="software", QT_LOGGING_RULES="qt.multimedia*=false")
command = [runner, "-input", str(target), "-import", str(lib), "-import", folder] + list(functions)
print("Tests QML (%s), faux serveur sur %s" % (target.relative_to(REPO_DIR), server.url), flush=True)
result = subprocess.run(command, env=env)
return result.returncode == 0
finally:
server.shutdown()
server.server_close()
def main(argv=None):
parser = argparse.ArgumentParser(prog="freebox-jellyfin test", description=__doc__.splitlines()[0],
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="\n".join(__doc__.splitlines()[1:]))
parser.add_argument("--qml", metavar="FICHIER", help="un seul fichier de tests/qml (ex. tst_session.qml)")
parser.add_argument("--no-python", action="store_true", help="sauter les tests Python de l'outillage")
parser.add_argument("functions", nargs="*", help="fonctions QML à lancer (TestCase::fonction)")
args = parser.parse_args(argv)
if not run_rules():
return 1
if not args.no_python and not args.qml and not args.functions and not run_python():
return 1
return 0 if run_qml(args.qml, args.functions) else 1
+113
View File
@@ -0,0 +1,113 @@
import tempfile
import textwrap
import unittest
from pathlib import Path
from freebox_jellyfin import boxrules
def es5(code):
return boxrules.check_es5("x.js", textwrap.dedent(code))
class Es5Test(unittest.TestCase):
def test_detects_es6(self):
cases = {
"let a = 1;": "let",
"const b = 2;": "const",
"list.map(x => x * 2);": "fléchée",
"var s = `a${b}`;": "gabarit",
"class A {}": "class",
"for (var x of list) {}": "for…of",
"f(...args);": "...",
}
for code, expected in cases.items():
with self.subTest(code=code):
problems = es5(code)
self.assertEqual(len(problems), 1, problems)
self.assertIn(expected, problems[0])
def test_ignores_comments_strings_and_regexes(self):
code = """
// let a = 1; x => y
/* const b = 2;
`gabarit` */
var s = "let c = 3 => ...rest";
var t = 'const d = `e`';
var url = /^https?:\\/\\//i; // (regex avec « // »)
var clean = text.replace(/\\/+$/, "");
var letter = constant + lettuce; // mots qui commencent par let/const
var ok = a >= b;
"""
self.assertEqual(es5(code), [])
def test_reports_line_numbers(self):
self.assertEqual(es5("var a;\n\nlet b;\n"), ["x.js:3: « let » (ES6) : utiliser var"])
class ImportsTest(unittest.TestCase):
def test_qtquick_version(self):
self.assertEqual(boxrules.check_imports("a.qml", "import QtQuick 2.5\n"), [])
self.assertEqual(boxrules.check_imports("a.qml", "import QtQuick 2.0\n"), [])
self.assertEqual(len(boxrules.check_imports("a.qml", "import QtQuick 2.6\n")), 1)
self.assertEqual(len(boxrules.check_imports("a.qml", "import QtQuick 2.15\n")), 1)
def test_forbidden_imports(self):
self.assertEqual(len(boxrules.check_imports("a.qml", "import QtQuick.Controls 1.4\n")), 1)
self.assertEqual(len(boxrules.check_imports("a.qml", 'import "."\n')), 1)
self.assertEqual(boxrules.check_imports("a.qml", '// import QtQuick 2.15\nimport "../Shared"\n'), [])
class DirectoriesTest(unittest.TestCase):
def make_app(self, files):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
root = Path(folder.name)
for name, content in files.items():
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(textwrap.dedent(content), encoding="utf-8")
return root
def test_valid_layout(self):
app = self.make_app({
"Main.qml": 'import QtQuick 2.5\nimport "Components"\nimport "Shared"\nItem {}\n',
"Components/qmldir": "Button 1.0 Button.qml\n",
"Components/Button.qml": 'import QtQuick 2.5\nimport "../Shared"\nItem { width: Theme.size }\n',
"Shared/qmldir": "singleton Theme 1.0 Theme.qml\n",
"Shared/Theme.qml": "pragma Singleton\nimport QtQuick 2.5\nQtObject { property int size: 1 }\n",
})
self.assertEqual(boxrules.check_directories(app), [])
def test_missing_qmldir_and_entries(self):
app = self.make_app({
"Main.qml": 'import "Components"\nimport "Other"\nItem {}\n',
"Components/qmldir": "Button 1.0 Button.qml\nGone 1.0 Gone.qml\n",
"Components/Button.qml": "Item {}\n",
"Components/Card.qml": "Item {}\n",
"Other/Thing.qml": "Item {}\n",
})
problems = "\n".join(boxrules.check_directories(app))
self.assertIn("Card.qml absent", problems)
self.assertIn("Gone.qml introuvable", problems)
self.assertIn("Other/: importé mais sans qmldir", problems)
def test_singleton_cycles(self):
app = self.make_app({
"Main.qml": 'import "Shared"\nItem {}\n',
"Shared/qmldir": "singleton Theme 1.0 Theme.qml\nsingleton Style 1.0 Style.qml\nCard 1.0 Card.qml\n",
"Shared/Theme.qml": "QtObject {}\n",
"Shared/Style.qml": "QtObject {}\n",
"Shared/Card.qml": "Item { width: Theme.size }\n",
})
problems = "\n".join(boxrules.check_directories(app))
self.assertIn("plusieurs singletons", problems)
self.assertIn("Card.qml: utilise le singleton Theme", problems)
def test_real_app_is_clean(self):
from freebox_jellyfin.project import APP_DIR
self.assertEqual(boxrules.check_app(APP_DIR), [])
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -0,0 +1,97 @@
import json
import os
import tarfile
import tempfile
import unittest
import urllib.error
import urllib.request
from freebox_jellyfin import fake_server, package
class PackageTest(unittest.TestCase):
def test_file_selection(self):
files = package.collect_files()
self.assertIn("manifest.json", files)
self.assertIn("Jellyfin.qml", files)
self.assertIn(os.path.join("Core", "qmldir"), files)
for name in files:
self.assertFalse(name.endswith((".fbxproject", ".user", ".py")), name)
self.assertFalse(any(part.startswith(".") for part in name.split(os.sep)), name)
def test_manifest_matches_client_version(self):
manifest = package.check_manifest(package.collect_files())
self.assertRegex(manifest["version"], r"^\d+\.\d+\.\d+$")
def test_archive_layout(self):
files = package.collect_files()
with tempfile.TemporaryDirectory() as folder:
output = os.path.join(folder, "p.tar.gz")
package.build_archive(files, output)
with tarfile.open(output) as archive:
names = archive.getnames()
self.assertIn("Core", names) # entrées de dossiers
self.assertIn("Core/Session.qml", names) # chemins relatifs à app/
self.assertEqual(archive.getmember("Core").type, tarfile.DIRTYPE)
class FakeServerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = fake_server.start()
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()
def call(self, method, path, body=None, token=None):
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = 'MediaBrowser Client="t", Token="%s"' % token
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(self.server.url + path, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(request, timeout=5) as response:
raw = response.read()
return response.status, json.loads(raw) if raw and raw[:1] in b"[{\"tf" else raw
except urllib.error.HTTPError as error:
return error.code, None
def setUp(self):
self.call("POST", "/__reset")
def test_auth_required(self):
self.assertEqual(self.call("GET", "/UserViews")[0], 401)
status, data = self.call("POST", "/Users/AuthenticateByName", {"Username": "alice", "Pw": "secret"})
self.assertEqual(status, 200)
self.assertEqual(self.call("GET", "/UserViews", token=data["AccessToken"])[0], 200)
self.assertEqual(self.call("POST", "/Users/AuthenticateByName", {"Username": "alice", "Pw": "x"})[0], 401)
def test_paging(self):
token = "token-user-alice"
status, data = self.call("GET", "/Items?parentId=lib-movies&startIndex=20&limit=10", token=token)
self.assertEqual((len(data["Items"]), data["TotalRecordCount"]), (5, 25))
def test_mock_and_journal(self):
self.call("POST", "/__mock", {"path": "/Users/Public", "status": 503})
self.assertEqual(self.call("GET", "/Users/Public")[0], 503)
status, journal = self.call("GET", "/__requests")
self.assertEqual([r["path"] for r in journal], ["/Users/Public"])
self.call("POST", "/__reset")
self.assertEqual(self.call("GET", "/Users/Public")[0], 200)
def test_stop_updates_resume_point(self):
token = "token-user-alice"
self.call("POST", "/Sessions/Playing/Stopped", {"ItemId": "movie-01", "PositionTicks": 1234}, token=token)
status, item = self.call("GET", "/Items/movie-01", token=token)
self.assertEqual(item["UserData"]["PlaybackPositionTicks"], 1234)
def test_images_are_png(self):
status, data = self.call("GET", "/Items/movie-01/Images/Primary?tag=x")
self.assertEqual(status, 200)
self.assertTrue(data.startswith(b"\x89PNG"))
if __name__ == "__main__":
unittest.main()
+81
View File
@@ -0,0 +1,81 @@
import QtQuick 2.5
import QtTest 1.2
import TestEnv 1.0
// Base des tests : accès au faux serveur Jellyfin (src/freebox_jellyfin/fake_server.py)
// démarré par `freebox-jellyfin test`, qui fournit son adresse via le module TestEnv.
// Les tests tournent sur le PC (Qt 5.15) : ce dossier n'est pas soumis aux règles ES5.
TestCase {
id: testCase
readonly property string serverUrl: Env.baseUrl
readonly property string serverHost: Env.host
readonly property string serverPort: String(Env.port)
// Lance start(done) et attend l'appel de done(...) ; renvoie ses arguments (tableau).
function waitCallback(start, timeout, message) {
var box = { done: false, args: [] };
start(function () {
box.args = Array.prototype.slice.call(arguments);
box.done = true;
});
tryVerify(function () { return box.done; }, timeout || 5000, message || "callback jamais appelé");
return box.args;
}
// Requête au faux serveur ; renvoie la réponse JSON décodée (ou null).
function http(method, path, body) {
var result = waitCallback(function (done) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE)
done(xhr.status, xhr.responseText);
};
xhr.open(method, serverUrl + path);
if (body !== undefined) {
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(body));
} else {
xhr.send();
}
}, 5000, "faux serveur injoignable : " + method + " " + path);
return result[1] ? JSON.parse(result[1]) : null;
}
function resetServer() {
http("POST", "/__reset");
}
// Réponse imposée : { path, method?, status?, body?, raw?, delay? (ms) }
function mock(spec) {
http("POST", "/__mock", spec);
}
// Requêtes reçues par le faux serveur (toutes, ou celles d'un chemin).
function requests(path) {
var all = http("GET", "/__requests");
return path ? all.filter(function (r) { return r.path === path; }) : all;
}
function lastRequest(path) {
var list = requests(path);
return list.length > 0 ? list[list.length - 1] : null;
}
// Premier descendant (parcours en largeur) pour lequel predicate(objet) est vrai.
function findChild(root, predicate) {
var queue = [root];
while (queue.length > 0) {
var item = queue.shift();
if (item !== root && predicate(item))
return item;
var children = item.children || [];
for (var i = 0; i < children.length; i++)
queue.push(children[i]);
var resources = item.resources || [];
for (var j = 0; j < resources.length; j++)
queue.push(resources[j]);
}
return null;
}
}
+212
View File
@@ -0,0 +1,212 @@
import QtQuick 2.5
import QtTest 1.2
import "../../app/Core"
// Parcours complets à la télécommande (touches simulées), comme sur la box :
// Navigator + vrais écrans + vraie Session, contre le faux serveur Jellyfin.
// L'interface est hors du TestCase : il est invisible, et KeyNavigation ignore les
// éléments invisibles.
Item {
width: 1280
height: 720
Session {
id: session
}
Navigator {
id: navigator
anchors.fill: parent
session: session
focus: true
}
JellyfinTestCase {
id: testCase
name: "Parcours"
when: windowShown
function init() {
session.cancel();
session.logout();
session.currentServer = null;
session.devUsers = [];
session.servers.clear();
session._quickConnectPoll.interval = 5000;
resetServer();
navigator.reset("ServerSelect");
waitTitle("Sélectionner un serveur");
}
// Écran affiché par le Navigator.
function view() {
var loader = findChild(navigator, function (o) { return o.setSource !== undefined && o.item !== undefined; });
return loader ? loader.item : null;
}
function waitTitle(title, timeout) {
tryVerify(function () { var v = view(); return v !== null && v.title === title; }, timeout || 5000,
"écran « " + title + " » attendu, affiché : « " + (view() ? view().title : "") + " »");
wait(50); // focus initial posé par le Navigator (onLoaded)
}
function type(text) {
for (var i = 0; i < text.length; i++)
keyClick(text.charAt(i));
}
function press(key, times) {
for (var i = 0; i < (times || 1); i++)
keyClick(key);
}
// Connexion sans passer par l'interface (pour les parcours qui commencent plus loin).
function signedIn() {
waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000);
var result = waitCallback(function (done) { session.authenticate("alice", "secret", done); });
compare(result[0], null);
}
function rowTitles() {
return view().rows.map(function (r) { return r.title; });
}
// ----------------------------------------------------------- connexion
function test_addServerAndSignInWithPassword() {
press(Qt.Key_Return); // « Ajouter un serveur »
waitTitle("Ajouter un serveur");
type(serverHost);
press(Qt.Key_Return); // champ suivant : port
type(serverPort);
press(Qt.Key_Return); // connexion
waitTitle("Qui regarde ?", 15000);
tryVerify(function () { return !view().loading; }, 5000);
compare(view().users.length, 2);
press(Qt.Key_Return); // alice (mot de passe)
waitTitle("Se connecter");
compare(view().username, "alice");
type("faux");
press(Qt.Key_Return);
tryCompare(view(), "error", "Nom d'utilisateur ou mot de passe incorrect.", 5000);
compare(view().title, "Se connecter");
press(Qt.Key_Backspace, 4); // le focus est revenu sur le mot de passe
type("secret");
press(Qt.Key_Return);
waitTitle("Bonjour alice");
tryVerify(function () { return !view().loading; }, 5000);
compare(rowTitles(), ["Reprendre", "Mes médias", "Ajouts récents · Films", "Ajouts récents · Séries"]);
compare(navigator.depth, 1, "Retour ne doit pas revenir à l'écran de connexion");
compare(session.servers.count, 1, "serveur enregistré");
compare(session.servers.get(0).address, "http://" + serverHost + ":" + serverPort);
}
function test_savedServerAndUserWithoutPassword() {
waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000);
navigator.reset("ServerSelect");
waitTitle("Sélectionner un serveur");
press(Qt.Key_Return); // le serveur enregistré a le focus
waitTitle("Qui regarde ?");
tryVerify(function () { return !view().loading; }, 5000);
press(Qt.Key_Right); // bob
press(Qt.Key_Return); // connexion directe, sans mot de passe
waitTitle("Bonjour bob");
}
function test_invalidServerShowsError() {
press(Qt.Key_Return);
waitTitle("Ajouter un serveur");
type("127.0.0.1");
press(Qt.Key_Return);
type("1");
press(Qt.Key_Return);
tryCompare(view(), "error", "Aucun serveur Jellyfin trouvé à cette adresse.", 15000);
compare(view().title, "Ajouter un serveur");
compare(view().busy, false);
}
function test_quickConnect() {
session._quickConnectPoll.interval = 50;
waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000);
navigator.reset("ServerSelect");
waitTitle("Sélectionner un serveur");
press(Qt.Key_Return);
waitTitle("Qui regarde ?");
tryVerify(function () { return !view().loading; }, 5000);
press(Qt.Key_Right, 2); // « Ajouter un compte »
press(Qt.Key_Return);
waitTitle("Se connecter");
tryVerify(function () { return view().quickConnectAvailable; }, 5000);
press(Qt.Key_Down, 2); // nom → mot de passe → « Se connecter »
press(Qt.Key_Right); // « Utiliser Quick Connect »
press(Qt.Key_Return);
waitTitle("Quick Connect");
tryCompare(view(), "quickConnectCode", "123456", 5000);
http("POST", "/__quickconnect/authorize");
waitTitle("Bonjour alice");
}
// ----------------------------------------------------------- catalogue
function test_homeToDetailsAndBack() {
signedIn();
navigator.reset("Home");
waitTitle("Bonjour alice");
tryVerify(function () { return !view().loading; }, 5000);
press(Qt.Key_Return); // 1re carte de « Reprendre »
waitTitle("Film direct");
tryVerify(function () { return view().item !== null; }, 5000);
compare(view().resumeMs, 600000);
press(Qt.Key_Escape);
waitTitle("Bonjour alice");
press(Qt.Key_Escape); // depuis l'accueil : choix de l'utilisateur
waitTitle("Qui regarde ?");
compare(navigator.depth, 2);
}
function test_libraryAndSeries() {
signedIn();
navigator.reset("Home");
waitTitle("Bonjour alice");
tryVerify(function () { return !view().loading; }, 5000);
press(Qt.Key_Down); // « Mes médias »
press(Qt.Key_Return); // Films
waitTitle("Films");
tryCompare(view(), "total", 25, 5000);
press(Qt.Key_Escape);
waitTitle("Bonjour alice");
tryVerify(function () { return !view().loading; }, 5000);
press(Qt.Key_Down, 3); // « Ajouts récents · Séries »
press(Qt.Key_Return);
waitTitle("Série test");
tryVerify(function () { return view().seasons.length === 2; }, 5000);
press(Qt.Key_Return); // Saison 1 (titre : la série, sous-titre : la saison)
tryVerify(function () { return view().subtitle === "Saison 1"; }, 5000, "écran de la saison attendu");
tryVerify(function () { return view().episodes !== undefined; }, 5000);
}
// De bout en bout : la lecture échoue (pas de flux sur le faux serveur), puis Retour.
// Le point de reprise (10 min) doit rester intact sur le serveur.
function test_failedPlaybackKeepsResumePoint() {
signedIn();
navigator.reset("Home");
navigator.push("Details", { itemId: "movie-direct" });
waitTitle("Film direct");
tryVerify(function () { return view().item !== null; }, 5000);
press(Qt.Key_Return); // « Reprendre à 10:00 »
tryVerify(function () { return view().itemId === "movie-direct" && view().info !== null; }, 5000);
compare(view().startMs, 600000);
wait(1500);
press(Qt.Key_Escape);
waitTitle("Film direct");
wait(300);
compare(requests("/Sessions/Playing").length, 0);
compare(requests("/Sessions/Playing/Progress").length, 0);
compare(requests("/Sessions/Playing/Stopped").length, 0);
var item = waitCallback(function (done) { session.loadItem("movie-direct", done); })[1];
compare(item.positionTicks, 6000000000);
}
}
}
+111
View File
@@ -0,0 +1,111 @@
import QtQuick 2.5
import QtTest 1.2
import "../../app/Shared/Format.js" as Format
import "../../app/Shared/Remote.js" as Remote
import "../../app/Core/DeviceProfile.js" as DeviceProfile
// Fonctions pures : Format.js, Remote.js, DeviceProfile.js.
TestCase {
name: "Helpers"
function test_ticks() {
compare(Format.ticksToMs(600000000), 60000);
compare(Format.msToTicks(1500), 15000000);
compare(Format.ticksToMs(undefined), 0);
compare(Format.msToTicks(null), 0);
}
function test_runtime_data() {
return [
{ tag: "vide", minutes: 0, expected: "" },
{ tag: "minutes", minutes: 52, expected: "52 min" },
{ tag: "heure pile", minutes: 120, expected: "2 h" },
{ tag: "heure + minutes < 10", minutes: 63, expected: "1 h 03 min" },
{ tag: "heure + minutes", minutes: 94, expected: "1 h 34 min" }
];
}
function test_runtime(data) {
compare(Format.runtime(Format.msToTicks(data.minutes * 60000)), data.expected);
}
function test_clock_data() {
return [
{ tag: "zéro", ms: 0, expected: "0:00" },
{ tag: "négatif", ms: -5000, expected: "0:00" },
{ tag: "secondes", ms: 4000, expected: "0:04" },
{ tag: "minutes", ms: 245000, expected: "4:05" },
{ tag: "heures", ms: 3723000, expected: "1:02:03" },
{ tag: "heures, minutes à 2 chiffres", ms: 2 * 3600000 + 45 * 60000, expected: "2:45:00" }
];
}
function test_clock(data) {
compare(Format.clock(data.ms), data.expected);
}
function test_cardLabels() {
var episode = { type: "Episode", name: "Pilote", seriesName: "Série", parentIndexNumber: 1, indexNumber: 3 };
compare(Format.episodeCode(episode), "S1 · É3");
compare(Format.cardTitle(episode), "Série");
compare(Format.cardSubtitle(episode), "S1 · É3 – Pilote");
compare(Format.episodeCode({ type: "Movie" }), "");
compare(Format.cardTitle({ type: "Movie", name: "Film" }), "Film");
compare(Format.cardSubtitle({ type: "Movie", year: 1997 }), "1997");
compare(Format.cardSubtitle({ type: "Movie", year: 0 }), "");
compare(Format.cardSubtitle({ type: "Series", childCount: 1 }), "1 saison");
compare(Format.cardSubtitle({ type: "Series", childCount: 3 }), "3 saisons");
}
function test_progress() {
compare(Format.progress({ playedPercentage: 25 }), 0.25);
compare(Format.progress({ runtimeTicks: 1000, positionTicks: 500 }), 0.5);
compare(Format.progress({ runtimeTicks: 0, positionTicks: 0 }), 0);
}
function test_infoLine() {
compare(Format.infoLine({ type: "Movie", year: 1997, runtimeTicks: Format.msToTicks(94 * 60000),
rating: "Tous publics", communityRating: 7.46 }),
"1997 · 1 h 34 min · Tous publics · 7,5/10");
compare(Format.infoLine({ type: "Episode", parentIndexNumber: 2, indexNumber: 1 }), "S2 · É1");
compare(Format.infoLine({ type: "Movie" }), "");
}
function test_remote() {
verify(Remote.isAccept(Qt.Key_Return));
verify(Remote.isAccept(Qt.Key_Enter));
verify(Remote.isAccept(Qt.Key_Select));
verify(!Remote.isAccept(Qt.Key_Space));
verify(Remote.isBack(Qt.Key_Back));
verify(Remote.isBack(Qt.Key_Escape));
verify(!Remote.isBack(Qt.Key_Backspace));
}
// La Revolution ne lit que le H.264 : jamais de HEVC déclaré, sinon Jellyfin
// enverrait un flux illisible au lieu de transcoder.
function test_deviceProfile_codecs() {
var profile = DeviceProfile.profile();
verify(profile.DirectPlayProfiles.length > 0);
for (var i = 0; i < profile.DirectPlayProfiles.length; i++) {
compare(profile.DirectPlayProfiles[i].VideoCodec, "h264");
}
var transcode = profile.TranscodingProfiles[0];
compare(transcode.Protocol, "hls");
compare(transcode.VideoCodec, "h264");
compare(profile.MaxStreamingBitrate, DeviceProfile.maxBitrate);
verify(JSON.stringify(profile).toLowerCase().indexOf("hevc") < 0);
verify(JSON.stringify(profile).toLowerCase().indexOf("h265") < 0);
}
// Sous-titres texte « External » : sinon Jellyfin transcode pour les incruster.
function test_deviceProfile_subtitles() {
var subtitles = DeviceProfile.profile().SubtitleProfiles;
var formats = [];
for (var i = 0; i < subtitles.length; i++) {
compare(subtitles[i].Method, "External", subtitles[i].Format);
formats.push(subtitles[i].Format);
}
verify(formats.indexOf("srt") >= 0);
verify(formats.indexOf("subrip") >= 0);
}
}
+258
View File
@@ -0,0 +1,258 @@
import QtQuick 2.5
import QtTest 1.2
import "../../app/Views"
// Views/PlayerView.qml : ce qui est signalé au serveur (reprise, « vu »).
// Règle critique : ne jamais écraser le point de reprise. Rien n'est signalé avant que la
// lecture ait démarré ET atteint la position de reprise, et jamais d'arrêt à la position 0.
//
// La session est simulée, et l'état du lecteur est piloté directement sur le VideoSurface
// (sans source, son interrogation périodique du lecteur reste à l'arrêt). Le lecteur est créé
// dans « stage » : le TestCase est invisible, et le focus ignore les éléments invisibles.
Item {
id: stage
width: 1280
height: 720
TestCase {
id: testCase
name: "PlayerView"
when: windowShown
property var player: null
property var video: null
property var session: null
property var navigator: null
Component {
id: fakeSessionComponent
QtObject {
property var reports: []
property var pending: null
property string preparedItem: ""
function preparePlayback(itemId, callback) {
preparedItem = itemId;
pending = callback;
}
function reportPlayback(event, info, positionMs, paused) {
var list = reports.slice();
list.push({ event: event, position: positionMs, paused: paused, itemId: info.itemId });
reports = list;
}
}
}
Component {
id: fakeNavigatorComponent
QtObject {
property int pops: 0
function pop() {
pops++;
return true;
}
}
}
Component {
id: playerComponent
PlayerView {
anchors.fill: parent
}
}
function open(startMs) {
session = fakeSessionComponent.createObject(testCase);
navigator = fakeNavigatorComponent.createObject(testCase);
player = playerComponent.createObject(stage, {
session: session, navigator: navigator, itemId: "movie-01", title: "Film", startMs: startMs || 0
});
verify(player !== null, "PlayerView non créé");
video = findVideo(player);
verify(video !== null, "VideoSurface introuvable");
compare(session.preparedItem, "movie-01");
}
// Réponse de Session.preparePlayback (URL vide : aucun vrai lecteur ne démarre).
function prepared() {
session.pending(null, { url: "", itemId: "movie-01", mediaSourceId: "src", playSessionId: "ps",
playMethod: "Transcode" });
}
// Même ordre que VideoSurface._poll() : position et durée, puis état.
function play(positionMs, durationMs) {
video.duration = durationMs || 7200000;
video.position = positionMs;
video.playerState = "playing";
}
function close() {
player.destroy();
player = null;
wait(20);
}
function events() {
return session.reports.map(function (r) { return r.event + "@" + Math.round(r.position); });
}
function findVideo(root) {
var queue = [root];
while (queue.length > 0) {
var item = queue.shift();
if (item !== root && item.backendName !== undefined && item.playerState !== undefined)
return item;
for (var i = 0; i < item.children.length; i++)
queue.push(item.children[i]);
}
return null;
}
function findTimer(root, interval) {
for (var i = 0; i < root.resources.length; i++) {
if (root.resources[i].interval === interval)
return root.resources[i];
}
return null;
}
function cleanup() {
if (player)
close();
if (session)
session.destroy();
if (navigator)
navigator.destroy();
session = navigator = video = null;
}
// ---------------------------------------------------------------- reprise
// Le cas qui a déjà effacé des points de reprise : lecture lancée mais position de
// reprise jamais atteinte (déplacement initial raté), puis Retour.
function test_resume_nothingReportedBeforeResumePoint() {
open(600000);
prepared();
play(0);
play(1000);
compare(events(), [], "rien avant la position de reprise");
close();
compare(events(), [], "pas d'arrêt signalé : le point de reprise serait écrasé");
}
function test_resume_reportedOnceReached() {
open(600000);
prepared();
play(0);
video.position = 590000; // à moins de 15 s de la reprise
compare(events(), ["start@590000"]);
video.position = 601000;
compare(events(), ["start@590000"], "start une seule fois");
close();
compare(events(), ["start@590000", "stop@601000"]);
}
function test_resume_notStartedWhilePaused() {
open(600000);
prepared();
video.duration = 7200000;
video.playerState = "paused";
video.position = 600000;
compare(events(), [], "pas de start tant que la lecture n'a pas démarré");
video.playerState = "playing";
compare(events(), ["start@600000"]);
}
// ------------------------------------------------------ depuis le début
function test_fromStart_startAtZeroButNoStopAtZero() {
open(0);
prepared();
play(0);
compare(events(), ["start@0"]);
close();
compare(events(), ["start@0"], "jamais d'arrêt signalé à la position 0");
}
function test_fromStart_stopWithPositionAndPause() {
open(0);
prepared();
play(5000);
video.playerState = "paused";
close();
compare(events(), ["start@5000", "stop@5000"]);
compare(session.reports[1].paused, true);
}
function test_progressEvery10s() {
open(0);
prepared();
play(1000);
var timer = findTimer(player, 10000);
verify(timer !== null, "minuterie de progression introuvable");
verify(timer.running);
timer.interval = 50;
video.position = 2000;
tryVerify(function () { return events().indexOf("progress@2000") >= 0; }, 2000);
video.position = 0;
var count = session.reports.length;
wait(200);
compare(session.reports.length, count, "pas de progression signalée à la position 0");
}
// ------------------------------------------------------- échecs et fin
function test_prepareError_nothingReported() {
open(600000);
session.pending("Lecture impossible (NoCompatibleStream).");
compare(player.error, "Lecture impossible (NoCompatibleStream).");
video.playerState = "playing";
close();
compare(events(), []);
}
function test_playerError_nothingReported() {
open(0);
prepared();
video.playerState = "error";
close();
compare(events(), []);
}
function test_ended_stopsOnceAndLeaves() {
open(0);
prepared();
play(7199000);
video.ended();
compare(navigator.pops, 1);
close();
compare(events(), ["start@7199000", "stop@7199000"], "un seul arrêt, même à la destruction");
}
// ------------------------------------------------------- télécommande
// Haut/Bas réaffichent les informations de lecture (masquées au bout de 4 s).
function test_keys_showOsd() {
open(0);
prepared();
play(100000);
player.forceActiveFocus();
var osd = findChild(player, function (o) { return o.shown !== undefined; });
verify(osd !== null, "OSD introuvable");
osd.shown = false;
keyClick(Qt.Key_Down);
verify(osd.shown);
}
function findChild(root, predicate) {
var queue = [root];
while (queue.length > 0) {
var item = queue.shift();
if (item !== root && predicate(item))
return item;
for (var i = 0; i < item.children.length; i++)
queue.push(item.children[i]);
}
return null;
}
}
}
+472
View File
@@ -0,0 +1,472 @@
import QtQuick 2.5
import QtTest 1.2
import "../../app/Core"
// Core/Session.qml : fonctions pures, puis API Jellyfin contre le faux serveur.
JellyfinTestCase {
id: testCase
name: "Session"
Session {
id: session
}
function init() {
session.cancel();
session.accessToken = "";
session.currentUser = null;
session.currentServer = null;
session.devUsers = [];
session.servers.clear();
session._quickConnectPoll.interval = 5000;
resetServer();
}
function connect() {
var result = waitCallback(function (done) {
session.connectToServer(serverHost, serverPort, done);
}, 15000, "connectToServer");
compare(result[0], null, "erreur de connexion");
return result[1];
}
function signIn(name, password) {
connect();
var result = waitCallback(function (done) {
session.authenticate(name || "alice", password === undefined ? "secret" : password, done);
});
compare(result[0], null, "erreur d'authentification");
return result[1];
}
// ------------------------------------------------------- fonctions pures
function test_serverCandidates() {
compare(session.serverCandidates("box.lan", ""),
["https://box.lan", "http://box.lan:8096", "https://box.lan:8920", "http://box.lan"]);
compare(session.serverCandidates(" box.lan/ ", ""),
["https://box.lan", "http://box.lan:8096", "https://box.lan:8920", "http://box.lan"]);
compare(session.serverCandidates("box.lan", "8100"), ["https://box.lan:8100", "http://box.lan:8100"]);
compare(session.serverCandidates("192.168.1.20:8096", ""),
["https://192.168.1.20:8096", "http://192.168.1.20:8096"]);
compare(session.serverCandidates("http://box.lan", ""), ["http://box.lan"]);
compare(session.serverCandidates("https://box.lan", "8920"), ["https://box.lan:8920"]);
compare(session.serverCandidates("https://box.lan:443", "8920"), ["https://box.lan:443"]);
compare(session.serverCandidates("", ""), []);
compare(session.serverCandidates(" ", "80"), []);
}
function test_isValidPort() {
verify(session.isValidPort("1"));
verify(session.isValidPort("8096"));
verify(session.isValidPort("65535"));
verify(!session.isValidPort("0"));
verify(!session.isValidPort("65536"));
verify(!session.isValidPort("80a"));
verify(!session.isValidPort("-1"));
verify(!session.isValidPort(""));
}
function test_query() {
compare(session._query({ a: 1, b: "", c: null, d: undefined, e: "x y&z", f: false }),
"a=1&e=x%20y%26z&f=false");
}
function test_toItem() {
var item = session._toItem({
Id: "i1", Name: "Nom", Type: "Episode", ProductionYear: 2001, RunTimeTicks: 10,
ImageTags: { Primary: "p", Thumb: "t" }, BackdropImageTags: ["b"],
ParentBackdropItemId: "pb", ParentBackdropImageTags: ["pbt"],
SeriesId: "s", SeriesName: "Série", SeriesPrimaryImageTag: "sp", SeasonId: "se",
IndexNumber: 3, ParentIndexNumber: 1, ChildCount: 2,
UserData: { PlaybackPositionTicks: 5, PlayedPercentage: 50, Played: true }
});
compare(item.id, "i1");
compare(item.imageTag, "p");
compare(item.thumbTag, "t");
compare(item.backdropTag, "b");
compare(item.parentBackdropTag, "pbt");
compare(item.seriesPrimaryTag, "sp");
compare(item.indexNumber, 3);
compare(item.parentIndexNumber, 1);
compare(item.positionTicks, 5);
compare(item.played, true);
// « index » est un rôle réservé des ListModel.
verify(!item.hasOwnProperty("index"));
var empty = session._toItem({ Id: "i2" });
compare(empty.name, "");
compare(empty.imageTag, "");
compare(empty.positionTicks, 0);
compare(empty.played, false);
compare(empty.isFolder, false);
}
function test_imageUrls() {
compare(session.imageUrl("i", "Primary", "t", 100), "", "sans serveur");
session.currentServer = { name: "S", address: "http://srv", id: "x" };
compare(session.imageUrl("i", "Primary", "t", 100), "http://srv/Items/i/Images/Primary?tag=t&maxHeight=100&quality=90");
compare(session.imageUrl("i", "Primary", "", 100), "", "sans tag");
var episode = { id: "e", type: "Episode", imageTag: "ei", seriesId: "s", seriesPrimaryTag: "sp" };
verify(session.thumbUrl(episode).indexOf("/Items/e/Images/Primary") > 0);
compare(session.posterUrl({ id: "e", imageTag: "", seriesId: "s", seriesPrimaryTag: "sp" }, 200),
"http://srv/Items/s/Images/Primary?tag=sp&maxHeight=200&quality=90");
var movie = { id: "m", type: "Movie", imageTag: "mp", thumbTag: "", backdropTag: "mb" };
verify(session.thumbUrl(movie).indexOf("/Items/m/Images/Backdrop?tag=mb") > 0, "fond à défaut de Thumb");
movie.backdropTag = "";
verify(session.thumbUrl(movie).indexOf("/Items/m/Images/Primary?tag=mp") > 0, "affiche en dernier recours");
compare(session.backdropUrl({ id: "e", backdropTag: "", parentBackdropItemId: "s", parentBackdropTag: "pb" }),
"http://srv/Items/s/Images/Backdrop?tag=pb&maxHeight=720&quality=90");
}
// ------------------------------------------------------------- serveurs
// https échoue (serveur HTTP seul) : la sonde retient http, sur le port saisi.
function test_connect_detectsProtocol() {
var server = connect();
compare(server.address, "http://" + serverHost + ":" + serverPort);
compare(server.name, "Serveur de test");
compare(server.id, "fakeserver0000000000000000000001");
compare(session.servers.count, 1);
compare(session.currentServer.address, server.address);
verify(requests("/System/Info/Public").length >= 1);
}
function test_connect_sameServerNotDuplicated() {
connect();
connect();
compare(session.servers.count, 1);
}
function test_connect_inputErrors() {
var result = waitCallback(function (done) { session.connectToServer(" ", "", done); });
compare(result[0], "Veuillez saisir l'adresse du serveur.");
result = waitCallback(function (done) { session.connectToServer("box.lan", "70000", done); });
compare(result[0], "Le port doit être un nombre entre 1 et 65535.");
compare(requests().length, 0, "aucune requête pour une saisie invalide");
}
function test_connect_unreachable() {
var result = waitCallback(function (done) { session.connectToServer("127.0.0.1", "1", done); }, 15000);
compare(result[0], "Aucun serveur Jellyfin trouvé à cette adresse.");
compare(session.servers.count, 0);
}
function test_connect_notJellyfin() {
mock({ path: "/System/Info/Public", body: { Hello: "world" } });
var result = waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000);
compare(result[0], "Aucun serveur Jellyfin trouvé à cette adresse.");
}
// ------------------------------------------------------- utilisateurs
function test_publicUsers() {
connect();
var result = waitCallback(function (done) { session.loadPublicUsers(done); });
compare(result[0], null);
compare(result[1].length, 2);
compare(result[1][0].name, "alice");
compare(result[1][0].hasPassword, true);
compare(result[1][1].hasPassword, false);
}
function test_authenticate_wrongPassword() {
connect();
var result = waitCallback(function (done) { session.authenticate("alice", "faux", done); });
compare(result[0], "Nom d'utilisateur ou mot de passe incorrect.");
compare(session.accessToken, "");
compare(session.currentUser, null);
}
function test_authenticate_emptyName() {
connect();
var result = waitCallback(function (done) { session.authenticate(" ", "x", done); });
compare(result[0], "Veuillez saisir votre nom d'utilisateur.");
compare(requests("/Users/AuthenticateByName").length, 0);
}
function test_authenticate_withoutPassword() {
var user = signIn("bob", "");
compare(user.name, "bob");
compare(lastRequest("/Users/AuthenticateByName").body.Pw, "");
}
// En-tête Authorization : identité du client, puis jeton une fois connecté.
function test_authorizationHeader() {
connect();
var anonymous = lastRequest("/System/Info/Public").auth;
verify(anonymous.indexOf('MediaBrowser Client="Jellyfin Freebox"') === 0, anonymous);
verify(anonymous.indexOf('Version="' + session.clientVersion + '"') > 0, anonymous);
verify(/DeviceId="[0-9a-f]{32}"/.test(anonymous), anonymous);
verify(anonymous.indexOf("Token=") < 0, "pas de jeton avant connexion");
var result = waitCallback(function (done) { session.authenticate("alice", "secret", done); });
compare(result[1].id, "user-alice");
compare(session.accessToken, "token-user-alice");
waitCallback(function (done) { session.loadLibraries(done); });
verify(lastRequest("/UserViews").auth.indexOf('Token="token-user-alice"') > 0);
}
function test_logout() {
signIn();
session.logout();
compare(session.accessToken, "");
compare(session.currentUser, null);
tryVerify(function () { return requests("/Sessions/Logout").length === 1; }, 3000);
verify(lastRequest("/Sessions/Logout").auth.indexOf('Token="token-user-alice"') > 0,
"la déconnexion envoie encore le jeton");
}
// --------------------------------------------------------- catalogue
function test_catalog_home() {
signIn();
var libraries = waitCallback(function (done) { session.loadLibraries(done); });
compare(libraries[0], null);
compare(libraries[1].length, 2);
compare(libraries[1][0].collectionType, "movies");
var resume = waitCallback(function (done) { session.loadResume(done); });
compare(resume[1].length, 1);
compare(resume[1][0].id, "movie-direct");
compare(resume[1][0].positionTicks, 6000000000);
compare(lastRequest("/UserItems/Resume").query.userId, "user-alice");
var latest = waitCallback(function (done) { session.loadLatest("lib-shows", done); });
compare(latest[1].length, 1);
compare(latest[1][0].type, "Series");
}
function test_catalog_libraryPaging() {
signIn();
var page = waitCallback(function (done) {
session.loadLibraryItems({ id: "lib-movies", collectionType: "movies" }, 20, 10, done);
});
compare(page[0], null);
compare(page[1].length, 5);
compare(page[2], 25);
var query = lastRequest("/Items").query;
compare(query.includeItemTypes, "Movie");
compare(query.startIndex, "20");
compare(query.recursive, "true");
waitCallback(function (done) {
session.loadLibraryItems({ id: "lib-shows", collectionType: "tvshows" }, 0, 10, done);
});
compare(lastRequest("/Items").query.includeItemTypes, "Series");
waitCallback(function (done) {
session.loadLibraryItems({ id: "x", collectionType: "homevideos" }, 0, 10, done);
});
compare(lastRequest("/Items").query.includeItemTypes, "Movie,Series,Video");
}
function test_catalog_series() {
signIn();
var item = waitCallback(function (done) { session.loadItem("series-1", done); });
compare(item[1].name, "Série test");
var seasons = waitCallback(function (done) { session.loadSeasons("series-1", done); });
compare(seasons[1].length, 2);
var episodes = waitCallback(function (done) { session.loadEpisodes("series-1", "season-1", done); });
compare(episodes[1].length, 2);
compare(episodes[1][1].indexNumber, 2);
compare(lastRequest("/Shows/series-1/Episodes").query.fields, "Overview");
}
// ------------------------------------------------------------ erreurs
function test_errors_messages() {
signIn();
mock({ path: "/UserViews", status: 500 });
var result = waitCallback(function (done) { session.loadLibraries(done); });
compare(result[0], "Erreur du serveur (500).");
compare(result[1], []);
mock({ path: "/UserItems/Resume", raw: "<html>pas du JSON</html>" });
result = waitCallback(function (done) { session.loadResume(done); });
compare(result[0], "Réponse inattendue du serveur.");
mock({ path: "/Items/nope", status: 404 });
result = waitCallback(function (done) { session.loadItem("nope", done); });
compare(result[0], "Erreur du serveur (404).");
compare(result[1], null);
}
function test_errors_expiredToken() {
signIn();
session.accessToken = "jeton-expire";
var result = waitCallback(function (done) { session.loadLibraries(done); });
compare(result[0], "Erreur du serveur (401).");
}
// Qt 5.5 n'a pas de timeout XHR : Session utilise un Timer par requête.
function test_request_timeout() {
mock({ path: "/System/Info/Public", delay: 2000, body: {} });
var result = waitCallback(function (done) {
session._request("GET", "/System/Info/Public", null, done, { baseUrl: serverUrl, timeout: 300 });
}, 1500);
compare(result[0].kind, "timeout");
}
function test_request_network() {
var result = waitCallback(function (done) {
session._request("GET", "/x", null, done, { baseUrl: "http://127.0.0.1:1", timeout: 5000 });
}, 6000);
compare(result[0].kind, "network");
}
// 204 sans corps : succès avec des données nulles (pas d'erreur de JSON).
function test_request_emptyBody() {
signIn();
var result = waitCallback(function (done) {
session._request("POST", "/Sessions/Logout", null, done);
});
compare(result[0], null);
compare(result[1], null);
}
// Un écran détruit appelle cancel() : ses callbacks en attente ne doivent jamais arriver.
function test_cancel_dropsPendingCallbacks() {
signIn();
mock({ path: "/UserViews", delay: 400, body: { Items: [] } });
var called = false;
session.loadLibraries(function () { called = true; });
session.cancel();
wait(900);
verify(!called, "callback appelé après cancel()");
// Les appels suivants fonctionnent normalement.
var result = waitCallback(function (done) { session.loadResume(done); });
compare(result[0], null);
}
// ------------------------------------------------------------- lecture
function test_playback_directPlay() {
signIn();
var result = waitCallback(function (done) { session.preparePlayback("movie-direct", done); });
compare(result[0], null);
var info = result[1];
compare(info.playMethod, "DirectPlay");
compare(info.mediaSourceId, "src-movie-direct");
compare(info.playSessionId, "play-movie-direct");
verify(info.url.indexOf(session.currentServer.address + "/Videos/movie-direct/stream?") === 0, info.url);
verify(info.url.indexOf("static=true") > 0, info.url);
verify(info.url.indexOf("api_key=token-user-alice") > 0, info.url);
var request = lastRequest("/Items/movie-direct/PlaybackInfo");
compare(request.method, "POST");
compare(request.query.userId, "user-alice");
// -1 : sinon Jellyfin transcode pour incruster les sous-titres.
compare(request.body.SubtitleStreamIndex, -1);
compare(request.body.DeviceProfile.Name, "Freebox Player");
verify(request.body.MaxStreamingBitrate > 0);
}
function test_playback_transcode() {
signIn();
var info = waitCallback(function (done) { session.preparePlayback("movie-transcode", done); })[1];
compare(info.playMethod, "Transcode");
compare(info.url, session.currentServer.address
+ "/videos/movie-transcode/master.m3u8?MediaSourceId=src-movie-transcode&PlaySessionId=play-movie-transcode");
}
function test_playback_errors() {
signIn();
var result = waitCallback(function (done) { session.preparePlayback("movie-broken", done); });
compare(result[0], "Lecture impossible (NoCompatibleStream).");
mock({ path: "/Items/movie-01/PlaybackInfo",
body: { PlaySessionId: "p", MediaSources: [{ Id: "s", SupportsDirectPlay: false,
SupportsDirectStream: false, SupportsTranscoding: false }] } });
result = waitCallback(function (done) { session.preparePlayback("movie-01", done); });
compare(result[0], "Ce média ne peut pas être lu sur la Freebox.");
}
function test_reportPlayback() {
signIn();
var info = { itemId: "movie-01", mediaSourceId: "src", playSessionId: "ps", playMethod: "Transcode" };
session.reportPlayback("start", info, 0, false);
session.reportPlayback("progress", info, 61000.7, true);
session.reportPlayback("stop", info, 62000, false);
tryVerify(function () { return requests("/Sessions/Playing/Stopped").length === 1; }, 3000);
var progress = lastRequest("/Sessions/Playing/Progress").body;
compare(progress.PositionTicks, 610007000);
compare(progress.IsPaused, true);
compare(progress.PlaySessionId, "ps");
compare(progress.PlayMethod, "Transcode");
compare(requests("/Sessions/Playing").length, 1);
compare(lastRequest("/Sessions/Playing/Stopped").body.PositionTicks, 620000000);
}
// ------------------------------------------------------- Quick Connect
function test_quickConnect() {
connect();
compare(waitCallback(function (done) { session.isQuickConnectEnabled(done); })[1], true);
session._quickConnectPoll.interval = 50;
var code = null;
var signedIn = null;
session.startQuickConnect(function (err, value) { code = err || value; },
function (err, user) { signedIn = err || user; });
tryVerify(function () { return code !== null; }, 3000);
compare(code, "123456");
wait(200);
compare(signedIn, null, "pas de connexion avant autorisation");
http("POST", "/__quickconnect/authorize");
tryVerify(function () { return signedIn !== null; }, 3000);
compare(signedIn.name, "alice");
compare(session.accessToken, "token-user-alice");
}
function test_quickConnect_stop() {
connect();
session._quickConnectPoll.interval = 50;
var signedIn = false;
var code = waitCallback(function (done) {
session.startQuickConnect(done, function () { signedIn = true; });
});
compare(code[1], "123456");
session.stopQuickConnect();
http("POST", "/__quickconnect/authorize");
wait(400);
verify(!signedIn);
compare(requests("/Users/AuthenticateWithQuickConnect").length, 0);
}
function test_quickConnect_disabled() {
connect();
mock({ path: "/QuickConnect/Initiate", status: 401 });
var result = waitCallback(function (done) { session.startQuickConnect(done, function () {}); });
compare(result[0], "Quick Connect est désactivé sur ce serveur.");
mock({ path: "/QuickConnect/Enabled", body: false });
compare(waitCallback(function (done) { session.isQuickConnectEnabled(done); })[1], false);
}
// ----------------------------------------------------------- dev-config
function test_devConfig() {
session.loadDevConfig(serverUrl + "/dev-config.json");
tryVerify(function () { return session.servers.count === 1; }, 15000);
compare(session.servers.get(0).address, "http://" + serverHost + ":" + serverPort);
compare(session.devUsers.length, 1);
compare(session.devUsers[0].name, "carol");
}
function test_devConfig_ignoredFromDisk() {
session.loadDevConfig("file:///tmp/dev-config.json");
wait(200);
compare(requests().length, 0);
compare(session.servers.count, 0);
}
function test_devConfig_missing() {
mock({ path: "/dev-config.json", status: 404 });
session.loadDevConfig(serverUrl + "/dev-config.json");
tryVerify(function () { return requests("/dev-config.json").length === 1; }, 3000);
wait(200);
compare(session.servers.count, 0);
compare(session.devUsers.length, 0);
}
}
+2 -2
View File
@@ -1,13 +1,13 @@
import QtQuick 2.5 import QtQuick 2.5
import QtQuick.Window 2.2 import QtQuick.Window 2.2
// Aperçu sur PC : charge Jellyfin.qml puis repasse la fenêtre en 1280x720 // Aperçu sur PC : charge app/Jellyfin.qml puis repasse la fenêtre en 1280x720
// (fbx.application.Application force le plein écran au démarrage). // (fbx.application.Application force le plein écran au démarrage).
QtObject { QtObject {
property var app: null property var app: null
Component.onCompleted: { Component.onCompleted: {
var component = Qt.createComponent("../Jellyfin.qml"); var component = Qt.createComponent("../app/Jellyfin.qml");
if (component.status === Component.Error) { if (component.status === Component.Error) {
console.error(component.errorString()); console.error(component.errorString());
Qt.quit(); Qt.quit();
-17
View File
@@ -1,17 +0,0 @@
#!/usr/bin/env bash
# Lance l'application sur le PC avec qmlscene (Qt 5) et libfbxqml.
# Usage : tools/run-local.sh [--fullscreen]
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
LIBFBXQML="${LIBFBXQML:-$ROOT/../libfbxqml}"
QMLSCENE="${QMLSCENE:-$(command -v qmlscene || echo /usr/lib/qt5/bin/qmlscene)}"
if [ ! -d "$LIBFBXQML/fbx" ]; then
echo "libfbxqml introuvable : git clone https://github.com/fbx/libfbxqml.git \"$LIBFBXQML\"" >&2
exit 1
fi
if [ "${1:-}" = "--fullscreen" ]; then
exec "$QMLSCENE" -I "$LIBFBXQML" "$ROOT/Jellyfin.qml"
fi
exec "$QMLSCENE" -I "$LIBFBXQML" "$ROOT/tools/preview.qml"
Generated
+8
View File
@@ -0,0 +1,8 @@
version = 1
revision = 3
requires-python = ">=3.14"
[[package]]
name = "freebox-jellyfin"
version = "0.1.0"
source = { editable = "." }