Add test suite (box rules, Python, QML against a fake Jellyfin server) and local preview jobs
- 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>
This commit is contained in:
1 parent
d0d019ac1e
commit
1b2acae316
19 files changed
+2097
-17
No files matched your search
@@ -2,12 +2,14 @@
|
||||
|
||||
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", "package", "deploy")
|
||||
COMMANDS = ("preview", "check", "test", "fake-server", "package", "deploy")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
@@ -22,6 +24,10 @@ def main(argv=None):
|
||||
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:
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -5,8 +5,8 @@ Reproduit « Outils > Freebox SDK > Make FreeStore Package » du plugin QtCreato
|
||||
- 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,
|
||||
syntaxe QML/JS (qmllint, s'il est installé) ;
|
||||
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]
|
||||
@@ -22,6 +22,7 @@ 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)
|
||||
@@ -48,7 +49,8 @@ def check_manifest(files):
|
||||
path = os.path.join(APP_DIR, "manifest.json")
|
||||
if not os.path.exists(path):
|
||||
raise ValueError("manifest.json manquant")
|
||||
manifest = json.load(open(path, encoding="utf-8"))
|
||||
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)")
|
||||
@@ -73,7 +75,8 @@ def check_manifest(files):
|
||||
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.
|
||||
session = open(os.path.join(APP_DIR, "Core", "Session.qml"), encoding="utf-8").read()
|
||||
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)"
|
||||
@@ -87,7 +90,11 @@ def check_manifest(files):
|
||||
def check_sources(files):
|
||||
for name in files:
|
||||
if name.endswith(".json"):
|
||||
json.load(open(os.path.join(APP_DIR, name), encoding="utf-8"))
|
||||
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.")
|
||||
@@ -120,7 +127,8 @@ def build_archive(files, output):
|
||||
if directory not in seen_dirs:
|
||||
seen_dirs.add(directory)
|
||||
archive.addfile(info(directory, True))
|
||||
data = open(os.path.join(APP_DIR, name), "rb").read()
|
||||
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))
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""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
|
||||
|
||||
@@ -9,7 +11,27 @@ 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"
|
||||
os.execv(scene, [scene, "-I", str(lib), str(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()
|
||||
@@ -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
|
||||
Reference in new issue
Block a user