Refactoring, create a src folders with the python toolchain
This commit is contained in:
1 parent
2790d92a60
commit
33e4fe0c4e
19 files changed
+246
-122
No files matched your search
@@ -1,53 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Charge l'application comme le fait 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.
|
||||
#
|
||||
# Usage : tools/check-load.sh (LIBFBXQML=… pour un autre emplacement de libfbxqml)
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
LIBFBXQML="${LIBFBXQML:-$ROOT/../libfbxqml}"
|
||||
QMLSCENE="${QMLSCENE:-$(command -v qmlscene || echo /usr/lib/qt5/bin/qmlscene)}"
|
||||
DURATION="${DURATION:-6}"
|
||||
|
||||
if [ ! -d "$LIBFBXQML/fbx" ]; then
|
||||
echo "libfbxqml introuvable : git clone https://github.com/fbx/libfbxqml.git \"$LIBFBXQML\"" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
WORK="$(mktemp -d)"
|
||||
trap 'kill "$SERVER_PID" 2>/dev/null || true; rm -rf "$WORK"' EXIT
|
||||
|
||||
# Serveur HTTP sur un port libre (choisi par le système).
|
||||
python3 -I - "$ROOT" > "$WORK/port" <<'EOF' &
|
||||
import functools, http.server, sys
|
||||
class Quiet(http.server.SimpleHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Quiet, directory=sys.argv[1]))
|
||||
print(server.server_address[1], flush=True)
|
||||
server.serve_forever()
|
||||
EOF
|
||||
SERVER_PID=$!
|
||||
for _ in $(seq 50); do [ -s "$WORK/port" ] && break; sleep 0.1; done
|
||||
PORT="$(cat "$WORK/port")"
|
||||
|
||||
echo "Chargement de http://127.0.0.1:$PORT/Jellyfin.qml pendant ${DURATION} s…"
|
||||
# Rendu logiciel : la CI (conteneur) n'a pas d'OpenGL.
|
||||
mkdir -p "$WORK/runtime" && chmod 700 "$WORK/runtime"
|
||||
XDG_RUNTIME_DIR="$WORK/runtime" QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software \
|
||||
timeout "$DURATION" "$QMLSCENE" -I "$LIBFBXQML" \
|
||||
"http://127.0.0.1:$PORT/Jellyfin.qml" > "$WORK/output" 2>&1 || true
|
||||
|
||||
# Messages attendus hors de la box : Settings de libfbxqml (pas d'objet App sur PC).
|
||||
grep -v -e "/libfbxqml/" -e "^qml: Setting" -e "^qml: Getting settings failed" -e "^\s*$" \
|
||||
"$WORK/output" > "$WORK/problems" || true
|
||||
|
||||
if [ -s "$WORK/problems" ]; then
|
||||
echo "Échec : messages inattendus au chargement :" >&2
|
||||
cat "$WORK/problems" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "OK : chargement sans erreur."
|
||||
-216
@@ -1,216 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lance l'application sur un Freebox Player en mode développeur.
|
||||
|
||||
Reproduit le « Run » du plugin QtCreator Freebox (github.com/fbx/freebox-qtcreator-plugin) :
|
||||
1. trouve le Player sur le réseau local (SSDP, type « fbx:devel ») ou utilise --box ;
|
||||
2. sert le dossier du projet en HTTP (le Player y télécharge manifest.json et les QML) ;
|
||||
3. appelle la méthode JSON-RPC « debug_qml_app » sur http://<box>/pub/devel ;
|
||||
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]
|
||||
--server : l'app ajoute ce serveur au démarrage (utile car la box n'enregistre rien en mode développement).
|
||||
--user nom[:mot_de_passe] : compte proposé sur « Qui regarde ? » (le mot de passe transite en clair sur le réseau local).
|
||||
La sortie est aussi écrite dans deploy.log (racine du projet), écrasé à chaque lancement.
|
||||
"""
|
||||
import argparse
|
||||
import functools
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import selectors
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SSDP_ADDR = ("239.255.255.250", 1900)
|
||||
SSDP_TYPE = "fbx:devel"
|
||||
|
||||
|
||||
def discover(timeout=3.0):
|
||||
"""Renvoie l'adresse IP du premier Player en mode développeur qui répond."""
|
||||
request = (
|
||||
"M-SEARCH * HTTP/1.1\r\n"
|
||||
"HOST: 239.255.255.250:1900\r\n"
|
||||
'MAN: "ssdp:discover"\r\n'
|
||||
"MX: 1\r\n"
|
||||
"ST: %s\r\n\r\n" % SSDP_TYPE
|
||||
).encode()
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
sock.sendto(request, SSDP_ADDR)
|
||||
while True:
|
||||
data, (addr, _) = sock.recvfrom(4096)
|
||||
headers = data.decode(errors="replace").lower()
|
||||
if "st: %s" % SSDP_TYPE in headers or "nt: %s" % SSDP_TYPE in headers:
|
||||
return addr
|
||||
except socket.timeout:
|
||||
return None
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
|
||||
def local_ip_towards(box):
|
||||
"""Adresse de ce PC vue depuis le Player (interface utilisée pour le joindre)."""
|
||||
with socket.create_connection((box, 80), timeout=3) as sock:
|
||||
return sock.getsockname()[0]
|
||||
|
||||
|
||||
DEV_CONFIG_PATH = "/dev-config.json"
|
||||
|
||||
|
||||
class QuietHandler(http.server.SimpleHTTPRequestHandler):
|
||||
verbose = False
|
||||
dev_config = None # dict servi sur DEV_CONFIG_PATH (jamais écrit sur disque)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.split("?")[0] == DEV_CONFIG_PATH and self.dev_config is not None:
|
||||
body = json.dumps(self.dev_config).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
super().do_GET()
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
if self.verbose:
|
||||
sys.stderr.write("[http] %s\n" % (fmt % args))
|
||||
|
||||
|
||||
def serve_project(bind_ip, verbose, dev_config=None):
|
||||
QuietHandler.verbose = verbose
|
||||
QuietHandler.dev_config = dev_config
|
||||
handler = functools.partial(QuietHandler, directory=PROJECT_DIR)
|
||||
server = http.server.ThreadingHTTPServer((bind_ip, 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
def json_rpc(box, method, params):
|
||||
body = json.dumps({"jsonrpc": "2.0", "method": method, "params": params, "id": "0"}).encode()
|
||||
request = urllib.request.Request(
|
||||
"http://%s/pub/devel" % box, data=body, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=15) as reply:
|
||||
answer = json.load(reply)
|
||||
if "error" in answer:
|
||||
raise RuntimeError(answer["error"].get("message", answer["error"]))
|
||||
return answer.get("result", {})
|
||||
|
||||
|
||||
def stream_output(box, stdout_port, stderr_port):
|
||||
"""Affiche la sortie de l'app ; se termine quand le Player ferme stdout (app quittée)."""
|
||||
selector = selectors.DefaultSelector()
|
||||
streams = {}
|
||||
for port, target in ((stdout_port, sys.stdout), (stderr_port, sys.stderr)):
|
||||
if port:
|
||||
sock = socket.create_connection((box, port), timeout=5)
|
||||
sock.settimeout(None)
|
||||
selector.register(sock, selectors.EVENT_READ)
|
||||
streams[sock] = target
|
||||
while streams:
|
||||
for key, _ in selector.select():
|
||||
sock = key.fileobj
|
||||
data = sock.recv(4096)
|
||||
if not data:
|
||||
selector.unregister(sock)
|
||||
sock.close()
|
||||
if streams.pop(sock) is sys.stdout:
|
||||
return
|
||||
continue
|
||||
streams[sock].write(data.decode(errors="replace"))
|
||||
streams[sock].flush()
|
||||
|
||||
|
||||
class Tee:
|
||||
"""Duplique un flux (stdout/stderr) dans le fichier de log."""
|
||||
|
||||
def __init__(self, stream, log):
|
||||
self.stream = stream
|
||||
self.log = log
|
||||
|
||||
def write(self, text):
|
||||
self.stream.write(text)
|
||||
self.stream.flush()
|
||||
self.log.write(text)
|
||||
self.log.flush()
|
||||
|
||||
def flush(self):
|
||||
self.stream.flush()
|
||||
self.log.flush()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--box", help="adresse IP du Player (sinon découverte SSDP)")
|
||||
parser.add_argument("--entry", default="main", help="entry point du manifest.json (défaut : main)")
|
||||
parser.add_argument("--verbose", action="store_true", help="affiche les fichiers téléchargés par le Player")
|
||||
parser.add_argument("--server", action="append", default=[], metavar="ADRESSE",
|
||||
help="serveur Jellyfin ajouté automatiquement par l'app au démarrage "
|
||||
"(ex. media.stilobique.com ; option répétable)")
|
||||
parser.add_argument("--user", action="extend", nargs="+", default=[], metavar="NOM[:MOT_DE_PASSE]",
|
||||
help="compte(s) affiché(s) sur l'écran « Qui regarde ? » ; avec mot de passe, "
|
||||
"connexion en un clic (ex. --user alice:mdp bob, ou --user répété)")
|
||||
parser.add_argument("--log", default=os.path.join(PROJECT_DIR, "deploy.log"),
|
||||
help="fichier de log, écrasé à chaque lancement (défaut : deploy.log ; vide pour désactiver)")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.log:
|
||||
log = open(args.log, "w", encoding="utf-8")
|
||||
log.write("# deploy.py %s\n" % time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
sys.stdout = Tee(sys.stdout, log)
|
||||
sys.stderr = Tee(sys.stderr, log)
|
||||
|
||||
box = args.box
|
||||
if not box:
|
||||
print("Recherche d'un Freebox Player en mode développeur…")
|
||||
box = discover()
|
||||
if not box:
|
||||
sys.exit("Aucun Player trouvé. Vérifiez le mode développeur, ou passez --box <IP>.")
|
||||
print("Player : %s" % box)
|
||||
|
||||
try:
|
||||
me = local_ip_towards(box)
|
||||
except OSError as error:
|
||||
sys.exit("Impossible de joindre %s:80 (%s)." % (box, error))
|
||||
|
||||
users = []
|
||||
for spec in args.user:
|
||||
name, sep, password = spec.partition(":")
|
||||
users.append({"name": name, "password": password} if sep else {"name": name})
|
||||
dev_config = {"servers": args.server, "users": users} if (args.server or users) else None
|
||||
server = serve_project(me, args.verbose, dev_config)
|
||||
port = server.server_address[1]
|
||||
manifest_url = "http://%s:%d/manifest.json" % (me, port)
|
||||
print("Projet servi sur %s" % manifest_url)
|
||||
if args.server:
|
||||
print("Serveurs de test proposés à l'app : %s" % ", ".join(args.server))
|
||||
if users: # les mots de passe ne sont jamais affichés
|
||||
print("Utilisateurs de test : %s" % ", ".join(
|
||||
u["name"] + (" (mot de passe fourni)" if "password" in u else "") for u in users))
|
||||
|
||||
try:
|
||||
result = json_rpc(box, "debug_qml_app", {
|
||||
"manifest_url": manifest_url,
|
||||
"entry_point": args.entry,
|
||||
"wait": False,
|
||||
})
|
||||
print("Application lancée. Ctrl+C pour arrêter.\n")
|
||||
stream_output(box, result.get("stdout_port"), result.get("stderr_port"))
|
||||
print("\nApplication fermée sur le Player.")
|
||||
except KeyboardInterrupt:
|
||||
print("\nArrêt.")
|
||||
except Exception as error: # erreurs réseau ou JSON-RPC : message lisible
|
||||
sys.exit("Échec du lancement : %s" % error)
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,150 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""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 (tools/ est exclu : l'aperçu 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é) ;
|
||||
- archive tar (format ustar, avec les entrées de dossiers) compressée en gzip.
|
||||
|
||||
Usage : tools/package.py [--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
|
||||
|
||||
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# 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"}
|
||||
EXCLUDED_DIRS = {"tools", "dist"}
|
||||
|
||||
|
||||
def collect_files():
|
||||
files = []
|
||||
for root, dirs, names in os.walk(PROJECT_DIR):
|
||||
rel_root = os.path.relpath(root, PROJECT_DIR)
|
||||
# Dossiers cachés (.git, .idea…) et dossiers d'outillage exclus.
|
||||
dirs[:] = sorted(d for d in dirs if not d.startswith(".")
|
||||
and not (rel_root == "." and d in EXCLUDED_DIRS))
|
||||
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(PROJECT_DIR, "manifest.json")
|
||||
if not os.path.exists(path):
|
||||
raise ValueError("manifest.json manquant")
|
||||
manifest = json.load(open(path, encoding="utf-8"))
|
||||
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.
|
||||
session = open(os.path.join(PROJECT_DIR, "Core", "Session.qml"), encoding="utf-8").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"):
|
||||
json.load(open(os.path.join(PROJECT_DIR, name), encoding="utf-8"))
|
||||
qmllint = shutil.which("qmllint")
|
||||
if not qmllint:
|
||||
print("Attention : qmllint introuvable, syntaxe QML/JS non vérifiée.")
|
||||
return
|
||||
sources = [os.path.join(PROJECT_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))
|
||||
data = open(os.path.join(PROJECT_DIR, name), "rb").read()
|
||||
archive.addfile(info(name.replace(os.sep, "/"), False, len(data)), io.BytesIO(data))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--output", help="archive à créer (défaut : dist/<identifier>-<version>.tar.gz)")
|
||||
args = parser.parse_args()
|
||||
|
||||
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(
|
||||
PROJECT_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).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user