Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10574ba0c5 | ||
|
|
ace2e486fc | ||
|
|
c008c22e09 | ||
|
|
bf606c23d1 | ||
|
|
1898e8b1ae | ||
|
|
e77ad85be9 | ||
|
|
11939fe39e | ||
|
|
8958822545 | ||
|
|
007bcce8a7 | ||
|
|
a985bbd018 | ||
|
|
1c9ac524db | ||
|
|
abf66733fe | ||
|
|
763219412b | ||
|
|
cccf2b85db | ||
|
|
6ae9238fee | ||
|
|
0ef1380265 | ||
|
|
9a7e93b162 | ||
|
|
106754fd77 | ||
|
|
0c0581e894 | ||
|
|
dae0508c93 | ||
|
|
cbd59a5bd9 | ||
|
|
d759bc8131 | ||
|
|
ac7648f9fe | ||
|
|
d9a90f8412 | ||
|
|
2e9632de49 | ||
|
|
fbb1956e17 | ||
|
|
8c6b642975 | ||
|
|
d926545e3d | ||
|
|
b323c681f8 | ||
|
|
e7063b31e3 | ||
|
|
ab658f27b0 | ||
|
|
c2947cfef8 | ||
|
|
67ac4cc68f | ||
|
|
c2f162d823 | ||
|
|
ad3ea0e9e6 | ||
|
|
0c44e42a22 | ||
|
|
1c8b24c5dd | ||
|
|
177967af55 | ||
|
|
42c4b53ced | ||
|
|
3e9e828225 | ||
|
|
51eb907078 | ||
|
|
9f0359d8c0 | ||
|
|
587e0fe097 |
@@ -82,9 +82,11 @@ jobs:
|
|||||||
if: failure()
|
if: failure()
|
||||||
run: docker compose -f docker-compose.yml -f docker-compose.e2e.yml logs --no-color
|
run: docker compose -f docker-compose.yml -f docker-compose.e2e.yml logs --no-color
|
||||||
|
|
||||||
|
# v3 obligatoire : l'API artifacts v4 n'est pas supportée par Gitea
|
||||||
|
# (GHESNotSupportedError — constaté sur le job MegaLinter).
|
||||||
- name: Upload Playwright report
|
- name: Upload Playwright report
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: playwright-report
|
name: playwright-report
|
||||||
path: web/playwright-report/
|
path: web/playwright-report/
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
name: Qualité & Sécurité
|
||||||
|
|
||||||
|
# Analyse statique (MegaLinter, config racine .mega-linter.yml) + CVE des
|
||||||
|
# dépendances (Trivy). Workflow SÉPARÉ de ci.yml : un rouge qualité ne bloque
|
||||||
|
# pas la chaîne tests → release pendant la phase de rodage. Une fois la base
|
||||||
|
# assainie, on pourra l'ajouter aux checks requis de la branch protection.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
# beta inclus : c'est la branche de dev, le feedback qualité doit y vivre
|
||||||
|
# (ci.yml/e2e.yml, eux, restent volontairement sur main + PR).
|
||||||
|
branches: [main, beta]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
megalinter:
|
||||||
|
name: MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# Historique complet : requis par gitleaks (scan de l'historique)
|
||||||
|
# et par le mode "fichiers modifiés seulement" en PR.
|
||||||
|
fetch-depth: 0
|
||||||
|
# Flavor "cupcake" : image allégée couvrant les langages courants
|
||||||
|
# (Java/Python/TS inclus). Si un linter activé manquait à la flavor,
|
||||||
|
# MegaLinter échoue en l'indiquant → remplacer par oxsecurity/megalinter@v9
|
||||||
|
# (image complète, plus lourde).
|
||||||
|
- name: MegaLinter
|
||||||
|
uses: oxsecurity/megalinter/flavors/cupcake@v9
|
||||||
|
env:
|
||||||
|
# main → scan complet du dépôt ; beta et PR → seulement les fichiers
|
||||||
|
# modifiés par rapport à main (rapide, feedback ciblé).
|
||||||
|
VALIDATE_ALL_CODEBASE: ${{ github.ref == 'refs/heads/main' }}
|
||||||
|
# v3 obligatoire : l'API artifacts v4 (@actions/artifact 2.x) n'est pas
|
||||||
|
# supportée par Gitea (GHESNotSupportedError constaté avec v4).
|
||||||
|
- name: Publier les rapports
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: megalinter-reports
|
||||||
|
path: megalinter-reports/
|
||||||
|
|
||||||
|
web-lint:
|
||||||
|
name: Web (ESLint · angular-eslint + sonarjs)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: web/package-lock.json
|
||||||
|
- name: npm ci
|
||||||
|
working-directory: web
|
||||||
|
run: npm ci --no-audit --no-fund
|
||||||
|
# Lint via la toolchain du projet (et non via MegaLinter : ESLint a
|
||||||
|
# besoin des plugins de web/node_modules et du contexte Angular).
|
||||||
|
# Config + règles : web/eslint.config.js (sonarjs = règles "à la Sonar").
|
||||||
|
- name: ng lint
|
||||||
|
working-directory: web
|
||||||
|
run: npm run lint
|
||||||
|
|
||||||
|
trivy:
|
||||||
|
name: Trivy (CVE dépendances Maven / pip / npm)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
# Pour résoudre pom.xml (versions héritées du parent Spring Boot), Trivy
|
||||||
|
# télécharge les BOMs depuis Maven Central — qui finit par rate-limiter
|
||||||
|
# l'IP du runner (429). Parade officielle : peupler ~/.m2 AVANT le scan,
|
||||||
|
# Trivy lit le cache local en priorité. Le cache setup-java (clé pom.xml)
|
||||||
|
# rend l'étape quasi gratuite d'un run à l'autre.
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '17'
|
||||||
|
cache: maven
|
||||||
|
- name: Précharger le cache Maven (~/.m2)
|
||||||
|
working-directory: core
|
||||||
|
run: |
|
||||||
|
chmod +x ./mvnw
|
||||||
|
./mvnw -B -q dependency:go-offline
|
||||||
|
- name: Installer Trivy
|
||||||
|
run: curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
|
||||||
|
# Scanne les manifestes du dépôt (pom.xml, requirements*.txt,
|
||||||
|
# package-lock.json) contre les bases CVE. --ignore-unfixed : on ne
|
||||||
|
# bloque que sur les vulnérabilités qui ONT un correctif publié.
|
||||||
|
# --offline-scan : AUCUNE requête vers Maven Central pendant la
|
||||||
|
# résolution — Trivy allait y chercher les POMs parents même avec le
|
||||||
|
# cache rempli, et l'IP du runner finissait rate-limitée (429, 30 min).
|
||||||
|
# Tout est déjà dans ~/.m2 grâce au dependency:go-offline ci-dessus ;
|
||||||
|
# contrepartie : une dépendance absente du cache serait ignorée en
|
||||||
|
# silence (impossible ici, go-offline échouerait d'abord).
|
||||||
|
- name: Scan des dépendances (HIGH/CRITICAL bloquants)
|
||||||
|
run: |
|
||||||
|
trivy fs . \
|
||||||
|
--scanners vuln \
|
||||||
|
--severity HIGH,CRITICAL \
|
||||||
|
--ignore-unfixed \
|
||||||
|
--offline-scan \
|
||||||
|
--skip-dirs node_modules \
|
||||||
|
--skip-dirs docusaurus \
|
||||||
|
--exit-code 1
|
||||||
@@ -47,7 +47,7 @@ jobs:
|
|||||||
|
|
||||||
# Detection du canal :
|
# Detection du canal :
|
||||||
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
|
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
|
||||||
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR prives
|
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR publics
|
||||||
# loremind-beta-<component> ; backup Gitea avec :version)
|
# loremind-beta-<component> ; backup Gitea avec :version)
|
||||||
- name: Extract version & channel
|
- name: Extract version & channel
|
||||||
id: meta
|
id: meta
|
||||||
@@ -74,8 +74,8 @@ jobs:
|
|||||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||||
|
|
||||||
# Build & push canal BETA
|
# Build & push canal BETA
|
||||||
# GHCR : repos prives loremind-beta-<component> (gated par PAT distribue
|
# GHCR : repos PUBLICS loremind-beta-<component> (canal beta libre ;
|
||||||
# via le relais Patreon aux tiers Compagnon).
|
# le switcher bascule IMAGE_NAMESPACE vers ce prefixe).
|
||||||
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne
|
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne
|
||||||
# pas faire upgrader les installs branchees sur Gitea).
|
# pas faire upgrader les installs branchees sur Gitea).
|
||||||
- name: Build & push ${{ matrix.component }} (beta)
|
- name: Build & push ${{ matrix.component }} (beta)
|
||||||
|
|||||||
@@ -12,12 +12,10 @@ name: Desktop installers
|
|||||||
# inclus) pour que le tag declenche ce workflow.
|
# inclus) pour que le tag declenche ce workflow.
|
||||||
#
|
#
|
||||||
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
||||||
# Tag beta vX.Y.Z-beta* -> AUCUNE publication publique. Le .msi est depose en
|
# Tag beta vX.Y.Z-beta* -> GitHub Release PUBLIQUE marquee « pre-release » : le
|
||||||
# ARTEFACT PRIVE du run (telechargeable seulement par
|
# canal beta est libre. /releases/latest l'ignore, donc
|
||||||
# toi via l'onglet Actions) ; tu le joins ensuite a un
|
# seules les installations beta en sont prevenues
|
||||||
# post Patreon reserve a un palier. Patreon = la
|
# (cf. DesktopUpdateService).
|
||||||
# barriere d'acces (equivalent du registry prive +
|
|
||||||
# relais pour les images Docker beta).
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -106,6 +104,10 @@ jobs:
|
|||||||
windows:
|
windows:
|
||||||
needs: tests
|
needs: tests
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
|
# Reprises par le job `publish` (tag de la release, statut pre-release).
|
||||||
|
outputs:
|
||||||
|
tag: ${{ steps.ver.outputs.tag }}
|
||||||
|
isbeta: ${{ steps.ver.outputs.isbeta }}
|
||||||
steps:
|
steps:
|
||||||
# En declenchement manuel, on checkout le TAG correspondant a la version
|
# En declenchement manuel, on checkout le TAG correspondant a la version
|
||||||
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
||||||
@@ -169,33 +171,20 @@ jobs:
|
|||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||||
|
|
||||||
# STABLE uniquement : Release GitHub publique avec le .msi.
|
# Le .msi est passe au job `publish`, seul a creer la release.
|
||||||
# tag_name explicite : en declenchement manuel, github.ref est une branche,
|
- name: Keep installer for the release
|
||||||
# donc on cible le tag derive (la release est attachee au bon tag).
|
|
||||||
- name: Publish installer to GitHub Release (stable)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
tag_name: ${{ steps.ver.outputs.tag }}
|
|
||||||
files: core/target/dist-out/*.msi
|
|
||||||
fail_on_unmatched_files: true
|
|
||||||
generate_release_notes: true
|
|
||||||
|
|
||||||
# BETA uniquement : artefact PRIVE (pas de release publique). A recuperer
|
|
||||||
# via l'onglet Actions puis a joindre a un post Patreon gate par palier.
|
|
||||||
- name: Upload installer as private artifact (beta)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: loremind-beta-${{ steps.ver.outputs.version }}-msi
|
name: installer-windows
|
||||||
path: core/target/dist-out/*.msi
|
path: core/target/dist-out/*.msi
|
||||||
retention-days: 90
|
if-no-files-found: error
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
||||||
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
||||||
# Brain empaquete via python-build-standalone (pas de Python embeddable Linux
|
# Brain empaquete via python-build-standalone (pas de Python embeddable Linux
|
||||||
# officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de
|
# officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de
|
||||||
# publication que windows : stable -> release publique ; beta -> artefact prive.
|
# publication que windows : stable -> release publique ; beta -> pre-release.
|
||||||
linux:
|
linux:
|
||||||
needs: tests
|
needs: tests
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -242,21 +231,40 @@ jobs:
|
|||||||
GITHUB_TOKEN: ${{ github.token }}
|
GITHUB_TOKEN: ${{ github.token }}
|
||||||
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
||||||
|
|
||||||
# STABLE uniquement : attache l'AppImage a la release publique (meme tag que
|
# L'AppImage est passee au job `publish`, seul a creer la release.
|
||||||
# le .msi -> les deux installeurs sur la meme release).
|
- name: Keep AppImage for the release
|
||||||
- name: Publish AppImage to GitHub Release (stable)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
tag_name: ${{ steps.ver.outputs.tag }}
|
|
||||||
files: core/target/dist-out/DM_Loremind*.AppImage
|
|
||||||
fail_on_unmatched_files: true
|
|
||||||
|
|
||||||
# BETA uniquement : artefact PRIVE (pas de release publique).
|
|
||||||
- name: Upload AppImage as private artifact (beta)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: loremind-beta-${{ steps.ver.outputs.version }}-appimage
|
name: installer-linux
|
||||||
path: core/target/dist-out/DM_Loremind*.AppImage
|
path: core/target/dist-out/DM_Loremind*.AppImage
|
||||||
retention-days: 90
|
if-no-files-found: error
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
|
# PUBLICATION : un seul job cree la release et y attache les deux installeurs.
|
||||||
|
# Quand windows et linux publiaient chacun de leur cote, ils tournaient en
|
||||||
|
# parallele et creaient DEUX releases pour le meme tag (une publiee, une en
|
||||||
|
# brouillon), l'un echouant sur « already_exists ». Rien n'est publie si l'un
|
||||||
|
# des deux builds echoue : une release a toujours ses deux installeurs.
|
||||||
|
# Relancer le workflow pour une version deja publiee met la release a jour et
|
||||||
|
# remplace les fichiers de meme nom (pas besoin de la supprimer).
|
||||||
|
publish:
|
||||||
|
needs: [windows, linux]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Get installers
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
pattern: installer-*
|
||||||
|
path: dist
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
# tag_name explicite : en declenchement manuel, github.ref est une branche.
|
||||||
|
# Une beta est publiee en pre-release (ignoree par /releases/latest).
|
||||||
|
- name: Publish GitHub Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ needs.windows.outputs.tag }}
|
||||||
|
files: dist/*
|
||||||
|
fail_on_unmatched_files: true
|
||||||
|
generate_release_notes: true
|
||||||
|
prerelease: ${{ needs.windows.outputs.isbeta == 'true' }}
|
||||||
|
|||||||
+2
-5
@@ -7,11 +7,6 @@
|
|||||||
brain/data/settings.json
|
brain/data/settings.json
|
||||||
*.key
|
*.key
|
||||||
*.pem
|
*.pem
|
||||||
# Exception : la cle PUBLIQUE JWT du relais Patreon est destinee a etre
|
|
||||||
# embarquee dans le binaire. Pas de risque a la committer (c'est une cle
|
|
||||||
# publique par construction). Sans cette exception, le module licensing
|
|
||||||
# est silencieusement desactive dans les builds CI.
|
|
||||||
!core/src/main/resources/licensing/jwt-public-key.pem
|
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Java / Spring Boot / Maven
|
# Java / Spring Boot / Maven
|
||||||
@@ -129,3 +124,5 @@ web/coverage/
|
|||||||
brain/htmlcov/
|
brain/htmlcov/
|
||||||
brain/.coverage
|
brain/.coverage
|
||||||
foundry-module/
|
foundry-module/
|
||||||
|
plan-promotion-loremind.md
|
||||||
|
post-reddit-foundryvtt.md
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Configuration MegaLinter — https://megalinter.io/latest/config-file/
|
||||||
|
#
|
||||||
|
# Périmètre volontairement resserré (liste ENABLE_LINTERS exclusive) : on
|
||||||
|
# active les linters au fil de l'eau plutôt que de subir les ~100 par défaut.
|
||||||
|
# Le scan CVE des dépendances n'est PAS ici : il est porté par le job Trivy
|
||||||
|
# (cf. .gitea/workflows/quality.yml).
|
||||||
|
|
||||||
|
APPLY_FIXES: none
|
||||||
|
DEFAULT_BRANCH: main
|
||||||
|
SHOW_ELAPSED_TIME: true
|
||||||
|
PRINT_ALPACA: false
|
||||||
|
|
||||||
|
# Liste EXCLUSIVE : tout linter absent d'ici est désactivé.
|
||||||
|
ENABLE_LINTERS:
|
||||||
|
# --- core (Java) : bugs + code smells "à la Sonar" sur les sources.
|
||||||
|
# (Sonar for IDE reste pertinent en local pour l'analyse de flux fine.)
|
||||||
|
- JAVA_PMD
|
||||||
|
# --- brain (Python) ---
|
||||||
|
- PYTHON_RUFF # remplace flake8/pylint/isort, très rapide
|
||||||
|
- PYTHON_BANDIT # sécurité du code Python
|
||||||
|
# - PYTHON_MYPY # à activer quand le brain aura des annotations de types
|
||||||
|
# --- repo entier ---
|
||||||
|
- REPOSITORY_GITLEAKS # secrets committés (tokens, mots de passe…)
|
||||||
|
- DOCKERFILE_HADOLINT # bonnes pratiques Dockerfile
|
||||||
|
# --- web (TypeScript) : PAS via MegaLinter. Le lint tourne avec la
|
||||||
|
# toolchain du projet (job "web-lint" de quality.yml → ng lint,
|
||||||
|
# config web/eslint.config.js avec angular-eslint + sonarjs).
|
||||||
|
|
||||||
|
# Jamais d'analyse des artefacts de build, dépendances et sites docs.
|
||||||
|
FILTER_REGEX_EXCLUDE: '(^|/)(node_modules|target|dist|coverage|\.angular|\.mvn|docusaurus)/'
|
||||||
|
|
||||||
|
# Rapports déposés là où le workflow les publie en artefact CI.
|
||||||
|
REPORT_OUTPUT_FOLDER: megalinter-reports
|
||||||
|
|
||||||
|
# Phase de rodage : passer temporairement à true pour rendre le job
|
||||||
|
# informatif (rapport sans échec CI) le temps de purger l'existant.
|
||||||
|
DISABLE_ERRORS: false
|
||||||
|
|
||||||
|
# PMD : ruleset projet à la racine (java-pmd-ruleset.xml, détecté
|
||||||
|
# automatiquement) — orienté bugs réels, sans style. Non-bloquant le temps
|
||||||
|
# de purger le backlog (~65 findings : PreserveStackTrace, EmptyCatchBlock,
|
||||||
|
# CheckResultSet, RelianceOnDefaultCharset…). Repasser à false ensuite.
|
||||||
|
JAVA_PMD_DISABLE_ERRORS: true
|
||||||
+1
-2
@@ -7,7 +7,6 @@
|
|||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](https://loremind-docs.igmlcreation.fr/)
|
[](https://loremind-docs.igmlcreation.fr/)
|
||||||
[](https://loremind-demo.igmlcreation.fr/)
|
[](https://loremind-demo.igmlcreation.fr/)
|
||||||
[](https://www.patreon.com/c/IGMLCreation)
|
|
||||||
[](https://discord.gg/cPpFzCjEzQ)
|
[](https://discord.gg/cPpFzCjEzQ)
|
||||||
|
|
||||||
## Découvrir DM Loremind en vidéo
|
## Découvrir DM Loremind en vidéo
|
||||||
@@ -67,7 +66,7 @@ Quelques limites à connaître :
|
|||||||
|
|
||||||
DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||||
|
|
||||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
- **Canal bêta** — les nouveautés en avant-première, gratuites pour tous : bascule depuis les Paramètres (Docker) ou pré-version GitHub (bureau)
|
||||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](https://loremind-docs.igmlcreation.fr/en/)
|
[](https://loremind-docs.igmlcreation.fr/en/)
|
||||||
[](https://loremind-demo.igmlcreation.fr/)
|
[](https://loremind-demo.igmlcreation.fr/)
|
||||||
[](https://www.patreon.com/c/IGMLCreation)
|
|
||||||
[](https://discord.gg/cPpFzCjEzQ)
|
[](https://discord.gg/cPpFzCjEzQ)
|
||||||
|
|
||||||
## See DM Loremind in action
|
## See DM Loremind in action
|
||||||
@@ -67,7 +66,7 @@ A few limitations to be aware of:
|
|||||||
|
|
||||||
DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support:
|
DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support:
|
||||||
|
|
||||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — early access to features, roadmap voting, exclusive devlogs
|
- **Beta channel** — new features ahead of time, free for everyone: switch from Settings (Docker) or install a GitHub pre-release (desktop)
|
||||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from app.application.generate_page import GeneratePageUseCase
|
|||||||
from app.application.llm_json import load_json_object
|
from app.application.llm_json import load_json_object
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.prompts import conversation_title as title_prompts
|
from app.application.prompts import conversation_title as title_prompts
|
||||||
|
from app.application.prompts import guided_answers as guided_answers_prompts
|
||||||
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
||||||
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
||||||
from app.application.prompts import session_recap as session_recap_prompts
|
from app.application.prompts import session_recap as session_recap_prompts
|
||||||
@@ -290,3 +291,82 @@ async def generate_session_recap(
|
|||||||
if not recap:
|
if not recap:
|
||||||
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
||||||
return SessionRecapResponseDTO(recap=recap)
|
return SessionRecapResponseDTO(recap=recap)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Méthodes guidées : proposer des réponses à partir d'une idée (Mentor d'écriture) ----
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedOptionDTO(BaseModel):
|
||||||
|
"""Choix possible d'une question à choix : valeur technique + libellé lisible."""
|
||||||
|
|
||||||
|
value: str
|
||||||
|
label: str = Field(default="")
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedFieldDTO(BaseModel):
|
||||||
|
"""Une question de la méthode guidée (décrite par le front, relayée par le Core)."""
|
||||||
|
|
||||||
|
key: str
|
||||||
|
label: str = Field(default="")
|
||||||
|
hint: str = Field(default="")
|
||||||
|
step: str = Field(default="")
|
||||||
|
options: list[GuidedOptionDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedAnswersRequestDTO(BaseModel):
|
||||||
|
method_name: str = Field(default="")
|
||||||
|
method_principle: str = Field(default="")
|
||||||
|
idea: str = Field(default="")
|
||||||
|
context: str = Field(default="")
|
||||||
|
fields: list[GuidedFieldDTO] = Field(default_factory=list)
|
||||||
|
existing: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedAnswersResponseDTO(BaseModel):
|
||||||
|
"""Une réponse proposée par clé (clés demandées uniquement, choix valides, non vides)."""
|
||||||
|
|
||||||
|
answers: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate/guided-answers", response_model=GuidedAnswersResponseDTO)
|
||||||
|
async def generate_guided_answers(
|
||||||
|
body: GuidedAnswersRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
|
) -> GuidedAnswersResponseDTO:
|
||||||
|
"""Propose des réponses aux questions d'une méthode guidée à partir de l'idée du MJ.
|
||||||
|
|
||||||
|
Rien n'est enregistré : le front remplit les champs vides, le MJ relit et corrige. Une
|
||||||
|
question à choix n'accepte qu'une des valeurs proposées ; le reste est ignoré.
|
||||||
|
"""
|
||||||
|
by_key = {f.key: f for f in body.fields if f.key}
|
||||||
|
prompt = guided_answers_prompts.guided_answers_prompt(
|
||||||
|
body.method_name, body.method_principle, body.idea, body.context,
|
||||||
|
[f.model_dump() for f in body.fields], body.existing, language)
|
||||||
|
try:
|
||||||
|
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
if not isinstance(parsed, dict):
|
||||||
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de réponses exploitables.")
|
||||||
|
return GuidedAnswersResponseDTO(answers=_clean_guided_answers(parsed.get("answers"), by_key))
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dict[str, str]:
|
||||||
|
"""Garde les clés demandées, non vides ; une question à choix n'accepte qu'une valeur proposée."""
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return out
|
||||||
|
for key, value in raw.items():
|
||||||
|
field = by_key.get(str(key))
|
||||||
|
if field is None or not isinstance(value, (str, int, float)):
|
||||||
|
continue
|
||||||
|
text = str(value).strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
if field.options and text not in {o.value for o in field.options}:
|
||||||
|
continue
|
||||||
|
out[field.key] = text
|
||||||
|
return out
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
|
|||||||
sections: dict[str, str]
|
sections: dict[str, str]
|
||||||
page_count: int
|
page_count: int
|
||||||
ocr_page_count: int
|
ocr_page_count: int
|
||||||
|
# Règles en deux langues : {code langue → sections} et langue d'origine du livre.
|
||||||
|
sections_by_language: dict[str, dict[str, str]] = {}
|
||||||
|
source_language: str = ""
|
||||||
|
|
||||||
|
|
||||||
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||||
@@ -70,6 +73,8 @@ async def import_rules(
|
|||||||
sections=result.sections,
|
sections=result.sections,
|
||||||
page_count=result.page_count,
|
page_count=result.page_count,
|
||||||
ocr_page_count=result.ocr_page_count,
|
ocr_page_count=result.ocr_page_count,
|
||||||
|
sections_by_language=result.sections_by_language,
|
||||||
|
source_language=result.source_language,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -115,6 +120,7 @@ async def import_rules_stream(
|
|||||||
@router.post("/import/campaign/stream")
|
@router.post("/import/campaign/stream")
|
||||||
async def import_campaign_stream(
|
async def import_campaign_stream(
|
||||||
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
) -> StreamingResponse:
|
) -> StreamingResponse:
|
||||||
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
||||||
@@ -131,7 +137,7 @@ async def import_campaign_stream(
|
|||||||
yield sse_event("error", {"message": upload_error})
|
yield sse_event("error", {"message": upload_error})
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
async for ev in use_case.stream(content):
|
async for ev in use_case.stream(content, language=language):
|
||||||
event_type = ev.pop("type")
|
event_type = ev.pop("type")
|
||||||
yield sse_event(event_type, ev)
|
yield sse_event(event_type, ev)
|
||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
|
|||||||
@@ -361,7 +361,7 @@ class ImportCampaignUseCase:
|
|||||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||||
self._map_concurrency = max(1, map_concurrency)
|
self._map_concurrency = max(1, map_concurrency)
|
||||||
|
|
||||||
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult:
|
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
||||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||||
doc = self._extractor.extract(pdf_bytes)
|
doc = self._extractor.extract(pdf_bytes)
|
||||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||||
@@ -371,7 +371,7 @@ class ImportCampaignUseCase:
|
|||||||
for start in range(0, total, self._map_concurrency):
|
for start in range(0, total, self._map_concurrency):
|
||||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||||
results = await asyncio.gather(*(
|
results = await asyncio.gather(*(
|
||||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||||
for i, c in wave
|
for i, c in wave
|
||||||
))
|
))
|
||||||
for res in results:
|
for res in results:
|
||||||
@@ -386,7 +386,7 @@ class ImportCampaignUseCase:
|
|||||||
npcs=merger.npcs(),
|
npcs=merger.npcs(),
|
||||||
)
|
)
|
||||||
|
|
||||||
async def stream(self, pdf_bytes: bytes):
|
async def stream(self, pdf_bytes: bytes, language: str = "fr"):
|
||||||
"""Variante streamée : yield des évènements d'avancement.
|
"""Variante streamée : yield des évènements d'avancement.
|
||||||
|
|
||||||
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
||||||
@@ -432,7 +432,7 @@ class ImportCampaignUseCase:
|
|||||||
for start in range(0, total, self._map_concurrency):
|
for start in range(0, total, self._map_concurrency):
|
||||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||||
gathered = asyncio.gather(
|
gathered = asyncio.gather(
|
||||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||||
for i, c in wave),
|
for i, c in wave),
|
||||||
return_exceptions=True,
|
return_exceptions=True,
|
||||||
)
|
)
|
||||||
@@ -553,21 +553,23 @@ class ImportCampaignUseCase:
|
|||||||
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
||||||
|
|
||||||
async def _map_chunk(
|
async def _map_chunk(
|
||||||
self, chunk: str, *, index: int, total: int, toc_block: str = ""
|
self, chunk: str, *, index: int, total: int, toc_block: str = "", language: str = "fr"
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
||||||
return await self._extract_payload(
|
return await self._extract_payload(
|
||||||
chunk, index=index, total=total, depth=0, toc_block=toc_block)
|
chunk, index=index, total=total, depth=0, toc_block=toc_block, language=language)
|
||||||
|
|
||||||
async def _extract_payload(
|
async def _extract_payload(
|
||||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = ""
|
self, text: str, *, index: int, total: int, depth: int, toc_block: str = "",
|
||||||
|
language: str = "fr",
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
||||||
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
||||||
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||||
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||||
prompt = (
|
prompt = (
|
||||||
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME)
|
prompts.MAP_SYSTEM.format(default_arc=prompts.default_arc_name(language))
|
||||||
|
+ prompts.language_block(language)
|
||||||
+ toc_section
|
+ toc_section
|
||||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||||
"Renvoie maintenant le JSON de l'arborescence."
|
"Renvoie maintenant le JSON de l'arborescence."
|
||||||
@@ -591,9 +593,9 @@ class ImportCampaignUseCase:
|
|||||||
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||||
"re-découpage en 2 moitiés plus digestes…")
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
a = await self._extract_payload(
|
||||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
b = await self._extract_payload(
|
b = await self._extract_payload(
|
||||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||||
payload, truncated = self._parse_payload(raw, index=index)
|
payload, truncated = self._parse_payload(raw, index=index)
|
||||||
|
|
||||||
@@ -607,9 +609,9 @@ class ImportCampaignUseCase:
|
|||||||
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||||
"re-découpage en 2 moitiés plus digestes…")
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
a = await self._extract_payload(
|
||||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
b = await self._extract_payload(
|
b = await self._extract_payload(
|
||||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||||
if truncated:
|
if truncated:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ from app.application.import_status import (
|
|||||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.prompts import import_rules as prompts
|
from app.application.prompts import import_rules as prompts
|
||||||
|
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
|
||||||
from app.application.streaming import with_heartbeat
|
from app.application.streaming import with_heartbeat
|
||||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||||
|
|
||||||
@@ -90,6 +91,9 @@ _ANCHORS_SCHEMA: dict = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
|
||||||
|
_DETECT_CHARS = 20_000
|
||||||
|
|
||||||
class _SectionMerger:
|
class _SectionMerger:
|
||||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||||
|
|
||||||
@@ -250,10 +254,25 @@ class ImportRulesUseCase:
|
|||||||
merger = _SectionMerger()
|
merger = _SectionMerger()
|
||||||
for i, chunk in enumerate(chunks):
|
for i, chunk in enumerate(chunks):
|
||||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||||
|
sections = merger.result()
|
||||||
|
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||||
|
by_language = {source: sections}
|
||||||
|
translator = RulesTranslator(self._llm)
|
||||||
|
for target in other_languages(source):
|
||||||
|
try:
|
||||||
|
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
|
||||||
|
by_language[target] = {
|
||||||
|
titles.get(title, title): await translator.translate_content(content, source, target)
|
||||||
|
for title, content in sections.items()
|
||||||
|
}
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||||
return RulesImportResult(
|
return RulesImportResult(
|
||||||
sections=merger.result(),
|
sections=sections,
|
||||||
page_count=doc.page_count,
|
page_count=doc.page_count,
|
||||||
ocr_page_count=doc.ocr_page_count,
|
ocr_page_count=doc.ocr_page_count,
|
||||||
|
sections_by_language=by_language,
|
||||||
|
source_language=source,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
||||||
@@ -344,14 +363,57 @@ class ImportRulesUseCase:
|
|||||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
|
||||||
|
# langue de l'application. Un échec de traduction n'annule pas l'import.
|
||||||
|
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||||
|
by_language: dict[str, dict[str, str]] = {source: sections}
|
||||||
|
for target in other_languages(source):
|
||||||
|
try:
|
||||||
|
async for ev in self._translate_events(sections, source, target):
|
||||||
|
if ev["type"] == "_translated":
|
||||||
|
by_language[target] = ev["sections"]
|
||||||
|
else:
|
||||||
|
yield ev
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||||
|
yield {"type": "status",
|
||||||
|
"message": f"Traduction ({language_name(target)}) impossible : {str(exc)[:200]}"}
|
||||||
|
|
||||||
yield {
|
yield {
|
||||||
"type": "done",
|
"type": "done",
|
||||||
"sections": sections,
|
"sections": sections,
|
||||||
|
"sections_by_language": by_language,
|
||||||
|
"source_language": source,
|
||||||
"page_count": doc.page_count,
|
"page_count": doc.page_count,
|
||||||
"ocr_page_count": doc.ocr_page_count,
|
"ocr_page_count": doc.ocr_page_count,
|
||||||
"skipped": skipped,
|
"skipped": skipped,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
|
||||||
|
"""Évènements d'avancement de la traduction ; le dernier est
|
||||||
|
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
|
||||||
|
translator = RulesTranslator(self._llm)
|
||||||
|
titles = list(sections)
|
||||||
|
total = len(titles)
|
||||||
|
label = language_name(target)
|
||||||
|
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
|
||||||
|
mapping: dict[str, str] = {}
|
||||||
|
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
|
||||||
|
if kind == "heartbeat":
|
||||||
|
yield {"type": "heartbeat", "current": 0, "total": total}
|
||||||
|
elif kind == "result":
|
||||||
|
mapping = unique_titles(payload)
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for i, title in enumerate(titles):
|
||||||
|
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
|
||||||
|
"current": i + 1, "total": total}
|
||||||
|
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
|
||||||
|
if kind == "heartbeat":
|
||||||
|
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||||
|
elif kind == "result":
|
||||||
|
out[mapping.get(title, title)] = payload
|
||||||
|
yield {"type": "_translated", "sections": out}
|
||||||
|
|
||||||
# --- MAP : un morceau → sections -----------------------------------------
|
# --- MAP : un morceau → sections -----------------------------------------
|
||||||
|
|
||||||
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
||||||
|
|||||||
@@ -113,5 +113,8 @@ async def generate_with_retry(
|
|||||||
+ str(exc)[:160]
|
+ str(exc)[:160]
|
||||||
)
|
)
|
||||||
await asyncio.sleep(wait)
|
await asyncio.sleep(wait)
|
||||||
|
# Le message « nouvel essai dans Ns » deviendrait faux : on dit que
|
||||||
|
# l'essai suivant est lancé (il peut durer plusieurs minutes).
|
||||||
|
notify_status(f"Nouvel essai en cours (tentative {attempt + 2}/{_ATTEMPTS})…")
|
||||||
assert last_error is not None
|
assert last_error is not None
|
||||||
raise last_error
|
raise last_error
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Prompt des méthodes guidées (Mentor d'écriture) : à partir de l'idée de départ du MJ,
|
||||||
|
proposer des réponses aux questions de la méthode (Donjon en 5 salles, Enquête en nœuds,
|
||||||
|
Plan du méchant…).
|
||||||
|
|
||||||
|
Générique : le front décrit la méthode (nom ; principe suivi du rôle de chaque étape, comme
|
||||||
|
dans l'assistant manuel) et ses questions (clé, libellé,
|
||||||
|
aide, étape, choix possibles) ; ce module ne fait que formuler le prompt. Les réponses
|
||||||
|
déjà écrites par le MJ sont fournies pour rester cohérent et ne jamais être contredites.
|
||||||
|
"""
|
||||||
|
from app.core.language import language_name
|
||||||
|
|
||||||
|
|
||||||
|
def _field_line(field: dict) -> str:
|
||||||
|
key = str(field.get("key") or "").strip()
|
||||||
|
label = str(field.get("label") or key).strip()
|
||||||
|
hint = str(field.get("hint") or "").strip()
|
||||||
|
step = str(field.get("step") or "").strip()
|
||||||
|
line = f'- "{key}"'
|
||||||
|
if step:
|
||||||
|
line += f" [{step}]"
|
||||||
|
line += f" : {label}"
|
||||||
|
if hint:
|
||||||
|
line += f" — {hint}"
|
||||||
|
options = field.get("options") or []
|
||||||
|
if options:
|
||||||
|
values = ", ".join(f'"{o.get("value")}" ({o.get("label")})' for o in options if o.get("value"))
|
||||||
|
line += f" — UNE valeur parmi : {values}"
|
||||||
|
return line
|
||||||
|
|
||||||
|
|
||||||
|
def guided_answers_prompt(method_name: str, method_principle: str, idea: str, context: str,
|
||||||
|
fields: list[dict], existing: dict[str, str], language: str) -> str:
|
||||||
|
"""Construit le prompt. `fields` = [{key, label, hint, step, options}] ; `existing` = réponses du MJ."""
|
||||||
|
fields_list = "\n".join(_field_line(f) for f in fields or [] if f.get("key"))
|
||||||
|
existing_lines = "\n".join(
|
||||||
|
f'- "{k}" : {v.strip()}' for k, v in (existing or {}).items() if isinstance(v, str) and v.strip())
|
||||||
|
existing_block = (
|
||||||
|
"\nCe que le MJ a DÉJÀ écrit (à respecter, ne le contredis jamais) :\n"
|
||||||
|
f"{existing_lines}\n" if existing_lines else ""
|
||||||
|
)
|
||||||
|
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context and context.strip() else ""
|
||||||
|
guide = method_principle.strip() if method_principle else ""
|
||||||
|
guide_block = (
|
||||||
|
"\nLa méthode, telle que le MJ la suit à la main (principe, puis rôle de chaque étape) :\n"
|
||||||
|
f"{guide}\n" if guide else ""
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
"Tu es un auteur expérimenté de scénarios de jeu de rôle, qui aide un MJ à écrire son aventure "
|
||||||
|
f"avec la méthode « {method_name.strip() or 'guidée'} ».\n"
|
||||||
|
f"{guide_block}\n"
|
||||||
|
f"Idée de départ du MJ : {idea.strip() or '(aucune : propose une aventure originale)'}\n"
|
||||||
|
f"{context_block}{existing_block}\n"
|
||||||
|
"Questions de la méthode auxquelles tu dois répondre (n'utilise QUE ces clés) :\n"
|
||||||
|
f"{fields_list}\n\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
|
'- Format exact : {"answers": {"cle": "réponse", ...}}\n'
|
||||||
|
"- N'inclus QUE des clés de la liste. Pour une question à choix, renvoie EXACTEMENT une des "
|
||||||
|
"valeurs proposées.\n"
|
||||||
|
"- Pars de l'idée du MJ et développe-la : garde son ton, ses lieux, ses personnages ; n'en change "
|
||||||
|
"pas le sujet.\n"
|
||||||
|
"- Respecte la méthode : chaque réponse remplit le rôle de SON étape, tel que décrit ci-dessus "
|
||||||
|
"(ex. une épreuve qui ne se règle pas par un combat, des pistes qui se recoupent). Ne mélange pas "
|
||||||
|
"les étapes.\n"
|
||||||
|
"- Toutes les réponses forment UNE aventure cohérente, concrète et jouable "
|
||||||
|
"(noms, lieux, motivations précises ; pas de généralités).\n"
|
||||||
|
"- Sois concis : un nom en quelques mots, une description en 2 à 4 phrases.\n"
|
||||||
|
"- Donne toujours aux joueurs de vrais choix et plusieurs façons de progresser.\n"
|
||||||
|
f"- Rédige les réponses en {language_name(language)}.\n"
|
||||||
|
"Renvoie maintenant le JSON."
|
||||||
|
)
|
||||||
@@ -1,7 +1,29 @@
|
|||||||
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
||||||
|
from app.core.language import language_name
|
||||||
|
|
||||||
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||||
DEFAULT_ARC_NAME = "Aventure principale"
|
DEFAULT_ARC_NAME = "Aventure principale"
|
||||||
|
DEFAULT_ARC_NAMES = {"fr": DEFAULT_ARC_NAME, "en": "Main adventure"}
|
||||||
|
|
||||||
|
|
||||||
|
def default_arc_name(language: str) -> str:
|
||||||
|
"""Nom de l'arc unique, dans la langue de l'interface."""
|
||||||
|
return DEFAULT_ARC_NAMES.get(language, DEFAULT_ARC_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
def language_block(language: str) -> str:
|
||||||
|
"""Consigne de langue : les textes sont écrits dans la langue de l'interface, quelle que
|
||||||
|
soit celle du livre (traduits fidèlement s'il le faut). Les TITRES et noms propres restent
|
||||||
|
ceux du livre : la fusion des morceaux se fait par nom exact, et un nom ne se traduit pas."""
|
||||||
|
name = language_name(language)
|
||||||
|
return (
|
||||||
|
"\n\nLANGUE DE SORTIE :\n"
|
||||||
|
f"- Rédige TOUS les textes (description, player_narration, gm_notes, salles, PNJ) en {name}, "
|
||||||
|
f"quelle que soit la langue du livre. Si le livre est dans une autre langue, TRADUIS ces textes "
|
||||||
|
"fidèlement, sans les résumer davantage.\n"
|
||||||
|
"- Garde TELS QUELS les noms propres (personnages, lieux, divinités, sorts, objets nommés) "
|
||||||
|
"et les noms d'arcs, de chapitres, de scènes, de salles et de PNJ (titres du livre)."
|
||||||
|
)
|
||||||
|
|
||||||
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
||||||
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""Règles en deux langues : détection de la langue d'un livre de règles et traduction de
|
||||||
|
ses sections (titre + contenu markdown) vers l'autre langue de l'application.
|
||||||
|
|
||||||
|
L'extraction reste FIDÈLE au livre (langue d'origine) ; la traduction produit la seconde
|
||||||
|
version. Les noms propres (lieux, personnages, divinités, sorts, objets nommés) sont
|
||||||
|
conservés tels quels. Un contenu long est traduit par morceaux coupés aux paragraphes,
|
||||||
|
pour rester sous les limites de sortie des modèles.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from app.application.llm_json import load_json_object
|
||||||
|
from app.application.llm_retry import generate_with_retry
|
||||||
|
from app.core.language import language_name
|
||||||
|
from app.domain.ports import LLMProvider
|
||||||
|
|
||||||
|
LANGUAGES = ("fr", "en")
|
||||||
|
|
||||||
|
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
|
||||||
|
CHUNK_CHARS = 6000
|
||||||
|
|
||||||
|
_FR_WORDS = {"le", "la", "les", "des", "une", "est", "et", "du", "dans", "pour", "que", "qui",
|
||||||
|
"sur", "avec", "vous", "votre", "sont", "pas", "par", "au", "aux", "ce", "cette", "il"}
|
||||||
|
_EN_WORDS = {"the", "and", "of", "to", "is", "in", "you", "your", "for", "with", "that", "are",
|
||||||
|
"on", "as", "be", "this", "it", "an", "by", "or", "can", "if", "each", "when"}
|
||||||
|
|
||||||
|
|
||||||
|
def detect_language(text: str, default: str = "fr") -> str:
|
||||||
|
"""Langue dominante (« fr » ou « en ») par comptage de mots-outils ; `default` si indécis."""
|
||||||
|
words = re.findall(r"[a-zàâçéèêëîïôûùüÿœ']+", (text or "").lower())
|
||||||
|
fr = sum(1 for w in words if w in _FR_WORDS)
|
||||||
|
en = sum(1 for w in words if w in _EN_WORDS)
|
||||||
|
if fr == en:
|
||||||
|
return default if default in LANGUAGES else "fr"
|
||||||
|
return "fr" if fr > en else "en"
|
||||||
|
|
||||||
|
|
||||||
|
def other_languages(source: str) -> list[str]:
|
||||||
|
return [lang for lang in LANGUAGES if lang != source]
|
||||||
|
|
||||||
|
|
||||||
|
def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
|
||||||
|
"""Coupe un markdown en morceaux ≤ max_chars, aux limites de paragraphes (puis de lignes)."""
|
||||||
|
if len(text) <= max_chars:
|
||||||
|
return [text]
|
||||||
|
chunks: list[str] = []
|
||||||
|
current = ""
|
||||||
|
for para in re.split(r"(\n\s*\n)", text):
|
||||||
|
if len(current) + len(para) <= max_chars:
|
||||||
|
current += para
|
||||||
|
continue
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current)
|
||||||
|
current = ""
|
||||||
|
while len(para) > max_chars: # paragraphe géant : coupe aux lignes, sinon brutalement
|
||||||
|
cut = para.rfind("\n", 0, max_chars)
|
||||||
|
cut = cut if cut > 0 else max_chars
|
||||||
|
chunks.append(para[:cut])
|
||||||
|
para = para[cut:]
|
||||||
|
current = para
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current)
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
|
||||||
|
def content_prompt(text: str, source: str, target: str) -> str:
|
||||||
|
return (
|
||||||
|
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
|
||||||
|
f"vers la langue « {language_name(target)} ».\n\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\n"
|
||||||
|
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
|
||||||
|
"objets nommés.\n"
|
||||||
|
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
|
||||||
|
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
|
||||||
|
"Extrait :\n"
|
||||||
|
f"{text}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def titles_prompt(titles: list[str], source: str, target: str) -> str:
|
||||||
|
listing = "\n".join(f"- {t}" for t in titles)
|
||||||
|
return (
|
||||||
|
f"Traduis ces titres de sections d'un livre de règles de jeu de rôle de la langue "
|
||||||
|
f"« {language_name(source)} » vers la langue « {language_name(target)} ». "
|
||||||
|
"Garde les noms propres tels quels.\n"
|
||||||
|
'Réponds UNIQUEMENT par un objet JSON : {"titles": {"titre d\'origine": "titre traduit", ...}}\n\n'
|
||||||
|
f"{listing}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RulesTranslator:
|
||||||
|
"""Traduit des sections de règles {titre: markdown} d'une langue vers une autre."""
|
||||||
|
|
||||||
|
def __init__(self, llm: LLMProvider) -> None:
|
||||||
|
self._llm = llm
|
||||||
|
|
||||||
|
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
|
||||||
|
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
|
||||||
|
if not titles:
|
||||||
|
return {}
|
||||||
|
raw = await generate_with_retry(self._llm, titles_prompt(titles, source, target),
|
||||||
|
output_format="json", temperature=0.2)
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for title in titles:
|
||||||
|
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||||
|
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||||
|
return out
|
||||||
|
|
||||||
|
async def translate_content(self, text: str, source: str, target: str) -> str:
|
||||||
|
"""Traduit un contenu markdown (morceau par morceau s'il est long)."""
|
||||||
|
if not text or not text.strip():
|
||||||
|
return text
|
||||||
|
parts = []
|
||||||
|
for chunk in split_markdown(text):
|
||||||
|
if not chunk.strip():
|
||||||
|
parts.append(chunk)
|
||||||
|
continue
|
||||||
|
translated = await generate_with_retry(self._llm, content_prompt(chunk, source, target),
|
||||||
|
temperature=0.2)
|
||||||
|
parts.append(translated.strip())
|
||||||
|
return "\n\n".join(p for p in parts if p.strip())
|
||||||
|
|
||||||
|
|
||||||
|
def unique_titles(titles: dict[str, str]) -> dict[str, str]:
|
||||||
|
"""Évite deux sections traduites sous le même titre (sinon l'une écraserait l'autre)."""
|
||||||
|
seen: dict[str, int] = {}
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for original, translated in titles.items():
|
||||||
|
count = seen.get(translated, 0)
|
||||||
|
seen[translated] = count + 1
|
||||||
|
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
||||||
|
return out
|
||||||
@@ -367,6 +367,10 @@ class RulesImportResult:
|
|||||||
sections: dict[str, str]
|
sections: dict[str, str]
|
||||||
page_count: int
|
page_count: int
|
||||||
ocr_page_count: int
|
ocr_page_count: int
|
||||||
|
# Règles en deux langues : {code langue → sections}. La langue d'origine du livre
|
||||||
|
# (`source_language`) contient l'extraction fidèle ; l'autre, sa traduction.
|
||||||
|
sections_by_language: dict[str, dict[str, str]] = field(default_factory=dict)
|
||||||
|
source_language: str = ""
|
||||||
|
|
||||||
def to_markdown(self) -> str:
|
def to_markdown(self) -> str:
|
||||||
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
||||||
|
|||||||
+1
-1
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="1.0.0",
|
version="1.6.2-beta",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Méthodes guidées : prompt de propositions et nettoyage des réponses du modèle."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.api.routers.generation import GuidedFieldDTO, GuidedOptionDTO, _clean_guided_answers
|
||||||
|
from app.application.prompts.guided_answers import guided_answers_prompt
|
||||||
|
|
||||||
|
|
||||||
|
def _fields() -> dict[str, GuidedFieldDTO]:
|
||||||
|
return {
|
||||||
|
"title": GuidedFieldDTO(key="title", label="Nom de l'enquête"),
|
||||||
|
"node1.nature": GuidedFieldDTO(key="node1.nature", label="Genre de scène", options=[
|
||||||
|
GuidedOptionDTO(value="location", label="Un lieu"), GuidedOptionDTO(value="npc", label="Une personne")]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_contains_idea_questions_choices_existing_answers_and_language():
|
||||||
|
prompt = guided_answers_prompt(
|
||||||
|
"Enquête en nœuds", "Trois pistes qui se recoupent.", "Une tour qui se rallume", "Campagne : Valfroide",
|
||||||
|
[{"key": "title", "label": "Nom de l'enquête", "hint": "Ex. : L'héritage", "step": "Le mystère"},
|
||||||
|
{"key": "node1.nature", "label": "Genre", "options": [{"value": "location", "label": "Un lieu"}]}],
|
||||||
|
{"truth": "Le notaire est coupable", "empty": " "}, "en")
|
||||||
|
|
||||||
|
assert "Une tour qui se rallume" in prompt
|
||||||
|
assert '"title" [Le mystère] : Nom de l\'enquête — Ex. : L\'héritage' in prompt
|
||||||
|
assert 'UNE valeur parmi : "location" (Un lieu)' in prompt
|
||||||
|
assert "Le notaire est coupable" in prompt
|
||||||
|
assert '"empty"' not in prompt, "une réponse vide n'est pas rappelée"
|
||||||
|
assert "Campagne : Valfroide" in prompt
|
||||||
|
assert "anglais" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_lists_the_method_steps_and_asks_to_follow_them():
|
||||||
|
guide = ("Cinq temps dans un même lieu.\n\n"
|
||||||
|
"- Salle 2 : l'épreuve : ici, l'épée ne suffit pas.\n"
|
||||||
|
"- Salle 3 : le revers : les choses se compliquent.")
|
||||||
|
p = guided_answers_prompt("Donjon en 5 salles", guide, "Une crypte", "", [{"key": "room2.name"}], {}, "fr")
|
||||||
|
assert "telle que le MJ la suit à la main" in p
|
||||||
|
assert "- Salle 2 : l'épreuve : ici, l'épée ne suffit pas." in p
|
||||||
|
assert "rôle de SON étape" in p
|
||||||
|
assert "Idée de départ du MJ : Une crypte" in p
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_without_idea_asks_for_an_original_adventure():
|
||||||
|
prompt = guided_answers_prompt("Plan du méchant", "", " ", "", [{"key": "villain", "label": "Adversaire"}], {}, "fr")
|
||||||
|
assert "propose une aventure originale" in prompt
|
||||||
|
assert "français" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_keeps_requested_keys_and_valid_choices_only():
|
||||||
|
out = _clean_guided_answers({
|
||||||
|
"title": " L'héritage empoisonné ",
|
||||||
|
"node1.nature": "npc",
|
||||||
|
"unknown": "ignorée",
|
||||||
|
"empty": "",
|
||||||
|
}, _fields())
|
||||||
|
assert out == {"title": "L'héritage empoisonné", "node1.nature": "npc"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_rejects_an_invalid_choice_and_non_text_values():
|
||||||
|
out = _clean_guided_answers({"node1.nature": "dragon", "title": ["liste"]}, _fields())
|
||||||
|
assert out == {}
|
||||||
|
assert _clean_guided_answers("pas un objet", _fields()) == {}
|
||||||
@@ -100,6 +100,8 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
|||||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||||
llm = ContentLLM([
|
llm = ContentLLM([
|
||||||
|
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||||
|
("Traduis cet extrait", "spells"),
|
||||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||||
("BBB second", '{"Magie":"sorts"}'),
|
("BBB second", '{"Magie":"sorts"}'),
|
||||||
])
|
])
|
||||||
@@ -111,6 +113,25 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
|||||||
assert done["type"] == "done"
|
assert done["type"] == "done"
|
||||||
assert done["sections"] == {"Magie": "sorts"}
|
assert done["sections"] == {"Magie": "sorts"}
|
||||||
assert done["skipped"] == 1
|
assert done["skipped"] == 1
|
||||||
|
# Règles en deux langues : livre en français (« Texte du PDF. ») → traduction anglaise.
|
||||||
|
assert done["source_language"] == "fr"
|
||||||
|
assert done["sections_by_language"] == {"fr": {"Magie": "sorts"}, "en": {"Magic": "spells"}}
|
||||||
|
assert any(e["type"] == "status" and "anglais" in e["message"] for e in events)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_rules_stream_keeps_the_source_language_when_translation_fails(monkeypatch, no_sleep):
|
||||||
|
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["The rules of the game"])
|
||||||
|
llm = ContentLLM([
|
||||||
|
("Traduis ces titres", LLMProviderError("HTTP 503 saturé")),
|
||||||
|
("The rules of the game", '{"Combat":"Each round, you roll the dice."}'),
|
||||||
|
])
|
||||||
|
uc = ImportRulesUseCase(llm, FakeExtractor(_doc("The rules of the game are simple and you can play.")))
|
||||||
|
events = [e async for e in uc.stream(b"pdf")]
|
||||||
|
done = events[-1]
|
||||||
|
assert done["type"] == "done"
|
||||||
|
assert done["source_language"] == "en"
|
||||||
|
assert done["sections_by_language"] == {"en": {"Combat": "Each round, you roll the dice."}}
|
||||||
|
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
||||||
|
|
||||||
|
|
||||||
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
||||||
@@ -155,3 +176,34 @@ async def test_campaign_stream_all_fail_emits_error(one_chunk, no_sleep):
|
|||||||
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
||||||
events = [e async for e in uc.stream(b"pdf")]
|
events = [e async for e in uc.stream(b"pdf")]
|
||||||
assert events[-1]["type"] == "error"
|
assert events[-1]["type"] == "error"
|
||||||
|
|
||||||
|
|
||||||
|
class _RecordingLLM(ScriptedLLM):
|
||||||
|
"""ScriptedLLM qui garde les prompts reçus."""
|
||||||
|
|
||||||
|
def __init__(self, responses: list) -> None:
|
||||||
|
super().__init__(responses)
|
||||||
|
self.prompts: list[str] = []
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompts.append(prompt)
|
||||||
|
return await super().generate(prompt, output_format=output_format, temperature=temperature)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_campaign_import_writes_in_the_interface_language_and_keeps_names():
|
||||||
|
llm = _RecordingLLM([_TREE])
|
||||||
|
uc = ImportCampaignUseCase(llm, FakeExtractor(_doc()))
|
||||||
|
events = [e async for e in uc.stream(b"pdf", language="en")]
|
||||||
|
assert events[-1]["type"] == "done"
|
||||||
|
prompt = llm.prompts[0]
|
||||||
|
assert "LANGUE DE SORTIE" in prompt
|
||||||
|
assert "en anglais" in prompt
|
||||||
|
assert "noms propres" in prompt
|
||||||
|
assert '"Main adventure"' in prompt, "arc par défaut dans la langue de l'interface"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_campaign_import_defaults_to_french():
|
||||||
|
llm = _RecordingLLM([_TREE])
|
||||||
|
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
||||||
|
assert "en français" in llm.prompts[0]
|
||||||
|
assert '"Aventure principale"' in llm.prompts[0]
|
||||||
|
|||||||
@@ -110,3 +110,21 @@ async def test_rate_limit_respects_suggested_retry_after(slept):
|
|||||||
assert await generate_with_retry(llm, "p") == "ok"
|
assert await generate_with_retry(llm, "p") == "ok"
|
||||||
# min(8 + 2, 60) = 10
|
# min(8 + 2, 60) = 10
|
||||||
assert slept == [10.0]
|
assert slept == [10.0]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_tells_the_ui_when_the_next_attempt_starts(slept):
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from app.application.import_status import reset_status_queue, set_status_queue
|
||||||
|
|
||||||
|
queue: asyncio.Queue = asyncio.Queue()
|
||||||
|
token = set_status_queue(queue)
|
||||||
|
try:
|
||||||
|
llm = FakeLLM([LLMProviderError("Erreur Mistral (ReadError) : ReadError"), "ok"])
|
||||||
|
assert await generate_with_retry(llm, "p") == "ok"
|
||||||
|
finally:
|
||||||
|
reset_status_queue(token)
|
||||||
|
messages = [queue.get_nowait() for _ in range(queue.qsize())]
|
||||||
|
assert "nouvel essai dans 3s" in messages[0]
|
||||||
|
# Sans ce second message, « nouvel essai dans 3s » restait affiché pendant tout l'essai suivant.
|
||||||
|
assert messages[1] == "Nouvel essai en cours (tentative 2/3)…"
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.application.rules_translation import (
|
||||||
|
RulesTranslator, detect_language, other_languages, split_markdown, unique_titles,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class EchoLLM:
|
||||||
|
"""Traduit « en majuscules » et garde trace des prompts reçus."""
|
||||||
|
|
||||||
|
def __init__(self, titles_json: str = '{"titles": {}}') -> None:
|
||||||
|
self.prompts: list[str] = []
|
||||||
|
self._titles_json = titles_json
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompts.append(prompt)
|
||||||
|
if "Traduis ces titres" in prompt:
|
||||||
|
return self._titles_json
|
||||||
|
return prompt.split("Extrait :\n", 1)[1].upper()
|
||||||
|
|
||||||
|
|
||||||
|
def test_detect_language():
|
||||||
|
assert detect_language("Le joueur lance les dés et la partie est terminée pour vous.") == "fr"
|
||||||
|
assert detect_language("The player rolls the dice and the game is over for you.") == "en"
|
||||||
|
assert detect_language("", default="en") == "en"
|
||||||
|
assert other_languages("fr") == ["en"]
|
||||||
|
assert other_languages("en") == ["fr"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_markdown_keeps_short_text_and_cuts_at_paragraphs():
|
||||||
|
assert split_markdown("court") == ["court"]
|
||||||
|
text = "\n\n".join(["a" * 40] * 10)
|
||||||
|
chunks = split_markdown(text, max_chars=100)
|
||||||
|
assert all(len(c) <= 100 for c in chunks)
|
||||||
|
assert "".join(chunks).replace("\n", "") == text.replace("\n", "")
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_markdown_cuts_a_giant_paragraph():
|
||||||
|
chunks = split_markdown("x" * 250, max_chars=100)
|
||||||
|
assert [len(c) for c in chunks] == [100, 100, 50]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_translate_content_keeps_names_instruction_and_joins_chunks():
|
||||||
|
llm = EchoLLM()
|
||||||
|
out = await RulesTranslator(llm).translate_content("## Combat\n\nChaque round.", "fr", "en")
|
||||||
|
assert out == "## COMBAT\n\nCHAQUE ROUND."
|
||||||
|
assert "noms propres" in llm.prompts[0]
|
||||||
|
assert "de la langue « français » vers la langue « anglais »" in llm.prompts[0]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_translate_titles_falls_back_to_the_original_title():
|
||||||
|
llm = EchoLLM('{"titles": {"Combat": "Fighting"}}')
|
||||||
|
out = await RulesTranslator(llm).translate_titles(["Combat", "Magie"], "fr", "en")
|
||||||
|
assert out == {"Combat": "Fighting", "Magie": "Magie"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_unique_titles_avoids_collisions():
|
||||||
|
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
||||||
|
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
|
||||||
+14
-26
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>1.0.0</version>
|
<version>1.6.2-beta</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
@@ -24,6 +24,19 @@
|
|||||||
>= 3.18 : corrige CVE-2025-48924 (recursion infinie ClassUtils.getClass).
|
>= 3.18 : corrige CVE-2025-48924 (recursion infinie ClassUtils.getClass).
|
||||||
Propriete reconnue par le BOM Spring Boot → s'applique partout. -->
|
Propriete reconnue par le BOM Spring Boot → s'applique partout. -->
|
||||||
<commons-lang3.version>3.20.0</commons-lang3.version>
|
<commons-lang3.version>3.20.0</commons-lang3.version>
|
||||||
|
<!-- Overrides CVE (detectes par Trivy en CI — job quality.yml) :
|
||||||
|
proprietes reconnues par le BOM Spring Boot, comme ci-dessus. -->
|
||||||
|
<!-- >= 2.21.4 : CVE-2026-54512 / CVE-2026-54513 (execution de code
|
||||||
|
arbitraire via contournement du PolymorphicTypeValidator). -->
|
||||||
|
<jackson-bom.version>2.21.4</jackson-bom.version>
|
||||||
|
<!-- >= 4.1.135 : lot de CVE netty (DoS codec/handler, bypass de
|
||||||
|
verification hostname CVE-2026-50010, DNS CVE-2026-45674/47691). -->
|
||||||
|
<netty.version>4.1.135.Final</netty.version>
|
||||||
|
<!-- >= 10.1.55 : 3 CRITICAL Tomcat (CVE-2026-41293 headers HTTP/2 non
|
||||||
|
valides, CVE-2026-43512 bypass auth digest, CVE-2026-43515). -->
|
||||||
|
<tomcat.version>10.1.55</tomcat.version>
|
||||||
|
<!-- >= 42.7.11 : CVE-2026-42198 (DoS client via SCRAM-SHA-256). -->
|
||||||
|
<postgresql.version>42.7.11</postgresql.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@@ -124,31 +137,6 @@
|
|||||||
<version>5.1.0</version>
|
<version>5.1.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Nimbus JOSE+JWT — verification des JWT Ed25519 (EdDSA) emis par le relais
|
|
||||||
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle.
|
|
||||||
>= 10.0.2 : corrige CVE-2025-53864 (DoS par JSON profondement imbrique
|
|
||||||
dans le claim set — surface critique : JWT colle par l'utilisateur). -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.nimbusds</groupId>
|
|
||||||
<artifactId>nimbus-jose-jwt</artifactId>
|
|
||||||
<version>10.9.1</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.bouncycastle</groupId>
|
|
||||||
<artifactId>bcprov-jdk18on</artifactId>
|
|
||||||
<version>1.84</version>
|
|
||||||
</dependency>
|
|
||||||
<!-- Google Tink : runtime requis par com.nimbusds.jose.crypto.Ed25519Verifier
|
|
||||||
(depuis Nimbus 9.x, la verification EdDSA delegue a Tink.subtle.Ed25519Verify).
|
|
||||||
Tink n'est PAS une dependance transitive de nimbus-jose-jwt → il faut
|
|
||||||
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify().
|
|
||||||
>= 1.15 : embarque un protobuf-java corrige (CVE-2024-7254). -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.crypto.tink</groupId>
|
|
||||||
<artifactId>tink</artifactId>
|
|
||||||
<version>1.21.0</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif :
|
<!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif :
|
||||||
compatible distribution bureau locale via jpackage). Sert l'export PDF
|
compatible distribution bureau locale via jpackage). Sert l'export PDF
|
||||||
d'une campagne (livret). -->
|
d'une campagne (livret). -->
|
||||||
|
|||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CampaignContentSearchService {
|
||||||
|
private final CampaignContentSearchRepository repository;
|
||||||
|
|
||||||
|
public CampaignContentSearchService(CampaignContentSearchRepository repository) {
|
||||||
|
this.repository = repository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<CampaignContentHit> search(String query) {
|
||||||
|
String value = query == null ? "" : query.strip();
|
||||||
|
return value.length() < 2 ? List.of() : repository.searchByName(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
|||||||
import com.loremind.application.playcontext.PlaythroughService;
|
import com.loremind.application.playcontext.PlaythroughService;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
@@ -108,6 +109,23 @@ public class CampaignService {
|
|||||||
campaignRepository.save(campaign);
|
campaignRepository.save(campaign);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fiche « Publication » de la campagne (vide si jamais renseignée). */
|
||||||
|
public CampaignPublication getPublication(String id) {
|
||||||
|
Campaign campaign = campaignRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||||
|
return campaign.getPublication() != null ? campaign.getPublication() : CampaignPublication.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remplace la fiche « Publication » (nettoyée : blancs → vide, longueurs bornées). */
|
||||||
|
public CampaignPublication updatePublication(String id, CampaignPublication publication) {
|
||||||
|
Campaign campaign = campaignRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||||
|
CampaignPublication clean = publication != null ? publication.normalized() : CampaignPublication.empty();
|
||||||
|
campaign.setPublication(clean.hasContent() ? clean : null);
|
||||||
|
campaignRepository.save(campaign);
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
|
||||||
private String normalizeId(String id) {
|
private String normalizeId(String id) {
|
||||||
return (id == null || id.isBlank()) ? null : id;
|
return (id == null || id.isBlank()) ? null : id;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IA des méthodes guidées (Mentor d'écriture) : propose des réponses aux questions d'une
|
||||||
|
* méthode à partir de l'idée de départ du MJ et de la campagne. Rien n'est enregistré : le
|
||||||
|
* front remplit les champs vides et le MJ relit, corrige ou relance.
|
||||||
|
*
|
||||||
|
* <p>Garde-fous : nombre de questions et longueur des textes bornés (le prompt reste
|
||||||
|
* raisonnable) ; en retour, seules les clés demandées sont gardées, et une question à choix
|
||||||
|
* n'accepte qu'une des valeurs proposées.</p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class GuidedAssistService {
|
||||||
|
|
||||||
|
static final int MAX_QUESTIONS = 80;
|
||||||
|
static final int MAX_TEXT = 4_000;
|
||||||
|
|
||||||
|
private final GuidedMethodAssistant assistant;
|
||||||
|
private final CampaignContextFormatter contextFormatter;
|
||||||
|
|
||||||
|
public GuidedAssistService(GuidedMethodAssistant assistant, CampaignContextFormatter contextFormatter) {
|
||||||
|
this.assistant = assistant;
|
||||||
|
this.contextFormatter = contextFormatter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Demande à proposer des réponses. @throws IllegalArgumentException aucune question valide */
|
||||||
|
public Map<String, String> suggest(String campaignId, String methodName, String principle, String idea,
|
||||||
|
List<Question> questions, Map<String, String> existing) {
|
||||||
|
List<Question> valid = questions == null ? List.of() : questions.stream()
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.filter(q -> q.key() != null && !q.key().isBlank())
|
||||||
|
.limit(MAX_QUESTIONS)
|
||||||
|
.toList();
|
||||||
|
if (valid.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Aucune question à laquelle répondre.");
|
||||||
|
}
|
||||||
|
Map<String, String> answers = assistant.answer(cap(methodName), cap(principle), cap(idea),
|
||||||
|
contextFormatter.format(campaignId), valid, capAll(existing));
|
||||||
|
return keepValid(answers, valid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clés demandées uniquement, valeurs non vides ; choix limités aux valeurs proposées. */
|
||||||
|
static Map<String, String> keepValid(Map<String, String> answers, List<Question> questions) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (answers == null) return out;
|
||||||
|
Map<String, Question> byKey = questions.stream()
|
||||||
|
.collect(Collectors.toMap(Question::key, q -> q, (a, b) -> a, LinkedHashMap::new));
|
||||||
|
for (Map.Entry<String, String> e : answers.entrySet()) {
|
||||||
|
Question q = byKey.get(e.getKey());
|
||||||
|
String value = e.getValue() == null ? "" : e.getValue().trim();
|
||||||
|
if (q == null || value.isEmpty()) continue;
|
||||||
|
if (q.options() != null && !q.options().isEmpty()) {
|
||||||
|
Set<String> allowed = q.options().stream().map(Choice::value).collect(Collectors.toSet());
|
||||||
|
if (!allowed.contains(value)) continue;
|
||||||
|
}
|
||||||
|
out.put(q.key(), cap(value));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, String> capAll(Map<String, String> existing) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (existing == null) return out;
|
||||||
|
existing.forEach((k, v) -> {
|
||||||
|
if (k != null && v != null && !v.isBlank()) out.put(k, cap(v.trim()));
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String cap(String s) {
|
||||||
|
if (s == null) return "";
|
||||||
|
return s.length() > MAX_TEXT ? s.substring(0, MAX_TEXT) : s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Squelette d'aventure produit par une méthode guidée (Mentor d'écriture, phase M3 —
|
||||||
|
* voir docs/conception-mentor-ecriture.md) : un chapitre et ses scènes, rédigés par le MJ
|
||||||
|
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
||||||
|
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
||||||
|
*
|
||||||
|
* <p>Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre
|
||||||
|
* est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite).
|
||||||
|
* Exactement l'un des deux.</p>
|
||||||
|
*
|
||||||
|
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
|
||||||
|
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
||||||
|
* @param chapter le chapitre (nom obligatoire)
|
||||||
|
* @param scenes les scènes, dans l'ordre (au moins une avec un nom)
|
||||||
|
* @param linkSequentially relier chaque scène à la suivante par une sortie
|
||||||
|
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
|
||||||
|
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
|
||||||
|
* une enquête en nœuds relie ses pistes en réseau, pas en chaîne
|
||||||
|
* @param clock horloge à créer dans chaque partie de la campagne (plan du méchant), ou {@code null}
|
||||||
|
*/
|
||||||
|
public record GuidedSkeleton(
|
||||||
|
String arcId,
|
||||||
|
String newArcName,
|
||||||
|
ChapterSpec chapter,
|
||||||
|
List<SceneSpec> scenes,
|
||||||
|
boolean linkSequentially,
|
||||||
|
String linkLabel,
|
||||||
|
List<LinkSpec> links,
|
||||||
|
ClockSpec clock
|
||||||
|
) {
|
||||||
|
|
||||||
|
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
|
||||||
|
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||||
|
boolean linkSequentially, String linkLabel) {
|
||||||
|
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
|
||||||
|
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes,
|
||||||
|
String gmNotes) {
|
||||||
|
public ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||||
|
this(name, description, playerObjectives, narrativeStakes, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lien d'une scène vers une autre, par position dans {@code scenes}.
|
||||||
|
*
|
||||||
|
* @param from index de la scène de départ
|
||||||
|
* @param to index de la scène d'arrivée
|
||||||
|
* @param label libellé du lien (langue du MJ)
|
||||||
|
* @param kind nature du lien (sortie, piste, indice) ; {@code null} = sortie
|
||||||
|
*/
|
||||||
|
public record LinkSpec(int from, int to, String label, LinkType kind) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Horloge de progression à créer dans chaque partie (Playthrough) de la campagne.
|
||||||
|
*
|
||||||
|
* @param name nom de l'horloge
|
||||||
|
* @param description ce qui arrive quand elle est pleine
|
||||||
|
* @param segments nombre de segments (une étape du plan = un segment)
|
||||||
|
*/
|
||||||
|
public record ClockSpec(String name, String description, int segments) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record SceneSpec(
|
||||||
|
String name, String description, SceneType type, String location,
|
||||||
|
String choicesConsequences, String gmSecretNotes, String enemies) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ce qui a été créé, pour que le front ouvre directement le chapitre.
|
||||||
|
*
|
||||||
|
* @param clocks nombre d'horloges créées (une par partie de la campagne)
|
||||||
|
*/
|
||||||
|
public record Result(String arcId, String chapterId, List<String> sceneIds, int clocks) {
|
||||||
|
public Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||||
|
this(arcId, chapterId, sceneIds, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+217
@@ -0,0 +1,217 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.application.playcontext.ClockService;
|
||||||
|
import com.loremind.domain.playcontext.ClockTrigger;
|
||||||
|
import com.loremind.domain.playcontext.Playthrough;
|
||||||
|
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persiste d'un bloc le squelette d'une méthode guidée (Mentor d'écriture, phase M3) :
|
||||||
|
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
||||||
|
*
|
||||||
|
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
|
||||||
|
* arc et le nouveau chapitre se placent à la suite). Transactionnel : tout ou rien.</p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class GuidedSkeletonService {
|
||||||
|
|
||||||
|
private final ArcRepository arcRepository;
|
||||||
|
private final ChapterRepository chapterRepository;
|
||||||
|
private final SceneRepository sceneRepository;
|
||||||
|
private final ArcService arcService;
|
||||||
|
private final ChapterService chapterService;
|
||||||
|
private final SceneService sceneService;
|
||||||
|
private final PlaythroughRepository playthroughRepository;
|
||||||
|
private final ClockService clockService;
|
||||||
|
|
||||||
|
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository,
|
||||||
|
SceneRepository sceneRepository,
|
||||||
|
ArcService arcService,
|
||||||
|
ChapterService chapterService,
|
||||||
|
SceneService sceneService,
|
||||||
|
PlaythroughRepository playthroughRepository,
|
||||||
|
ClockService clockService) {
|
||||||
|
this.arcRepository = arcRepository;
|
||||||
|
this.chapterRepository = chapterRepository;
|
||||||
|
this.sceneRepository = sceneRepository;
|
||||||
|
this.arcService = arcService;
|
||||||
|
this.chapterService = chapterService;
|
||||||
|
this.sceneService = sceneService;
|
||||||
|
this.playthroughRepository = playthroughRepository;
|
||||||
|
this.clockService = clockService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
||||||
|
* arc d'une autre campagne ou non linéaire)
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||||
|
validate(skeleton);
|
||||||
|
String arcId = resolveArc(campaignId, skeleton);
|
||||||
|
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||||
|
|
||||||
|
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
|
||||||
|
List<Scene> scenes = new ArrayList<>();
|
||||||
|
List<Scene> byIndex = new ArrayList<>();
|
||||||
|
int order = 0;
|
||||||
|
for (GuidedSkeleton.SceneSpec spec : skeleton.scenes()) {
|
||||||
|
if (spec == null || isBlank(spec.name())) {
|
||||||
|
byIndex.add(null);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Scene created = sceneService.createScene(Scene.builder()
|
||||||
|
.name(spec.name().trim())
|
||||||
|
.description(blankToNull(spec.description()))
|
||||||
|
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
|
||||||
|
.location(blankToNull(spec.location()))
|
||||||
|
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
||||||
|
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
||||||
|
.enemies(blankToNull(spec.enemies()))
|
||||||
|
.chapterId(chapter.getId())
|
||||||
|
.order(order++)
|
||||||
|
.build());
|
||||||
|
scenes.add(created);
|
||||||
|
byIndex.add(created);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skeleton.linkSequentially()) {
|
||||||
|
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||||
|
}
|
||||||
|
if (skeleton.links() != null && !skeleton.links().isEmpty()) {
|
||||||
|
linkExplicitly(byIndex, skeleton.links());
|
||||||
|
}
|
||||||
|
int clocks = createClocks(campaignId, skeleton.clock());
|
||||||
|
|
||||||
|
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList(), clocks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liens explicites (réseau d'une enquête) : ajoutés aux sorties existantes. Un lien vers
|
||||||
|
* ou depuis une scène ignorée (sans nom), hors limites ou en boucle sur soi est écarté.
|
||||||
|
*/
|
||||||
|
private void linkExplicitly(List<Scene> byIndex, List<GuidedSkeleton.LinkSpec> links) {
|
||||||
|
java.util.Map<String, Scene> touched = new java.util.LinkedHashMap<>();
|
||||||
|
for (GuidedSkeleton.LinkSpec link : links) {
|
||||||
|
if (link == null || link.from() == link.to()) continue;
|
||||||
|
Scene from = at(byIndex, link.from());
|
||||||
|
Scene to = at(byIndex, link.to());
|
||||||
|
if (from == null || to == null) continue;
|
||||||
|
List<SceneBranch> branches = from.getBranches() == null ? new ArrayList<>() : new ArrayList<>(from.getBranches());
|
||||||
|
String label = isBlank(link.label()) ? to.getName() : link.label().trim();
|
||||||
|
branches.add(new SceneBranch(label, to.getId(), null,
|
||||||
|
Objects.requireNonNullElse(link.kind(), LinkType.EXIT)));
|
||||||
|
from.setBranches(branches);
|
||||||
|
touched.put(from.getId(), from);
|
||||||
|
}
|
||||||
|
touched.values().forEach(sceneRepository::save);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Scene at(List<Scene> byIndex, int index) {
|
||||||
|
return index >= 0 && index < byIndex.size() ? byIndex.get(index) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Horloge du plan (méthode « Plan du méchant ») : créée dans chaque partie de la campagne,
|
||||||
|
* car une horloge est de l'état de partie. Aucune partie : rien n'est créé (le MJ la
|
||||||
|
* créera quand il lancera une partie).
|
||||||
|
*/
|
||||||
|
private int createClocks(String campaignId, GuidedSkeleton.ClockSpec clock) {
|
||||||
|
if (clock == null || isBlank(clock.name())) return 0;
|
||||||
|
int count = 0;
|
||||||
|
for (Playthrough p : playthroughRepository.findByCampaignId(campaignId)) {
|
||||||
|
clockService.create(p.getId(), clock.name().trim(), blankToNull(clock.description()),
|
||||||
|
clock.segments(), ClockTrigger.NONE, null, null);
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void validate(GuidedSkeleton skeleton) {
|
||||||
|
if (skeleton == null) {
|
||||||
|
throw new IllegalArgumentException("Squelette manquant.");
|
||||||
|
}
|
||||||
|
boolean hasArc = !isBlank(skeleton.arcId());
|
||||||
|
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
||||||
|
if (hasArc == hasNewArc) {
|
||||||
|
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
||||||
|
}
|
||||||
|
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
||||||
|
throw new IllegalArgumentException("Le chapitre doit avoir un nom.");
|
||||||
|
}
|
||||||
|
if (skeleton.scenes() == null || skeleton.scenes().stream().noneMatch(s -> s != null && !isBlank(s.name()))) {
|
||||||
|
throw new IllegalArgumentException("Il faut au moins une scène nommée.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Arc existant (vérifié : même campagne, linéaire) ou nouvel arc linéaire placé à la suite. */
|
||||||
|
private String resolveArc(String campaignId, GuidedSkeleton skeleton) {
|
||||||
|
List<Arc> arcs = arcRepository.findByCampaignId(campaignId);
|
||||||
|
if (!isBlank(skeleton.arcId())) {
|
||||||
|
Arc arc = arcs.stream().filter(a -> skeleton.arcId().equals(a.getId())).findFirst()
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
|
||||||
|
if (arc.getType() != ArcType.LINEAR) {
|
||||||
|
throw new IllegalArgumentException("Une méthode guidée s'ajoute à un arc linéaire.");
|
||||||
|
}
|
||||||
|
return arc.getId();
|
||||||
|
}
|
||||||
|
// L'arc SYSTEM (« Quêtes libres », ordre 9999) reste en dernier : on ne le compte pas.
|
||||||
|
int nextOrder = arcs.stream().filter(a -> a.getType() != ArcType.SYSTEM)
|
||||||
|
.mapToInt(Arc::getOrder).max().orElse(-1) + 1;
|
||||||
|
return arcService.createArc(Arc.builder()
|
||||||
|
.name(skeleton.newArcName().trim())
|
||||||
|
.campaignId(campaignId)
|
||||||
|
.type(ArcType.LINEAR)
|
||||||
|
.order(nextOrder)
|
||||||
|
.build()).getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec) {
|
||||||
|
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
||||||
|
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
||||||
|
return chapterService.createChapter(Chapter.builder()
|
||||||
|
.name(spec.name().trim())
|
||||||
|
.description(blankToNull(spec.description()))
|
||||||
|
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||||
|
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||||
|
.gmNotes(blankToNull(spec.gmNotes()))
|
||||||
|
.arcId(arcId)
|
||||||
|
.order(nextOrder)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chaque scène reçoit une sortie vers la suivante (la dernière n'en a pas). */
|
||||||
|
private void linkInChain(List<Scene> scenes, String label) {
|
||||||
|
for (int i = 0; i < scenes.size() - 1; i++) {
|
||||||
|
Scene scene = scenes.get(i);
|
||||||
|
scene.setBranches(new ArrayList<>(List.of(
|
||||||
|
new SceneBranch(label, scenes.get(i + 1).getId(), null, LinkType.EXIT))));
|
||||||
|
sceneRepository.save(scene);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String s) {
|
||||||
|
return s == null || s.isBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String blankToNull(String s) {
|
||||||
|
return isBlank(s) ? null : s.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||||
import com.loremind.domain.shared.ReorderSupport;
|
import com.loremind.domain.shared.ReorderSupport;
|
||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -29,8 +30,17 @@ public class NpcService {
|
|||||||
String campaignId,
|
String campaignId,
|
||||||
List<String> relatedPageIds,
|
List<String> relatedPageIds,
|
||||||
String folder,
|
String folder,
|
||||||
Integer order
|
Integer order,
|
||||||
) {}
|
/** Rôle dans l'histoire ; null = inchangé (mise à jour) / non renseigné (création). */
|
||||||
|
NpcStory story
|
||||||
|
) {
|
||||||
|
public NpcData(String name, String portraitImageId, String headerImageId, Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues, Map<String, Map<String, String>> keyValueValues,
|
||||||
|
String campaignId, List<String> relatedPageIds, String folder, Integer order) {
|
||||||
|
this(name, portraitImageId, headerImageId, values, imageValues, keyValueValues, campaignId,
|
||||||
|
relatedPageIds, folder, order, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public Npc createNpc(NpcData data) {
|
public Npc createNpc(NpcData data) {
|
||||||
int order = data.order() != null
|
int order = data.order() != null
|
||||||
@@ -47,6 +57,7 @@ public class NpcService {
|
|||||||
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
|
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
|
||||||
.folder(normalizeFolder(data.folder()))
|
.folder(normalizeFolder(data.folder()))
|
||||||
.order(order)
|
.order(order)
|
||||||
|
.story(cleanStory(data.story()))
|
||||||
.build();
|
.build();
|
||||||
return npcRepository.save(npc);
|
return npcRepository.save(npc);
|
||||||
}
|
}
|
||||||
@@ -70,12 +81,22 @@ public class NpcService {
|
|||||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||||
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
|
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
|
||||||
existing.setFolder(normalizeFolder(data.folder()));
|
existing.setFolder(normalizeFolder(data.folder()));
|
||||||
|
if (data.story() != null) {
|
||||||
|
existing.setStory(cleanStory(data.story()));
|
||||||
|
}
|
||||||
if (data.order() != null) {
|
if (data.order() != null) {
|
||||||
existing.setOrder(data.order());
|
existing.setOrder(data.order());
|
||||||
}
|
}
|
||||||
return npcRepository.save(existing);
|
return npcRepository.save(existing);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fiche nettoyée, ou null si elle est vide (rien à stocker). */
|
||||||
|
private static NpcStory cleanStory(NpcStory story) {
|
||||||
|
if (story == null) return null;
|
||||||
|
NpcStory clean = story.normalized();
|
||||||
|
return clean.hasContent() ? clean : null;
|
||||||
|
}
|
||||||
|
|
||||||
public void deleteNpc(String id) {
|
public void deleteNpc(String id) {
|
||||||
npcRepository.deleteById(id);
|
npcRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -106,6 +106,11 @@ public class QuestService {
|
|||||||
/** Le chapitre est-il un CONTENEUR de cette quête (jumeau hub ou hébergé en arc SYSTEM) ? */
|
/** Le chapitre est-il un CONTENEUR de cette quête (jumeau hub ou hébergé en arc SYSTEM) ? */
|
||||||
private boolean isContainerOf(Quest quest, Chapter chapter) {
|
private boolean isContainerOf(Quest quest, Chapter chapter) {
|
||||||
if (Objects.equals(quest.getArcId(), chapter.getArcId())) return true;
|
if (Objects.equals(quest.getArcId(), chapter.getArcId())) return true;
|
||||||
|
return inSystemArc(chapter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le chapitre vit-il dans l'arc technique SYSTEM (masqué partout dans l'appli) ? */
|
||||||
|
private boolean inSystemArc(Chapter chapter) {
|
||||||
return chapter.getArcId() != null && arcRepository.findById(chapter.getArcId())
|
return chapter.getArcId() != null && arcRepository.findById(chapter.getArcId())
|
||||||
.map(a -> a.getType() == ArcType.SYSTEM)
|
.map(a -> a.getType() == ArcType.SYSTEM)
|
||||||
.orElse(false);
|
.orElse(false);
|
||||||
@@ -156,6 +161,18 @@ public class QuestService {
|
|||||||
/**
|
/**
|
||||||
* Supprime la quête et, en cascade, ses {@code QuestProgression} dans toutes les Parties.
|
* Supprime la quête et, en cascade, ses {@code QuestProgression} dans toutes les Parties.
|
||||||
*
|
*
|
||||||
|
* <p>Nettoyage du CONTENEUR (chapitre jumeau, jamais un chapitre simplement LIÉ —
|
||||||
|
* isContainerOf exclut les liens transversaux) :
|
||||||
|
* <ul>
|
||||||
|
* <li>jumeau de HUB non vide : GARDÉ — il redevient un chapitre visible de l'arc,
|
||||||
|
* aucune perte de contenu ;</li>
|
||||||
|
* <li>conteneur d'arc SYSTEM (quête libre) : supprimé AVEC ses scènes — une fois la
|
||||||
|
* quête partie il est invisible partout dans l'appli et pourrirait en fantôme
|
||||||
|
* (réapparitions dans les exports). L'impact est annoncé au préalable par
|
||||||
|
* {@link #getDeletionImpact} (dialogue de confirmation côté front) ;</li>
|
||||||
|
* <li>conteneur encore référencé par une autre quête : jamais touché.</li>
|
||||||
|
* </ul></p>
|
||||||
|
*
|
||||||
* <p>Limite connue (nettoyage prévu Phase 5) : les {@code Prerequisite.QuestCompleted}
|
* <p>Limite connue (nettoyage prévu Phase 5) : les {@code Prerequisite.QuestCompleted}
|
||||||
* d'autres quêtes qui pointaient celle-ci restent pendants, sans être signalés ni
|
* d'autres quêtes qui pointaient celle-ci restent pendants, sans être signalés ni
|
||||||
* nettoyés. Échec sûr aujourd'hui : un prérequis vers une quête supprimée n'est jamais
|
* nettoyés. Échec sûr aujourd'hui : un prérequis vers une quête supprimée n'est jamais
|
||||||
@@ -167,28 +184,47 @@ public class QuestService {
|
|||||||
progressionRepository.deleteByQuestId(id);
|
progressionRepository.deleteByQuestId(id);
|
||||||
questRepository.deleteById(id);
|
questRepository.deleteById(id);
|
||||||
if (quest == null) return;
|
if (quest == null) return;
|
||||||
// Nettoyage du CONTENEUR (jumeau hub ou hébergé en arc SYSTEM) : un chapitre VIDE
|
|
||||||
// (aucune scène), plus référencé par aucune autre quête, ne doit pas réapparaître
|
|
||||||
// comme « chapitre vide » fantôme. S'il contient des scènes, on le GARDE (aucune
|
|
||||||
// perte de contenu). Les chapitres simplement LIÉS (quête transversale pointant du
|
|
||||||
// contenu réel d'un autre arc) ne sont JAMAIS touchés — isContainerOf les exclut.
|
|
||||||
List<Quest> remaining = questRepository.findByCampaignId(quest.getCampaignId());
|
List<Quest> remaining = questRepository.findByCampaignId(quest.getCampaignId());
|
||||||
for (QuestNodeRef node : nullSafeNodes(quest.getNodes())) {
|
for (QuestNodeRef node : nullSafeNodes(quest.getNodes())) {
|
||||||
if (node.nodeType() != NodeType.CHAPTER) continue;
|
if (node.nodeType() != NodeType.CHAPTER) continue;
|
||||||
chapterRepository.findById(node.nodeId()).ifPresent(ch -> {
|
chapterRepository.findById(node.nodeId()).ifPresent(ch -> {
|
||||||
boolean container = isContainerOf(quest, ch);
|
boolean container = isContainerOf(quest, ch);
|
||||||
boolean empty = sceneRepository.findByChapterId(ch.getId()).isEmpty();
|
|
||||||
boolean referencedElsewhere = remaining.stream()
|
boolean referencedElsewhere = remaining.stream()
|
||||||
.anyMatch(q -> nullSafeNodes(q.getNodes()).stream()
|
.anyMatch(q -> nullSafeNodes(q.getNodes()).stream()
|
||||||
.anyMatch(n -> n.nodeType() == NodeType.CHAPTER
|
.anyMatch(n -> n.nodeType() == NodeType.CHAPTER
|
||||||
&& ch.getId().equals(n.nodeId())));
|
&& ch.getId().equals(n.nodeId())));
|
||||||
if (container && empty && !referencedElsewhere) {
|
if (!container || referencedElsewhere) return;
|
||||||
chapterRepository.deleteById(ch.getId());
|
var scenes = sceneRepository.findByChapterId(ch.getId());
|
||||||
}
|
if (!scenes.isEmpty() && !inSystemArc(ch)) return; // jumeau de hub : reste visible
|
||||||
|
for (var scene : scenes) sceneRepository.deleteById(scene.getId());
|
||||||
|
chapterRepository.deleteById(ch.getId());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Scènes qui tomberont avec la quête (conteneurs d'arc SYSTEM exclusifs à cette quête). */
|
||||||
|
public record DeletionImpact(int scenes) {}
|
||||||
|
|
||||||
|
public DeletionImpact getDeletionImpact(String questId) {
|
||||||
|
Quest quest = questRepository.findById(questId).orElse(null);
|
||||||
|
if (quest == null) return new DeletionImpact(0);
|
||||||
|
List<Quest> others = questRepository.findByCampaignId(quest.getCampaignId()).stream()
|
||||||
|
.filter(q -> !questId.equals(q.getId()))
|
||||||
|
.toList();
|
||||||
|
int scenes = 0;
|
||||||
|
for (QuestNodeRef node : nullSafeNodes(quest.getNodes())) {
|
||||||
|
if (node.nodeType() != NodeType.CHAPTER) continue;
|
||||||
|
Chapter ch = chapterRepository.findById(node.nodeId()).orElse(null);
|
||||||
|
if (ch == null || !isContainerOf(quest, ch) || !inSystemArc(ch)) continue;
|
||||||
|
boolean referencedElsewhere = others.stream()
|
||||||
|
.anyMatch(q -> nullSafeNodes(q.getNodes()).stream()
|
||||||
|
.anyMatch(n -> n.nodeType() == NodeType.CHAPTER
|
||||||
|
&& ch.getId().equals(n.nodeId())));
|
||||||
|
if (!referencedElsewhere) scenes += sceneRepository.findByChapterId(ch.getId()).size();
|
||||||
|
}
|
||||||
|
return new DeletionImpact(scenes);
|
||||||
|
}
|
||||||
|
|
||||||
private static List<QuestNodeRef> nullSafeNodes(List<QuestNodeRef> nodes) {
|
private static List<QuestNodeRef> nullSafeNodes(List<QuestNodeRef> nodes) {
|
||||||
return nodes != null ? nodes : List.of();
|
return nodes != null ? nodes : List.of();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,6 +125,8 @@ public class SceneService {
|
|||||||
case "playerNarration" -> scene.setPlayerNarration(value);
|
case "playerNarration" -> scene.setPlayerNarration(value);
|
||||||
case "choicesConsequences" -> scene.setChoicesConsequences(value);
|
case "choicesConsequences" -> scene.setChoicesConsequences(value);
|
||||||
case "combatDifficulty" -> scene.setCombatDifficulty(value);
|
case "combatDifficulty" -> scene.setCombatDifficulty(value);
|
||||||
|
case "tactics" -> scene.setTactics(value);
|
||||||
|
case "purpose" -> scene.setPurpose(value);
|
||||||
case "enemies" -> scene.setEnemies(value);
|
case "enemies" -> scene.setEnemies(value);
|
||||||
case "gmSecretNotes" -> scene.setGmSecretNotes(value);
|
case "gmSecretNotes" -> scene.setGmSecretNotes(value);
|
||||||
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
|
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||||
|
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Une remarque de relecture d'éditeur (Mentor d'écriture, phase M2) : un conseil
|
||||||
|
* d'auteur sur la QUALITÉ de l'écriture, pas sur la complétude (ça, c'est le readiness).
|
||||||
|
*
|
||||||
|
* <p>Contrairement à {@link ReadinessGap}, le back ne rédige pas le texte : il
|
||||||
|
* renvoie la règle et ses paramètres, et le front compose observation / pourquoi /
|
||||||
|
* question depuis l'i18n ({@code writingReview.rules.<ruleId>}), en fr comme en en.</p>
|
||||||
|
*
|
||||||
|
* @param entityType type de l'entité concernée (réutilise celui du readiness pour les liens profonds)
|
||||||
|
* @param entityId id de l'entité concernée
|
||||||
|
* @param entityName libellé lisible de l'entité
|
||||||
|
* @param ruleId identifiant stable de la règle (ex. {@code WRITE-002-FAKE-CHOICE})
|
||||||
|
* @param category famille de la remarque (regroupement à l'affichage)
|
||||||
|
* @param params valeurs à injecter dans le texte i18n (ex. {@code count}, {@code phrase})
|
||||||
|
* @param arcId arc parent (navigation), ou {@code null}
|
||||||
|
* @param chapterId chapitre parent (navigation), ou {@code null}
|
||||||
|
*/
|
||||||
|
public record WritingRemark(
|
||||||
|
ReadinessEntityType entityType,
|
||||||
|
String entityId,
|
||||||
|
String entityName,
|
||||||
|
String ruleId,
|
||||||
|
WritingRemarkCategory category,
|
||||||
|
Map<String, String> params,
|
||||||
|
String arcId,
|
||||||
|
String chapterId
|
||||||
|
) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relecture d'éditeur d'une campagne (Mentor d'écriture, phase M2).
|
||||||
|
*
|
||||||
|
* @param campaignId campagne relue
|
||||||
|
* @param remarks remarques dans l'ordre de l'arbre (campagne, puis arc par arc)
|
||||||
|
*/
|
||||||
|
public record WritingReviewReport(String campaignId, List<WritingRemark> remarks) {
|
||||||
|
}
|
||||||
+539
@@ -0,0 +1,539 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||||
|
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relecture d'éditeur (Mentor d'écriture, phase M2 — voir docs/conception-mentor-ecriture.md) :
|
||||||
|
* conseils d'auteur sur la QUALITÉ de l'écriture (vrais choix, rythme, enjeux, narration),
|
||||||
|
* là où le readiness ({@link CampaignReadinessService}) ne juge que la complétude.
|
||||||
|
*
|
||||||
|
* <p><b>Déterministe, sans IA, sans persistance</b> ; même chargement en une passe que le
|
||||||
|
* readiness (arcs → chapitres → scènes). Purement indicatif : une remarque est un conseil,
|
||||||
|
* jamais un blocage. Le texte est composé côté front à partir de {@code ruleId} + {@code params}.</p>
|
||||||
|
*
|
||||||
|
* <p>L'arc SYSTEM (« Quêtes libres ») est de la plomberie invisible : ses chapitres-conteneurs
|
||||||
|
* ne reçoivent pas de remarque de niveau chapitre, mais leurs scènes sont relues comme les autres.</p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class WritingReviewService {
|
||||||
|
|
||||||
|
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
|
||||||
|
static final int CORRIDOR_MIN_SCENES = 3;
|
||||||
|
/** WRITE-003 : nombre minimal de scènes menant à une révélation (règle des 3 indices). */
|
||||||
|
static final int REVELATION_MIN_INCOMING = 3;
|
||||||
|
/** WRITE-011 / 012 / 014 : un chapitre « qui utilise le graphe » a au moins ce nombre de scènes reliées. */
|
||||||
|
static final int LINKED_MIN_SCENES = 2;
|
||||||
|
/** WRITE-012 : taille minimale d'un chapitre pour juger un passage obligé. */
|
||||||
|
static final int CHOKEPOINT_MIN_SCENES = 4;
|
||||||
|
/** WRITE-013 : nombre minimal de pièces pour juger la forme d'un donjon. */
|
||||||
|
static final int DUNGEON_MIN_ROOMS = 4;
|
||||||
|
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
|
||||||
|
static final int PROACTIVE_MIN_SCENES = 3;
|
||||||
|
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
||||||
|
static final int MONOTONOUS_RUN = 3;
|
||||||
|
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
||||||
|
static final int LONG_NARRATION_CHARS = 1200;
|
||||||
|
/** WRITE-010 : nombre minimal de scènes pour juger la part de scènes non typées. */
|
||||||
|
static final int UNTYPED_MIN_SCENES = 5;
|
||||||
|
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
||||||
|
static final double UNTYPED_RATIO = 0.7;
|
||||||
|
|
||||||
|
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
||||||
|
static final String KIND_COMBAT = "COMBAT";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-007 : la narration décide à la place des personnages (action ou émotion imposée).
|
||||||
|
* Volontairement restreint aux tournures sans ambiguïté, pour éviter les faux positifs.
|
||||||
|
*/
|
||||||
|
private static final Pattern NARRATION_DECIDES = Pattern.compile(
|
||||||
|
"\\b(vous (?:décidez|choisissez|ressentez|avez (?:très |si )?peur"
|
||||||
|
+ "|êtes (?:terrifié|effrayé|terrorisé|paniqué|soulagé|ému)e?s?"
|
||||||
|
+ "|entrez|vous précipitez|dégainez|attaquez|fuyez)"
|
||||||
|
+ "|you (?:decide|choose|feel (?:afraid|scared|uneasy|relieved|guilty)"
|
||||||
|
+ "|are (?:afraid|scared|terrified|relieved|panicking)"
|
||||||
|
+ "|enter|rush|draw your|attack|flee))\\b",
|
||||||
|
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.UNICODE_CHARACTER_CLASS);
|
||||||
|
|
||||||
|
private final CampaignRepository campaignRepository;
|
||||||
|
private final ArcRepository arcRepository;
|
||||||
|
private final ChapterRepository chapterRepository;
|
||||||
|
private final SceneRepository sceneRepository;
|
||||||
|
private final QuestRepository questRepository;
|
||||||
|
private final NpcRepository npcRepository;
|
||||||
|
|
||||||
|
public WritingReviewService(CampaignRepository campaignRepository,
|
||||||
|
ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository,
|
||||||
|
SceneRepository sceneRepository,
|
||||||
|
QuestRepository questRepository,
|
||||||
|
NpcRepository npcRepository) {
|
||||||
|
this.campaignRepository = campaignRepository;
|
||||||
|
this.arcRepository = arcRepository;
|
||||||
|
this.chapterRepository = chapterRepository;
|
||||||
|
this.sceneRepository = sceneRepository;
|
||||||
|
this.questRepository = questRepository;
|
||||||
|
this.npcRepository = npcRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Relit toute la campagne et renvoie les remarques dans l'ordre de l'arbre. */
|
||||||
|
public WritingReviewReport review(String campaignId) {
|
||||||
|
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
||||||
|
List<WritingRemark> treeRemarks = new ArrayList<>();
|
||||||
|
|
||||||
|
Set<String> arcsWithQuests = questRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||||
|
|
||||||
|
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||||
|
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||||
|
|
||||||
|
int totalScenes = 0;
|
||||||
|
int genericScenes = 0;
|
||||||
|
for (Arc arc : arcs) {
|
||||||
|
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||||
|
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||||
|
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
||||||
|
|
||||||
|
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
|
||||||
|
if (visibleArc && countLines(arc.getHooks()) == 1) {
|
||||||
|
treeRemarks.add(arcRemark(arc, "WRITE-017-SINGLE-HOOK", WritingRemarkCategory.AGENCY, Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
||||||
|
if (visibleArc && isBlank(arc.getStakes())
|
||||||
|
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
||||||
|
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Scene> lastChapterScenes = List.of();
|
||||||
|
for (Chapter chapter : chapters) {
|
||||||
|
List<Scene> scenes = new ArrayList<>(sceneRepository.findByChapterId(chapter.getId()));
|
||||||
|
scenes.sort(Comparator.comparingInt(Scene::getOrder));
|
||||||
|
totalScenes += scenes.size();
|
||||||
|
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
||||||
|
|
||||||
|
if (visibleArc) {
|
||||||
|
reviewChapter(arc, chapter, scenes, treeRemarks);
|
||||||
|
}
|
||||||
|
for (Scene scene : scenes) {
|
||||||
|
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||||
|
}
|
||||||
|
reviewGraph(arc, chapter, scenes, treeRemarks);
|
||||||
|
if (!scenes.isEmpty()) {
|
||||||
|
lastChapterScenes = scenes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
||||||
|
checkSingleEnding(arc, lastChapterScenes, treeRemarks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WRITE-010 — trop de scènes non typées pour juger le rythme.
|
||||||
|
if (totalScenes >= UNTYPED_MIN_SCENES && (double) genericScenes / totalScenes > UNTYPED_RATIO) {
|
||||||
|
String campaignName = campaignRepository.findById(campaignId).map(Campaign::getName).orElse(null);
|
||||||
|
int pct = (int) Math.round(100.0 * genericScenes / totalScenes);
|
||||||
|
campaignRemarks.add(new WritingRemark(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
||||||
|
"WRITE-010-UNTYPED-SCENES", WritingRemarkCategory.PACING,
|
||||||
|
Map.of("percent", String.valueOf(pct), "count", String.valueOf(genericScenes)),
|
||||||
|
null, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
|
||||||
|
remarks.addAll(treeRemarks);
|
||||||
|
remarks.addAll(reviewNpcs(campaignId));
|
||||||
|
return new WritingReviewReport(campaignId, remarks);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Niveau chapitre ---------------------------------------------------------------
|
||||||
|
|
||||||
|
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||||
|
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
||||||
|
|
||||||
|
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
||||||
|
boolean anyBranch = scenes.stream().anyMatch(WritingReviewService::hasBranches);
|
||||||
|
boolean anyChoice = scenes.stream().anyMatch(s -> !isBlank(s.getChoicesConsequences()));
|
||||||
|
if (scenes.size() >= CORRIDOR_MIN_SCENES && !anyBranch && !anyChoice) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-001-CORRIDOR", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("count", String.valueOf(scenes.size()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
// WRITE-004 — rythme monotone : N scènes d'affilée du même genre.
|
||||||
|
MonotonousRun run = findMonotonousRun(scenes);
|
||||||
|
if (run != null) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-004-MONOTONOUS-PACING", WritingRemarkCategory.PACING,
|
||||||
|
Map.of("count", String.valueOf(run.length()), "kind", run.kind())));
|
||||||
|
}
|
||||||
|
|
||||||
|
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
||||||
|
if (isBlank(chapter.getNarrativeStakes())) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// WRITE-014 — enquête sans relance : des révélations, mais aucun événement que le MJ
|
||||||
|
// peut déclencher si les joueurs tournent en rond.
|
||||||
|
boolean investigation = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.REVELATION);
|
||||||
|
boolean proactive = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.EVENT);
|
||||||
|
if (investigation && !proactive && scenes.size() >= PROACTIVE_MIN_SCENES && usesLinks(scenes)) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-014-NO-PROACTIVE", WritingRemarkCategory.PACING, Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record MonotonousRun(String kind, int length) {}
|
||||||
|
|
||||||
|
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
||||||
|
private static MonotonousRun findMonotonousRun(List<Scene> scenes) {
|
||||||
|
String currentKind = null;
|
||||||
|
int length = 0;
|
||||||
|
MonotonousRun found = null;
|
||||||
|
for (Scene scene : scenes) {
|
||||||
|
String kind = pacingKind(scene);
|
||||||
|
if (kind != null && kind.equals(currentKind)) {
|
||||||
|
length++;
|
||||||
|
} else {
|
||||||
|
if (found != null) return found;
|
||||||
|
currentKind = kind;
|
||||||
|
length = kind == null ? 0 : 1;
|
||||||
|
}
|
||||||
|
if (length >= MONOTONOUS_RUN) {
|
||||||
|
found = new MonotonousRun(currentKind, length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Genre d'une scène pour le rythme : COMBAT, sinon son type s'il est renseigné, sinon null. */
|
||||||
|
private static String pacingKind(Scene scene) {
|
||||||
|
if (isCombat(scene)) return KIND_COMBAT;
|
||||||
|
SceneType type = typeOf(scene);
|
||||||
|
return type == SceneType.GENERIC ? null : type.name();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Niveau scène -------------------------------------------------------------------
|
||||||
|
|
||||||
|
private void reviewScene(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
|
checkFakeChoice(arc, chapter, scene, chapterScenes, out);
|
||||||
|
checkSingleClue(arc, chapter, scene, chapterScenes, out);
|
||||||
|
checkNarration(arc, chapter, scene, out);
|
||||||
|
checkCombatPurpose(arc, chapter, scene, out);
|
||||||
|
checkLinearDungeon(arc, chapter, scene, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-013 — donjon en couloir : des pièces reliées entre elles, mais sans aucune boucle
|
||||||
|
* (graphe des liens = arbre). Les joueurs ne choisissent pas leur route et ne peuvent ni
|
||||||
|
* contourner un obstacle ni revenir par un autre chemin. Muet si les pièces ne sont pas reliées.
|
||||||
|
*/
|
||||||
|
private void checkLinearDungeon(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||||
|
List<Room> rooms = scene.getRooms();
|
||||||
|
if (rooms == null || rooms.size() < DUNGEON_MIN_ROOMS) return;
|
||||||
|
Set<String> ids = rooms.stream().map(Room::getId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||||
|
// Arêtes non orientées distinctes (A→B et B→A = un seul passage).
|
||||||
|
Set<String> edges = new HashSet<>();
|
||||||
|
for (Room r : rooms) {
|
||||||
|
if (r.getBranches() == null) continue;
|
||||||
|
for (RoomBranch b : r.getBranches()) {
|
||||||
|
String to = b.targetRoomId();
|
||||||
|
if (isBlank(r.getId()) || !ids.contains(to) || r.getId().equals(to)) continue;
|
||||||
|
edges.add(r.getId().compareTo(to) < 0 ? r.getId() + "|" + to : to + "|" + r.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (edges.isEmpty()) return;
|
||||||
|
int components = countComponents(ids, edges);
|
||||||
|
int loops = edges.size() - ids.size() + components;
|
||||||
|
if (loops == 0 && components == 1) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-013-LINEAR-DUNGEON", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("rooms", String.valueOf(ids.size()))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countComponents(Set<String> nodes, Set<String> edges) {
|
||||||
|
Map<String, Set<String>> adj = new HashMap<>();
|
||||||
|
for (String n : nodes) adj.put(n, new HashSet<>());
|
||||||
|
for (String e : edges) {
|
||||||
|
String[] ab = e.split("\\|", 2);
|
||||||
|
adj.get(ab[0]).add(ab[1]);
|
||||||
|
adj.get(ab[1]).add(ab[0]);
|
||||||
|
}
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
int components = 0;
|
||||||
|
for (String start : nodes) {
|
||||||
|
if (!seen.add(start)) continue;
|
||||||
|
components++;
|
||||||
|
Deque<String> stack = new ArrayDeque<>(List.of(start));
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
for (String next : adj.get(stack.pop())) {
|
||||||
|
if (seen.add(next)) stack.push(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return components;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Graphe du chapitre -------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Règles sur la forme du graphe des scènes d'un chapitre, seulement s'il utilise des liens
|
||||||
|
* (sans aucun lien, c'est WRITE-001 qui parle) : WRITE-011 scène isolée, WRITE-012 passage
|
||||||
|
* obligé. Les liens sont internes au chapitre (règle de SceneService).
|
||||||
|
*/
|
||||||
|
private void reviewGraph(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||||
|
if (!usesLinks(scenes)) return;
|
||||||
|
Map<String, Set<String>> next = successors(scenes);
|
||||||
|
Set<String> withIncoming = next.values().stream().flatMap(Set::stream).collect(Collectors.toSet());
|
||||||
|
|
||||||
|
// WRITE-011 — scène isolée : ni lien entrant ni lien sortant (hors scène d'ouverture).
|
||||||
|
for (int i = 1; i < scenes.size(); i++) {
|
||||||
|
Scene s = scenes.get(i);
|
||||||
|
if (next.get(s.getId()).isEmpty() && !withIncoming.contains(s.getId())) {
|
||||||
|
out.add(sceneRemark(arc, chapter, s, "WRITE-011-ISOLATED-SCENE", WritingRemarkCategory.PACING, Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkChokepoint(arc, chapter, scenes, next, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-012 — passage obligé : depuis la scène d'ouverture, tous les chemins vers les
|
||||||
|
* fins du chapitre traversent une même scène. Si les joueurs y échouent ou passent à côté,
|
||||||
|
* tout s'arrête. Une seule remarque par chapitre (le premier passage obligé).
|
||||||
|
*/
|
||||||
|
private void checkChokepoint(Arc arc, Chapter chapter, List<Scene> scenes, Map<String, Set<String>> next,
|
||||||
|
List<WritingRemark> out) {
|
||||||
|
if (scenes.size() < CHOKEPOINT_MIN_SCENES) return;
|
||||||
|
String entry = scenes.get(0).getId();
|
||||||
|
if (next.get(entry).isEmpty()) return;
|
||||||
|
Set<String> reachable = reach(entry, next, null);
|
||||||
|
Set<String> ends = reachable.stream().filter(id -> next.get(id).isEmpty()).collect(Collectors.toSet());
|
||||||
|
if (ends.isEmpty()) return; // Boucle sans fin : rien à juger.
|
||||||
|
|
||||||
|
List<Scene> chokepoints = new ArrayList<>();
|
||||||
|
for (Scene s : scenes) {
|
||||||
|
String id = s.getId();
|
||||||
|
if (id.equals(entry) || ends.contains(id) || !reachable.contains(id)) continue;
|
||||||
|
Set<String> without = reach(entry, next, id);
|
||||||
|
if (ends.stream().noneMatch(without::contains)) chokepoints.add(s);
|
||||||
|
}
|
||||||
|
if (chokepoints.isEmpty()) return;
|
||||||
|
out.add(sceneRemark(arc, chapter, chokepoints.get(0), "WRITE-012-CHOKEPOINT", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("count", String.valueOf(chokepoints.size()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Successeurs de chaque scène du chapitre (liens vers des scènes du même chapitre seulement). */
|
||||||
|
private static Map<String, Set<String>> successors(List<Scene> scenes) {
|
||||||
|
Set<String> ids = scenes.stream().map(Scene::getId).collect(Collectors.toSet());
|
||||||
|
Map<String, Set<String>> next = new HashMap<>();
|
||||||
|
for (Scene s : scenes) {
|
||||||
|
Set<String> targets = new LinkedHashSet<>();
|
||||||
|
if (s.getBranches() != null) {
|
||||||
|
for (SceneBranch b : s.getBranches()) {
|
||||||
|
String to = b.targetSceneId();
|
||||||
|
if (ids.contains(to) && !to.equals(s.getId())) targets.add(to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next.put(s.getId(), targets);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scènes atteignables depuis {@code from} en suivant les liens, sans passer par {@code removed}. */
|
||||||
|
private static Set<String> reach(String from, Map<String, Set<String>> next, String removed) {
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
Deque<String> stack = new ArrayDeque<>(List.of(from));
|
||||||
|
seen.add(from);
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
for (String n : next.getOrDefault(stack.pop(), Set.of())) {
|
||||||
|
if (!n.equals(removed) && seen.add(n)) stack.push(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return seen;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le chapitre utilise le graphe : au moins {@link #LINKED_MIN_SCENES} scènes portent des liens. */
|
||||||
|
private static boolean usesLinks(List<Scene> scenes) {
|
||||||
|
return scenes.stream().filter(WritingReviewService::hasBranches).count() >= LINKED_MIN_SCENES;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WRITE-002 — faux carrefour : plusieurs sorties qui mènent toutes au même endroit. */
|
||||||
|
private void checkFakeChoice(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
|
List<SceneBranch> branches = scene.getBranches();
|
||||||
|
if (branches == null || branches.size() < 2) return;
|
||||||
|
Set<String> targets = branches.stream().map(SceneBranch::targetSceneId).collect(Collectors.toSet());
|
||||||
|
if (targets.size() != 1) return;
|
||||||
|
String target = targets.iterator().next();
|
||||||
|
if (isBlank(target)) return; // Branche cassée : c'est l'affaire du readiness (SCENE-010).
|
||||||
|
String targetName = chapterScenes.stream()
|
||||||
|
.filter(s -> target.equals(s.getId())).map(Scene::getName)
|
||||||
|
.filter(n -> !isBlank(n)).findFirst().orElse("?");
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-002-FAKE-CHOICE", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("count", String.valueOf(branches.size()), "target", targetName)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-003 — révélation à chemin unique (règle des 3 indices). Seulement dans un
|
||||||
|
* chapitre qui utilise des liens : sans aucun lien, c'est WRITE-001 qui parle.
|
||||||
|
*/
|
||||||
|
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
|
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||||
|
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||||
|
List<Scene> sources = chapterScenes.stream()
|
||||||
|
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||||
|
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
|
||||||
|
.toList();
|
||||||
|
if (sources.size() < REVELATION_MIN_INCOMING) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("incoming", String.valueOf(sources.size()))));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// WRITE-015 — assez de chemins, mais tous du même genre (que des interrogatoires…) :
|
||||||
|
// un groupe qui n'aime pas ce genre de scène passe à côté de tous les indices.
|
||||||
|
Set<SceneType> kinds = sources.stream().map(WritingReviewService::typeOf).collect(Collectors.toSet());
|
||||||
|
if (kinds.size() == 1 && !kinds.contains(SceneType.GENERIC)) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-015-SAME-SOURCE-CLUES", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("kind", kinds.iterator().next().name(), "count", String.valueOf(sources.size()))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WRITE-006 — narration trop longue ; WRITE-007 — narration qui décide à la place des PJ. */
|
||||||
|
private void checkNarration(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||||
|
String narration = scene.getPlayerNarration();
|
||||||
|
if (isBlank(narration)) return;
|
||||||
|
int length = narration.strip().length();
|
||||||
|
if (length > LONG_NARRATION_CHARS) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-006-LONG-NARRATION", WritingRemarkCategory.NARRATION,
|
||||||
|
Map.of("chars", String.valueOf(length))));
|
||||||
|
}
|
||||||
|
Matcher m = NARRATION_DECIDES.matcher(narration);
|
||||||
|
if (m.find()) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-007-NARRATION-DECIDES", WritingRemarkCategory.NARRATION,
|
||||||
|
Map.of("phrase", m.group(1))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WRITE-008 — combat sans but : ni choix décrits, ni notes sur les motivations des ennemis. */
|
||||||
|
private void checkCombatPurpose(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||||
|
if (isCombat(scene) && isBlank(scene.getChoicesConsequences()) && isBlank(scene.getGmSecretNotes())
|
||||||
|
&& isBlank(scene.getTactics())) {
|
||||||
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-008-COMBAT-NO-PURPOSE", WritingRemarkCategory.STAKES,
|
||||||
|
Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Niveau arc -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
||||||
|
private void checkSingleEnding(Arc arc, List<Scene> lastChapterScenes, List<WritingRemark> out) {
|
||||||
|
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
||||||
|
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
||||||
|
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
||||||
|
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("arc", labelOr(arc.getName(), "Arc")), arc.getId(), finale.getChapterId()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- PNJ ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-016 — opposant ou allié sans motivation : un PNJ qui pèse sur l'intrigue doit
|
||||||
|
* vouloir quelque chose, sinon le MJ ne sait pas comment le faire réagir. Les figurants
|
||||||
|
* et les PNJ sans rôle précisé ne sont pas jugés (pas de bruit sur les seconds rôles).
|
||||||
|
*/
|
||||||
|
private List<WritingRemark> reviewNpcs(String campaignId) {
|
||||||
|
List<WritingRemark> out = new ArrayList<>();
|
||||||
|
for (Npc npc : npcRepository.findByCampaignId(campaignId)) {
|
||||||
|
NpcStory story = npc.getStory();
|
||||||
|
if (story != null && story.drivesThePlot() && story.normalized().motivation() == null) {
|
||||||
|
out.add(new WritingRemark(ReadinessEntityType.NPC, npc.getId(), labelOr(npc.getName(), "PNJ"),
|
||||||
|
"WRITE-016-NPC-NO-MOTIVATION", WritingRemarkCategory.STAKES,
|
||||||
|
Map.of("role", story.normalized().role()), null, null));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Helpers ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Nombre de lignes non vides (une accroche par ligne, puces « - » comprises). */
|
||||||
|
private static int countLines(String text) {
|
||||||
|
if (isBlank(text)) return 0;
|
||||||
|
return (int) text.lines().filter(l -> !l.isBlank()).count();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isCombat(Scene scene) {
|
||||||
|
return typeOf(scene) == SceneType.ENCOUNTER
|
||||||
|
|| !isBlank(scene.getCombatDifficulty())
|
||||||
|
|| !isBlank(scene.getEnemies())
|
||||||
|
|| (scene.getEnemyIds() != null && scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasBranches(Scene scene) {
|
||||||
|
return scene.getBranches() != null && !scene.getBranches().isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SceneType typeOf(Scene scene) {
|
||||||
|
return Objects.requireNonNullElse(scene.getType(), SceneType.GENERIC);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
||||||
|
WritingRemarkCategory category, Map<String, String> params) {
|
||||||
|
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
||||||
|
ruleId, category, params, arc.getId(), chapter.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
||||||
|
WritingRemarkCategory category, Map<String, String> params) {
|
||||||
|
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
||||||
|
ruleId, category, params, arc.getId(), chapter.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
||||||
|
Map<String, String> params) {
|
||||||
|
return new WritingRemark(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
||||||
|
ruleId, category, params, arc.getId(), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String s) {
|
||||||
|
return s == null || s.isBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String labelOr(String value, String fallback) {
|
||||||
|
return isBlank(value) ? fallback : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package com.loremind.application.campaigncontext;
|
|
||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Prerequisite;
|
|
||||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
|
||||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.TreeSet;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Service applicatif : énumère les noms de faits ({@link Prerequisite.FlagSet})
|
|
||||||
* référencés par les quêtes d'une Campagne.
|
|
||||||
*
|
|
||||||
* <p>Modèle "déclaration implicite" : il n'existe pas de table de faits déclarés
|
|
||||||
* globalement. Un fait existe dès qu'au moins une quête le référence dans ses
|
|
||||||
* prérequis. Ce service expose la liste dédupliquée pour les UIs (toggle dans
|
|
||||||
* la Partie, autocomplete dans l'éditeur de prérequis de quête).</p>
|
|
||||||
*
|
|
||||||
* <p>Niveau 1 : lit désormais les quêtes (entité de première classe), plus les
|
|
||||||
* chapitres HUB.</p>
|
|
||||||
*/
|
|
||||||
@Service
|
|
||||||
public class CampaignReferencedFlagsService {
|
|
||||||
|
|
||||||
private final QuestRepository questRepository;
|
|
||||||
|
|
||||||
public CampaignReferencedFlagsService(QuestRepository questRepository) {
|
|
||||||
this.questRepository = questRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Retourne la liste triée alphabétiquement des noms de faits référencés. */
|
|
||||||
public List<String> listForCampaign(String campaignId) {
|
|
||||||
TreeSet<String> unique = new TreeSet<>();
|
|
||||||
for (Quest quest : questRepository.findByCampaignId(campaignId)) {
|
|
||||||
if (quest.getPrerequisites() == null) continue;
|
|
||||||
for (Prerequisite p : quest.getPrerequisites()) {
|
|
||||||
if (p instanceof Prerequisite.FlagSet f && f.flagName() != null && !f.flagName().isBlank()) {
|
|
||||||
unique.add(f.flagName());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return List.copyOf(unique);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.loremind.application.licensing;
|
package com.loremind.application.channel;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
+6
-2
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.application.gamesystemcontext;
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||||
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||||
@@ -36,9 +37,11 @@ public class GameSystemContextBuilder {
|
|||||||
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
|
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
|
||||||
|
|
||||||
private final GameSystemRepository gameSystemRepository;
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
private final CurrentLanguage currentLanguage;
|
||||||
|
|
||||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
|
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository, CurrentLanguage currentLanguage) {
|
||||||
this.gameSystemRepository = gameSystemRepository;
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
this.currentLanguage = currentLanguage;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
||||||
@@ -48,7 +51,8 @@ public class GameSystemContextBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
||||||
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown());
|
// Règles dans la langue de l'interface (repli sur l'autre version si celle-ci est vide).
|
||||||
|
Map<String, String> allSections = parseH2Sections(gs.rulesFor(currentLanguage.get()));
|
||||||
Map<String, String> filtered = filterByIntent(allSections, intent);
|
Map<String, String> filtered = filterByIntent(allSections, intent);
|
||||||
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ public class GameSystemService {
|
|||||||
String name,
|
String name,
|
||||||
String description,
|
String description,
|
||||||
String rulesMarkdown,
|
String rulesMarkdown,
|
||||||
|
String rulesMarkdownEn,
|
||||||
List<TemplateField> characterTemplate,
|
List<TemplateField> characterTemplate,
|
||||||
List<TemplateField> npcTemplate,
|
List<TemplateField> npcTemplate,
|
||||||
List<TemplateField> enemyTemplate,
|
List<TemplateField> enemyTemplate,
|
||||||
@@ -72,6 +73,7 @@ public class GameSystemService {
|
|||||||
.name(data.name())
|
.name(data.name())
|
||||||
.description(data.description())
|
.description(data.description())
|
||||||
.rulesMarkdown(data.rulesMarkdown())
|
.rulesMarkdown(data.rulesMarkdown())
|
||||||
|
.rulesMarkdownEn(data.rulesMarkdownEn())
|
||||||
.foundryActorType(normalize(data.foundryActorType()))
|
.foundryActorType(normalize(data.foundryActorType()))
|
||||||
.author(normalize(data.author()))
|
.author(normalize(data.author()))
|
||||||
.isPublic(data.isPublic())
|
.isPublic(data.isPublic())
|
||||||
@@ -96,6 +98,7 @@ public class GameSystemService {
|
|||||||
existing.setName(data.name());
|
existing.setName(data.name());
|
||||||
existing.setDescription(data.description());
|
existing.setDescription(data.description());
|
||||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||||
|
existing.setRulesMarkdownEn(data.rulesMarkdownEn());
|
||||||
existing.replaceCharacterTemplate(data.characterTemplate());
|
existing.replaceCharacterTemplate(data.characterTemplate());
|
||||||
existing.replaceNpcTemplate(data.npcTemplate());
|
existing.replaceNpcTemplate(data.npcTemplate());
|
||||||
existing.replaceEnemyTemplate(data.enemyTemplate());
|
existing.replaceEnemyTemplate(data.enemyTemplate());
|
||||||
|
|||||||
@@ -1,266 +0,0 @@
|
|||||||
package com.loremind.application.licensing;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.License;
|
|
||||||
import com.loremind.domain.licensing.LicenseClaims;
|
|
||||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
|
||||||
import com.loremind.domain.licensing.LicenseStatus;
|
|
||||||
import com.loremind.domain.licensing.RegistryCredentials;
|
|
||||||
import com.loremind.domain.licensing.ports.JwtVerifier;
|
|
||||||
import com.loremind.domain.licensing.ports.LicenseRelay;
|
|
||||||
import com.loremind.domain.licensing.ports.LicenseRepository;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Service application pour la gestion de la licence Patreon.
|
|
||||||
* <p>
|
|
||||||
* Responsabilites :
|
|
||||||
* <ul>
|
|
||||||
* <li>Installer un nouveau JWT recu du relais (apres OAuth utilisateur)</li>
|
|
||||||
* <li>Calculer le {@link LicenseStatus} courant en respectant la grace period</li>
|
|
||||||
* <li>Renouveler le JWT avant expiration en appelant le relais</li>
|
|
||||||
* <li>Activer/desactiver le toggle "canal beta" cote utilisateur</li>
|
|
||||||
* <li>Distribuer les credentials registry pour le pull beta</li>
|
|
||||||
* </ul>
|
|
||||||
*/
|
|
||||||
@Service
|
|
||||||
public class LicenseService {
|
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(LicenseService.class);
|
|
||||||
|
|
||||||
private final LicenseRepository repository;
|
|
||||||
private final JwtVerifier jwtVerifier;
|
|
||||||
private final LicenseRelay relay;
|
|
||||||
private final long gracePeriodSeconds;
|
|
||||||
private final long refreshBeforeExpirySeconds;
|
|
||||||
private final boolean licensingEnabled;
|
|
||||||
|
|
||||||
public LicenseService(
|
|
||||||
LicenseRepository repository,
|
|
||||||
JwtVerifier jwtVerifier,
|
|
||||||
LicenseRelay relay,
|
|
||||||
@Value("${licensing.grace-period-days:14}") int gracePeriodDays,
|
|
||||||
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays,
|
|
||||||
@Value("${licensing.enabled:true}") boolean licensingEnabled) {
|
|
||||||
this.repository = repository;
|
|
||||||
this.jwtVerifier = jwtVerifier;
|
|
||||||
this.relay = relay;
|
|
||||||
this.gracePeriodSeconds = gracePeriodDays * 86_400L;
|
|
||||||
this.refreshBeforeExpirySeconds = refreshBeforeExpiryDays * 86_400L;
|
|
||||||
this.licensingEnabled = licensingEnabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true si le licensing Patreon est actif : il faut a la fois que la
|
|
||||||
* feature soit activee ({@code licensing.enabled}, faux en mode
|
|
||||||
* bureau/local ou le gating par image Docker n'a aucun sens) ET que
|
|
||||||
* le verifier soit configure (cle publique presente). Faux => l'UI
|
|
||||||
* masque toute la section Patreon, le daemon de refresh est no-op,
|
|
||||||
* et le canal beta est desactive.
|
|
||||||
*/
|
|
||||||
public boolean isLicensingEnabled() {
|
|
||||||
return licensingEnabled && jwtVerifier.isConfigured();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Genere ou retourne l'instance_id stable de cette installation.
|
|
||||||
* Stocke dans la licence elle-meme. Si pas de licence, en cree un volatil
|
|
||||||
* (sera persiste a la prochaine connexion).
|
|
||||||
*/
|
|
||||||
public String getOrCreateInstanceId() {
|
|
||||||
return repository.findCurrent()
|
|
||||||
.map(License::getInstanceId)
|
|
||||||
.orElseGet(() -> "li-" + UUID.randomUUID());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Construit l'URL OAuth pour ouvrir dans le navigateur de l'utilisateur.
|
|
||||||
*/
|
|
||||||
public String buildConnectUrl() {
|
|
||||||
return relay.buildConnectUrl(getOrCreateInstanceId());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Installe un JWT recu du relais (l'utilisateur l'a colle dans l'UI ou
|
|
||||||
* recu via deep-link). Verifie la signature, extrait les claims, persiste.
|
|
||||||
*/
|
|
||||||
public LicenseSnapshot installToken(String rawJwt) throws InstallException {
|
|
||||||
if (!jwtVerifier.isConfigured()) {
|
|
||||||
throw new InstallException("Licensing feature not enabled (no public key configured)");
|
|
||||||
}
|
|
||||||
LicenseClaims claims;
|
|
||||||
try {
|
|
||||||
claims = jwtVerifier.verify(rawJwt);
|
|
||||||
} catch (JwtVerifier.JwtVerificationException e) {
|
|
||||||
throw new InstallException("Invalid JWT: " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
Instant now = Instant.now();
|
|
||||||
if (claims.expiresAt().isBefore(now)) {
|
|
||||||
throw new InstallException("JWT already expired");
|
|
||||||
}
|
|
||||||
|
|
||||||
Optional<License> existing = repository.findCurrent();
|
|
||||||
License toSave = License.builder()
|
|
||||||
.id("current")
|
|
||||||
.rawJwt(rawJwt)
|
|
||||||
.patreonUserId(claims.subject())
|
|
||||||
.tierId(claims.tierId())
|
|
||||||
.instanceId(claims.instanceId())
|
|
||||||
.issuedAt(claims.issuedAt())
|
|
||||||
.expiresAt(claims.expiresAt())
|
|
||||||
.lastRefreshAttemptAt(now)
|
|
||||||
.lastRefreshSucceeded(true)
|
|
||||||
// Au premier install, on active le canal beta par defaut.
|
|
||||||
// Sur reinstall apres deconnexion, on respecte la valeur precedente.
|
|
||||||
.betaChannelEnabled(existing.map(License::isBetaChannelEnabled).orElse(true))
|
|
||||||
.createdAt(existing.map(License::getCreatedAt).orElse(now))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
License saved = repository.save(toSave);
|
|
||||||
log.info("Patreon license installed for user={} tier={} expires={}",
|
|
||||||
saved.getPatreonUserId(), saved.getTierId(), saved.getExpiresAt());
|
|
||||||
return snapshotOf(saved, now);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Etat courant de la licence pour exposition UI / decision technique.
|
|
||||||
*/
|
|
||||||
public LicenseSnapshot getCurrentSnapshot() {
|
|
||||||
return repository.findCurrent()
|
|
||||||
.map(l -> snapshotOf(l, Instant.now()))
|
|
||||||
.orElseGet(LicenseSnapshot::none);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Supprime la licence (deconnexion volontaire de Patreon par l'utilisateur).
|
|
||||||
*/
|
|
||||||
public void disconnect() {
|
|
||||||
repository.deleteCurrent();
|
|
||||||
log.info("Patreon license removed (user disconnect)");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Active ou desactive le canal beta. Necessite une licence valide ou en grace.
|
|
||||||
*/
|
|
||||||
public LicenseSnapshot setBetaChannelEnabled(boolean enabled) {
|
|
||||||
License current = repository.findCurrent()
|
|
||||||
.orElseThrow(() -> new IllegalStateException("No license installed"));
|
|
||||||
current.setBetaChannelEnabled(enabled);
|
|
||||||
License saved = repository.save(current);
|
|
||||||
return snapshotOf(saved, Instant.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tente un refresh si la licence est proche de l'expiration. Idempotent.
|
|
||||||
* Appele par le daemon planifie + manuellement via l'UI ("Reessayer").
|
|
||||||
*/
|
|
||||||
public void refreshIfNeeded() {
|
|
||||||
Optional<License> opt = repository.findCurrent();
|
|
||||||
if (opt.isEmpty()) return;
|
|
||||||
License current = opt.get();
|
|
||||||
Instant now = Instant.now();
|
|
||||||
long secondsUntilExpiry = Duration.between(now, current.getExpiresAt()).getSeconds();
|
|
||||||
if (secondsUntilExpiry > refreshBeforeExpirySeconds) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
doRefresh(current, now);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Force un refresh immediat (bouton UI "Reessayer maintenant").
|
|
||||||
*/
|
|
||||||
public void forceRefresh() {
|
|
||||||
repository.findCurrent().ifPresent(license -> doRefresh(license, Instant.now()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tente le refresh aupres du relais et persiste le resultat (succes ou echec) sur
|
|
||||||
* la licence. Le succes/echec est lu depuis {@code lastRefreshSucceeded}, pas
|
|
||||||
* depuis un retour de methode : le tentative est deja actee cote persistance.
|
|
||||||
*/
|
|
||||||
private void doRefresh(License current, Instant now) {
|
|
||||||
log.info("Refreshing Patreon license (current expires {})", current.getExpiresAt());
|
|
||||||
try {
|
|
||||||
String newJwt = relay.refreshToken(current.getRawJwt());
|
|
||||||
LicenseClaims claims = jwtVerifier.verify(newJwt);
|
|
||||||
|
|
||||||
current.setRawJwt(newJwt);
|
|
||||||
current.setIssuedAt(claims.issuedAt());
|
|
||||||
current.setExpiresAt(claims.expiresAt());
|
|
||||||
current.setTierId(claims.tierId());
|
|
||||||
current.setLastRefreshAttemptAt(now);
|
|
||||||
current.setLastRefreshSucceeded(true);
|
|
||||||
repository.save(current);
|
|
||||||
log.info("License refreshed successfully (new expiry {})", claims.expiresAt());
|
|
||||||
} catch (LicenseRelay.RelayException e) {
|
|
||||||
current.setLastRefreshAttemptAt(now);
|
|
||||||
current.setLastRefreshSucceeded(false);
|
|
||||||
repository.save(current);
|
|
||||||
if (e.getKind() == LicenseRelay.RelayErrorKind.REJECTED) {
|
|
||||||
log.warn("Relay rejected refresh ({}): tier may have been cancelled", e.getMessage());
|
|
||||||
} else {
|
|
||||||
log.warn("Relay refresh transient failure ({}): {}", e.getKind(), e.getMessage());
|
|
||||||
}
|
|
||||||
} catch (JwtVerifier.JwtVerificationException e) {
|
|
||||||
current.setLastRefreshAttemptAt(now);
|
|
||||||
current.setLastRefreshSucceeded(false);
|
|
||||||
repository.save(current);
|
|
||||||
log.error("Relay returned a JWT that fails verification: {}", e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Recupere les credentials registry pour pull du canal beta.
|
|
||||||
* @return empty si pas de licence valide ou relais en echec
|
|
||||||
*/
|
|
||||||
public Optional<RegistryCredentials> fetchRegistryCredentials() {
|
|
||||||
LicenseSnapshot snap = getCurrentSnapshot();
|
|
||||||
if (snap.status() != LicenseStatus.VALID && snap.status() != LicenseStatus.GRACE) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
License current = repository.findCurrent().orElse(null);
|
|
||||||
if (current == null) return Optional.empty();
|
|
||||||
try {
|
|
||||||
return Optional.of(relay.fetchRegistryCredentials(current.getRawJwt()));
|
|
||||||
} catch (LicenseRelay.RelayException e) {
|
|
||||||
log.warn("Cannot fetch registry credentials ({}): {}", e.getKind(), e.getMessage());
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private LicenseSnapshot snapshotOf(License l, Instant now) {
|
|
||||||
LicenseStatus status = computeStatus(l, now);
|
|
||||||
return new LicenseSnapshot(
|
|
||||||
status,
|
|
||||||
l.getPatreonUserId(),
|
|
||||||
l.getTierId(),
|
|
||||||
l.getInstanceId(),
|
|
||||||
l.getExpiresAt(),
|
|
||||||
l.getLastRefreshAttemptAt(),
|
|
||||||
l.isLastRefreshSucceeded(),
|
|
||||||
l.isBetaChannelEnabled()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private LicenseStatus computeStatus(License l, Instant now) {
|
|
||||||
if (l.getExpiresAt() == null) return LicenseStatus.NONE;
|
|
||||||
if (now.isBefore(l.getExpiresAt())) return LicenseStatus.VALID;
|
|
||||||
long secondsPastExpiry = Duration.between(l.getExpiresAt(), now).getSeconds();
|
|
||||||
if (secondsPastExpiry <= gracePeriodSeconds) return LicenseStatus.GRACE;
|
|
||||||
return LicenseStatus.EXPIRED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class InstallException extends Exception {
|
|
||||||
public InstallException(String message) {
|
|
||||||
super(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -111,6 +111,11 @@ public class SessionService {
|
|||||||
return sessionRepository.findActive();
|
return sessionRepository.findActive();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Toutes les sessions en cours, la plus récente d'abord (raccourci « Séance en cours »). */
|
||||||
|
public List<Session> getAllActive() {
|
||||||
|
return sessionRepository.findAllActive();
|
||||||
|
}
|
||||||
|
|
||||||
public Optional<Session> getActiveByPlaythrough(String playthroughId) {
|
public Optional<Session> getActiveByPlaythrough(String playthroughId) {
|
||||||
return sessionRepository.findActiveByPlaythroughId(playthroughId);
|
return sessionRepository.findActiveByPlaythroughId(playthroughId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package com.loremind.application.remoteaccess;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verdict « une tablette peut-elle joindre ce PC ? », calculé à partir des faits lus sur
|
||||||
|
* le système. Logique pure (testable sans Windows).
|
||||||
|
*
|
||||||
|
* @param supported vérification possible (Windows)
|
||||||
|
* @param ready rien ne bloque côté PC
|
||||||
|
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
|
||||||
|
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
|
||||||
|
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
|
||||||
|
* @param thirdPartyFirewalls pare-feu tiers présents : leurs réglages ne sont pas lisibles, donc {@code ready}
|
||||||
|
* ne peut pas être garanti — le front avertit l'utilisateur de les régler lui-même
|
||||||
|
* @param program exécutable concerné
|
||||||
|
* @param platform {@code windows} ou {@code linux}
|
||||||
|
* @param linuxFirewall Linux : pare-feu actif ({@code ufw}, {@code firewalld}, {@code none})
|
||||||
|
* @param portOpen Linux : port autorisé ({@code null} = invérifiable sans droits administrateur)
|
||||||
|
* @param fixCommand Linux : commande à lancer pour ouvrir le port, ou {@code null}
|
||||||
|
*/
|
||||||
|
public record NetworkReadiness(
|
||||||
|
boolean supported,
|
||||||
|
boolean ready,
|
||||||
|
List<String> publicNetworks,
|
||||||
|
boolean firewallAllowed,
|
||||||
|
boolean firewallBlocked,
|
||||||
|
List<String> thirdPartyFirewalls,
|
||||||
|
String program,
|
||||||
|
String platform,
|
||||||
|
String linuxFirewall,
|
||||||
|
Boolean portOpen,
|
||||||
|
String fixCommand
|
||||||
|
) {
|
||||||
|
|
||||||
|
static final String PUBLIC = "Public";
|
||||||
|
static final String PRIVATE = "Private";
|
||||||
|
|
||||||
|
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
|
||||||
|
if (snapshot == null || !snapshot.supported()) {
|
||||||
|
return new NetworkReadiness(false, false, List.of(), false, false, List.of(), null, null, null, null, null);
|
||||||
|
}
|
||||||
|
if (NetworkSnapshot.LINUX.equals(snapshot.platform())) {
|
||||||
|
return evaluateLinux(snapshot);
|
||||||
|
}
|
||||||
|
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
|
||||||
|
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
|
||||||
|
boolean blockedPrivate = covers(rules, "Block", PRIVATE);
|
||||||
|
boolean publicOpen = covers(rules, "Allow", PUBLIC) && !covers(rules, "Block", PUBLIC);
|
||||||
|
|
||||||
|
List<String> publicNetworks = (snapshot.networks() == null ? List.<NetworkSnapshot.Network>of() : snapshot.networks())
|
||||||
|
.stream()
|
||||||
|
.filter(n -> PUBLIC.equalsIgnoreCase(n.category()))
|
||||||
|
.map(n -> n.name() != null && !n.name().isBlank() ? n.name() : n.alias())
|
||||||
|
.toList();
|
||||||
|
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
|
||||||
|
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
|
||||||
|
|
||||||
|
// « ready » ne porte que sur ce qui est lisible (Windows) ; un pare-feu tiers est signalé à part.
|
||||||
|
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
|
||||||
|
List<String> thirdParty = snapshot.thirdPartyFirewalls() == null ? List.of() : snapshot.thirdPartyFirewalls();
|
||||||
|
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, thirdParty,
|
||||||
|
snapshot.program(), NetworkSnapshot.WINDOWS, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Linux : prêt si aucun pare-feu (ufw, firewalld) n'est actif, ou si le port est ouvert.
|
||||||
|
* Port invérifiable (ufw sans droits root) : pas prêt, mais pas en erreur — le front
|
||||||
|
* affiche la commande « au cas où ».
|
||||||
|
*/
|
||||||
|
private static NetworkReadiness evaluateLinux(NetworkSnapshot s) {
|
||||||
|
String fw = s.linuxFirewall() == null ? "none" : s.linuxFirewall();
|
||||||
|
boolean ready = "none".equals(fw) || Boolean.TRUE.equals(s.portOpen());
|
||||||
|
return new NetworkReadiness(true, ready, List.of(), false, false, List.of(), null,
|
||||||
|
NetworkSnapshot.LINUX, fw, s.portOpen(), ready ? null : linuxCommand(fw, s.port()));
|
||||||
|
}
|
||||||
|
|
||||||
|
static String linuxCommand(String firewall, int port) {
|
||||||
|
return switch (firewall) {
|
||||||
|
case "ufw" -> "sudo ufw allow " + port + "/tcp";
|
||||||
|
case "firewalld" -> "sudo firewall-cmd --permanent --add-port=" + port + "/tcp && sudo firewall-cmd --reload";
|
||||||
|
default -> null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
|
||||||
|
private static boolean covers(List<NetworkSnapshot.FirewallRule> rules, String action, String profile) {
|
||||||
|
return rules.stream()
|
||||||
|
.filter(r -> action.equalsIgnoreCase(r.action()) && "True".equalsIgnoreCase(r.enabled()))
|
||||||
|
.anyMatch(r -> profiles(r.profile()).stream().anyMatch(p -> p.equals("any") || p.equals(profile.toLowerCase(Locale.ROOT))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> profiles(String raw) {
|
||||||
|
if (raw == null) return List.of();
|
||||||
|
return Arrays.stream(raw.split(","))
|
||||||
|
.map(s -> s.trim().toLowerCase(Locale.ROOT))
|
||||||
|
.filter(s -> !s.isEmpty())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.application.remoteaccess;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
/** Vue publique d'un appareil appairé (jamais l'empreinte du jeton). */
|
||||||
|
public record PairedDevice(String id, String name, String userAgent, Instant createdAt, Instant lastSeenAt) {
|
||||||
|
|
||||||
|
static PairedDevice of(RemoteDevice d) {
|
||||||
|
return new PairedDevice(d.getId(), d.getName(), d.getUserAgent(), d.getCreatedAt(), d.getLastSeenAt());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.loremind.application.remoteaccess;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
/** Code d'appairage à 6 chiffres affiché sur le PC (usage unique). */
|
||||||
|
public record PairingCode(String code, Instant expiresAt) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.loremind.application.remoteaccess;
|
||||||
|
|
||||||
|
/** Appairage refusé : code absent, faux, expiré, ou trop d'essais. Message prêt à afficher. */
|
||||||
|
public class PairingRejectedException extends RuntimeException {
|
||||||
|
|
||||||
|
public PairingRejectedException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.loremind.application.remoteaccess;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résultat d'un appairage réussi.
|
||||||
|
*
|
||||||
|
* @param token jeton d'appareil en clair : à poser en cookie, jamais renvoyé dans le corps
|
||||||
|
* @param device l'appareil enregistré
|
||||||
|
*/
|
||||||
|
public record PairingResult(String token, PairedDevice device) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package com.loremind.application.remoteaccess;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||||
|
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||||
|
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||||
|
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||||
|
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.time.Clock;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
|
||||||
|
* <p>
|
||||||
|
* Modèle de confiance : le connecteur habituel reste limité à la machine (127.0.0.1) et
|
||||||
|
* n'exige rien, comme avant. Quand le MJ active l'accès distant, un SECOND connecteur
|
||||||
|
* s'ouvre sur le réseau local ; tout ce qui y arrive doit présenter un jeton d'appareil,
|
||||||
|
* obtenu en saisissant un code à 6 chiffres affiché sur le PC (usage unique, 5 minutes,
|
||||||
|
* 5 essais). Les Paramètres restent réservés à la machine (filtre {@code RemoteAccessFilter}).
|
||||||
|
* <p>
|
||||||
|
* Uniquement en mode bureau (profil {@code local}) : en Docker, rien de tout ceci n'existe.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@Profile("local")
|
||||||
|
public class RemoteAccessService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RemoteAccessService.class);
|
||||||
|
|
||||||
|
static final Duration CODE_TTL = Duration.ofMinutes(5);
|
||||||
|
static final int CODE_MAX_ATTEMPTS = 5;
|
||||||
|
/** Garde-fou anti force brute tous codes confondus : au-delà, plus aucun essai pendant 1 min. */
|
||||||
|
static final int GLOBAL_MAX_FAILURES_PER_MINUTE = 20;
|
||||||
|
/** On ne réécrit « vu pour la dernière fois » qu'au plus une fois par minute et par appareil. */
|
||||||
|
static final Duration TOUCH_INTERVAL = Duration.ofMinutes(1);
|
||||||
|
static final int DEVICE_NAME_MAX = 100;
|
||||||
|
static final int USER_AGENT_MAX = 300;
|
||||||
|
|
||||||
|
private final RemoteAccessConfigRepository configRepository;
|
||||||
|
private final RemoteDeviceRepository deviceRepository;
|
||||||
|
private final LanConnector lanConnector;
|
||||||
|
private final int localPort;
|
||||||
|
private final Clock clock;
|
||||||
|
private final SecureRandom random = new SecureRandom();
|
||||||
|
|
||||||
|
private PairingCode currentCode;
|
||||||
|
private int attemptsLeft;
|
||||||
|
private final Deque<Instant> recentFailures = new ArrayDeque<>();
|
||||||
|
private String lastError;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||||
|
RemoteDeviceRepository deviceRepository,
|
||||||
|
LanConnector lanConnector,
|
||||||
|
@Value("${server.port:8080}") int localPort) {
|
||||||
|
this(configRepository, deviceRepository, lanConnector, localPort, Clock.systemUTC());
|
||||||
|
}
|
||||||
|
|
||||||
|
RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||||
|
RemoteDeviceRepository deviceRepository,
|
||||||
|
LanConnector lanConnector,
|
||||||
|
int localPort,
|
||||||
|
Clock clock) {
|
||||||
|
this.configRepository = configRepository;
|
||||||
|
this.deviceRepository = deviceRepository;
|
||||||
|
this.lanConnector = lanConnector;
|
||||||
|
this.localPort = localPort;
|
||||||
|
this.clock = clock;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Réglage -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Au démarrage : rouvre le connecteur si l'accès distant était activé. Ne bloque jamais le lancement. */
|
||||||
|
public synchronized void applySavedConfig() {
|
||||||
|
RemoteAccessConfig config = currentConfig();
|
||||||
|
if (!config.enabled()) return;
|
||||||
|
try {
|
||||||
|
lanConnector.start(config.port());
|
||||||
|
lastError = null;
|
||||||
|
} catch (IllegalStateException e) {
|
||||||
|
lastError = e.getMessage();
|
||||||
|
log.warn("Accès distant activé mais connecteur impossible à ouvrir : {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Active ou désactive l'accès distant. À l'activation, le connecteur est ouvert AVANT
|
||||||
|
* d'enregistrer le réglage : un port occupé laisse l'accès désactivé.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException port hors plage ou identique au port local
|
||||||
|
* @throws IllegalStateException port déjà occupé
|
||||||
|
*/
|
||||||
|
public synchronized RemoteAccessStatus configure(boolean enabled, int port) {
|
||||||
|
if (port < 1024 || port > 65535) {
|
||||||
|
throw new IllegalArgumentException("Le port doit être compris entre 1024 et 65535.");
|
||||||
|
}
|
||||||
|
if (port == localPort) {
|
||||||
|
throw new IllegalArgumentException("Choisissez un port différent de celui de l'application (" + localPort + ").");
|
||||||
|
}
|
||||||
|
if (enabled) {
|
||||||
|
lanConnector.start(port);
|
||||||
|
} else {
|
||||||
|
lanConnector.stop();
|
||||||
|
currentCode = null;
|
||||||
|
}
|
||||||
|
lastError = null;
|
||||||
|
configRepository.save(new RemoteAccessConfig(enabled, port));
|
||||||
|
return status();
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized RemoteAccessStatus status() {
|
||||||
|
RemoteAccessConfig config = currentConfig();
|
||||||
|
int running = lanConnector.runningPort();
|
||||||
|
List<String> urls = running > 0
|
||||||
|
? lanConnector.lanAddresses().stream().map(ip -> "http://" + ip + ":" + running).toList()
|
||||||
|
: List.of();
|
||||||
|
List<PairedDevice> devices = deviceRepository.findAll().stream()
|
||||||
|
.sorted(Comparator.comparing(RemoteDevice::getCreatedAt, Comparator.nullsLast(Comparator.naturalOrder())))
|
||||||
|
.map(PairedDevice::of)
|
||||||
|
.toList();
|
||||||
|
return new RemoteAccessStatus(config.enabled(), config.port(), running > 0, urls, lastError, devices);
|
||||||
|
}
|
||||||
|
|
||||||
|
private RemoteAccessConfig currentConfig() {
|
||||||
|
return configRepository.find().orElseGet(RemoteAccessConfig::disabledByDefault);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Appairage -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nouveau code d'appairage (remplace le précédent).
|
||||||
|
*
|
||||||
|
* @throws IllegalStateException si l'accès distant n'est pas ouvert
|
||||||
|
*/
|
||||||
|
public synchronized PairingCode newPairingCode() {
|
||||||
|
if (lanConnector.runningPort() <= 0) {
|
||||||
|
throw new IllegalStateException("Activez d'abord l'accès depuis le réseau local.");
|
||||||
|
}
|
||||||
|
String code = String.format("%06d", random.nextInt(1_000_000));
|
||||||
|
currentCode = new PairingCode(code, clock.instant().plus(CODE_TTL));
|
||||||
|
attemptsLeft = CODE_MAX_ATTEMPTS;
|
||||||
|
return currentCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Échange un code valide contre un jeton d'appareil (à poser en cookie). Le code est
|
||||||
|
* consommé : un second appareil demande un nouveau code.
|
||||||
|
*
|
||||||
|
* @throws PairingRejectedException code absent, faux, expiré ou trop d'essais
|
||||||
|
*/
|
||||||
|
public synchronized PairingResult pair(String code, String deviceName, String userAgent) {
|
||||||
|
Instant now = clock.instant();
|
||||||
|
pruneFailures(now);
|
||||||
|
if (recentFailures.size() >= GLOBAL_MAX_FAILURES_PER_MINUTE) {
|
||||||
|
throw new PairingRejectedException("Trop d'essais. Patientez une minute.");
|
||||||
|
}
|
||||||
|
if (currentCode == null || now.isAfter(currentCode.expiresAt())) {
|
||||||
|
currentCode = null;
|
||||||
|
recordFailure(now);
|
||||||
|
throw new PairingRejectedException("Aucun code valide : affichez un nouveau code sur le PC.");
|
||||||
|
}
|
||||||
|
if (code == null || !constantTimeEquals(code.trim(), currentCode.code())) {
|
||||||
|
recordFailure(now);
|
||||||
|
if (--attemptsLeft <= 0) {
|
||||||
|
currentCode = null;
|
||||||
|
throw new PairingRejectedException("Trop d'essais : affichez un nouveau code sur le PC.");
|
||||||
|
}
|
||||||
|
throw new PairingRejectedException("Code incorrect.");
|
||||||
|
}
|
||||||
|
currentCode = null;
|
||||||
|
|
||||||
|
String token = newToken();
|
||||||
|
RemoteDevice device = deviceRepository.save(RemoteDevice.builder()
|
||||||
|
.name(clean(deviceName, DEVICE_NAME_MAX, "Appareil"))
|
||||||
|
.tokenHash(sha256(token))
|
||||||
|
.userAgent(clean(userAgent, USER_AGENT_MAX, null))
|
||||||
|
.createdAt(now)
|
||||||
|
.lastSeenAt(now)
|
||||||
|
.build());
|
||||||
|
log.info("Accès distant : appareil appairé « {} »", device.getName());
|
||||||
|
return new PairingResult(token, PairedDevice.of(device));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Appareil correspondant au jeton présenté, s'il est connu (sinon : appairage requis). */
|
||||||
|
public Optional<RemoteDevice> authenticate(String token) {
|
||||||
|
if (token == null || token.isBlank()) return Optional.empty();
|
||||||
|
Optional<RemoteDevice> device = deviceRepository.findByTokenHash(sha256(token));
|
||||||
|
device.ifPresent(d -> {
|
||||||
|
Instant now = clock.instant();
|
||||||
|
if (d.getLastSeenAt() == null || d.getLastSeenAt().plus(TOUCH_INTERVAL).isBefore(now)) {
|
||||||
|
deviceRepository.touch(d.getId(), now);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return device;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Coupe l'accès d'un appareil. */
|
||||||
|
public boolean revoke(String deviceId) {
|
||||||
|
return deviceRepository.deleteById(deviceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Port réseau réglé (ouvert ou non) : celui que le pare-feu doit laisser passer. */
|
||||||
|
public synchronized int configuredPort() {
|
||||||
|
return currentConfig().port();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Port du connecteur réseau ouvert, ou -1 (pour le filtre : qui vient « de l'extérieur » ?). */
|
||||||
|
public int lanPort() {
|
||||||
|
return lanConnector.runningPort();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Outils -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private void recordFailure(Instant now) {
|
||||||
|
recentFailures.addLast(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void pruneFailures(Instant now) {
|
||||||
|
Instant limit = now.minus(Duration.ofMinutes(1));
|
||||||
|
while (!recentFailures.isEmpty() && recentFailures.peekFirst().isBefore(limit)) {
|
||||||
|
recentFailures.removeFirst();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String newToken() {
|
||||||
|
byte[] bytes = new byte[32];
|
||||||
|
random.nextBytes(bytes);
|
||||||
|
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String sha256(String value) {
|
||||||
|
try {
|
||||||
|
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return HexFormat.of().formatHex(digest);
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new IllegalStateException("SHA-256 indisponible", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean constantTimeEquals(String a, String b) {
|
||||||
|
return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clean(String value, int max, String fallback) {
|
||||||
|
if (value == null || value.isBlank()) return fallback;
|
||||||
|
String trimmed = value.strip();
|
||||||
|
return trimmed.length() > max ? trimmed.substring(0, max) : trimmed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.loremind.application.remoteaccess;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* État de l'accès distant, pour l'écran Paramètres du PC.
|
||||||
|
*
|
||||||
|
* @param enabled accès activé (réglage enregistré)
|
||||||
|
* @param port port réseau dédié
|
||||||
|
* @param running connecteur réseau effectivement ouvert
|
||||||
|
* @param urls adresses à taper sur la tablette (une par interface réseau locale)
|
||||||
|
* @param lastError dernière erreur d'ouverture (ex. port occupé au démarrage), ou null
|
||||||
|
* @param devices appareils appairés
|
||||||
|
*/
|
||||||
|
public record RemoteAccessStatus(
|
||||||
|
boolean enabled,
|
||||||
|
int port,
|
||||||
|
boolean running,
|
||||||
|
List<String> urls,
|
||||||
|
String lastError,
|
||||||
|
List<PairedDevice> devices
|
||||||
|
) {
|
||||||
|
}
|
||||||
@@ -44,6 +44,9 @@ public class Campaign {
|
|||||||
*/
|
*/
|
||||||
private String graphPositions;
|
private String graphPositions;
|
||||||
|
|
||||||
|
/** Fiche « Publication » (couverture, page technique, crédits…). Null = jamais renseignée. */
|
||||||
|
private CampaignPublication publication;
|
||||||
|
|
||||||
public boolean isLinkedToLore() {
|
public boolean isLinkedToLore() {
|
||||||
return this.loreId != null && !this.loreId.isBlank();
|
return this.loreId != null && !this.loreId.isBlank();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
/** Lightweight search projection with the ancestors needed to open a result. */
|
||||||
|
public record CampaignContentHit(String kind, String id, String name,
|
||||||
|
String campaignId, String campaignName, String arcId, String arcName,
|
||||||
|
String chapterId, String chapterName) {}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import java.util.function.UnaryOperator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche « Publication » d'une campagne : ce qu'un module vendu ou partagé affiche en
|
||||||
|
* couverture, page technique, introduction pour le MJ et page de crédits.
|
||||||
|
* <p>
|
||||||
|
* Tout est en texte libre (« 1 à 3 », « 3-5 joueurs », « 2 séances de 4 h ») : chaque
|
||||||
|
* système de jeu a ses conventions, l'auteur écrit ce qu'il veut voir imprimé.
|
||||||
|
* Valeur immuable ; {@link #normalized()} nettoie une saisie (blancs → null, longueurs bornées).
|
||||||
|
*
|
||||||
|
* @param subtitle sous-titre de couverture
|
||||||
|
* @param author auteur(s) affichés en couverture
|
||||||
|
* @param system système de jeu tel qu'il doit apparaître (« D&D 5e », « Chroniques Oubliées »)
|
||||||
|
* @param levels niveaux des personnages
|
||||||
|
* @param players nombre de joueurs
|
||||||
|
* @param duration durée de jeu estimée
|
||||||
|
* @param pitch argument : l'aventure en quelques lignes
|
||||||
|
* @param gmBackground contexte caché, réservé au MJ (ce qui s'est vraiment passé)
|
||||||
|
* @param hooks accroches pour impliquer les personnages (une par ligne « - … »)
|
||||||
|
* @param contentWarnings avertissements de contenu (thèmes sensibles)
|
||||||
|
* @param credits crédits : auteur, illustrations, relecture, testeurs…
|
||||||
|
* @param legal licence et mentions légales
|
||||||
|
* @param version version du document (« 1.0 »)
|
||||||
|
* @param coverImageId image de couverture (id d'image), nullable
|
||||||
|
*/
|
||||||
|
public record CampaignPublication(
|
||||||
|
String subtitle,
|
||||||
|
String author,
|
||||||
|
String system,
|
||||||
|
String levels,
|
||||||
|
String players,
|
||||||
|
String duration,
|
||||||
|
String pitch,
|
||||||
|
String gmBackground,
|
||||||
|
String hooks,
|
||||||
|
String contentWarnings,
|
||||||
|
String credits,
|
||||||
|
String legal,
|
||||||
|
String version,
|
||||||
|
String coverImageId
|
||||||
|
) {
|
||||||
|
|
||||||
|
private static final int SHORT_MAX = 200;
|
||||||
|
private static final int LONG_MAX = 20_000;
|
||||||
|
|
||||||
|
public static CampaignPublication empty() {
|
||||||
|
return new CampaignPublication(null, null, null, null, null, null, null,
|
||||||
|
null, null, null, null, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Copie nettoyée : textes rognés, blancs → null, longueurs bornées. */
|
||||||
|
public CampaignPublication normalized() {
|
||||||
|
UnaryOperator<String> shortText = s -> clean(s, SHORT_MAX);
|
||||||
|
UnaryOperator<String> longText = s -> clean(s, LONG_MAX);
|
||||||
|
return new CampaignPublication(
|
||||||
|
shortText.apply(subtitle), shortText.apply(author), shortText.apply(system),
|
||||||
|
shortText.apply(levels), shortText.apply(players), shortText.apply(duration),
|
||||||
|
longText.apply(pitch), longText.apply(gmBackground), longText.apply(hooks),
|
||||||
|
longText.apply(contentWarnings), longText.apply(credits), longText.apply(legal),
|
||||||
|
shortText.apply(version), shortText.apply(coverImageId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vrai si au moins un champ est renseigné. (Pas de getter {@code isEmpty()} : il serait
|
||||||
|
* sérialisé en JSON comme un champ de plus.)
|
||||||
|
*/
|
||||||
|
public boolean hasContent() {
|
||||||
|
return !normalized().equals(empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Au moins une information de la page technique (système, niveaux, joueurs, durée). */
|
||||||
|
public boolean hasTechnicalSheet() {
|
||||||
|
return present(system) || present(levels) || present(players) || present(duration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Au moins une information de la page de crédits. */
|
||||||
|
public boolean hasCredits() {
|
||||||
|
return present(author) || present(credits) || present(legal) || present(version);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean present(String s) {
|
||||||
|
return s != null && !s.isBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clean(String s, int max) {
|
||||||
|
if (s == null) return null;
|
||||||
|
String t = s.trim();
|
||||||
|
if (t.isEmpty()) return null;
|
||||||
|
return t.length() > max ? t.substring(0, max) : t;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,6 +60,9 @@ public class Npc {
|
|||||||
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
|
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
|
||||||
private int order;
|
private int order;
|
||||||
|
|
||||||
|
/** Rôle dans l'histoire (rôle, motivation, ce qu'il sait, signe distinctif). Null = non renseigné. */
|
||||||
|
private NpcStory story;
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.bestiary;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche « rôle dans l'histoire » d'un PNJ, indépendante du système de jeu (le gabarit du
|
||||||
|
* système porte les caractéristiques) : ce qui rend le PNJ jouable et utile au récit.
|
||||||
|
*
|
||||||
|
* @param role place dans l'histoire : {@code OPPONENT} (s'oppose aux PJ), {@code ALLY}
|
||||||
|
* (les aide), {@code RESOURCE} (détient une information ou un service),
|
||||||
|
* {@code EXTRA} (figurant) ; null = non précisé
|
||||||
|
* @param motivation ce qu'il veut, et ce qu'il est prêt à faire pour l'obtenir
|
||||||
|
* @param knowledge ce qu'il sait (et peut révéler) — réservé au MJ
|
||||||
|
* @param mannerism signe distinctif à jouer (geste, phrasé, tic)
|
||||||
|
*/
|
||||||
|
public record NpcStory(String role, String motivation, String knowledge, String mannerism) {
|
||||||
|
|
||||||
|
public static final Set<String> ROLES = Set.of("OPPONENT", "ALLY", "RESOURCE", "EXTRA");
|
||||||
|
private static final int SHORT_MAX = 300;
|
||||||
|
private static final int LONG_MAX = 10_000;
|
||||||
|
|
||||||
|
/** Copie nettoyée : rôle inconnu → null, textes rognés (blancs → null) et bornés. */
|
||||||
|
public NpcStory normalized() {
|
||||||
|
String r = role == null ? null : role.trim().toUpperCase(Locale.ROOT);
|
||||||
|
// Set.of(...).contains(null) lève une NullPointerException : rôle absent testé à part.
|
||||||
|
return new NpcStory(r != null && ROLES.contains(r) ? r : null,
|
||||||
|
clean(motivation, LONG_MAX), clean(knowledge, LONG_MAX), clean(mannerism, SHORT_MAX));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vrai si au moins un élément est renseigné. */
|
||||||
|
public boolean hasContent() {
|
||||||
|
NpcStory n = normalized();
|
||||||
|
return n.role() != null || n.motivation() != null || n.knowledge() != null || n.mannerism() != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un PNJ qui pèse sur l'intrigue (opposant ou allié) : sa motivation est attendue. */
|
||||||
|
public boolean drivesThePlot() {
|
||||||
|
String r = normalized().role();
|
||||||
|
return "OPPONENT".equals(r) || "ALLY".equals(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String clean(String s, int max) {
|
||||||
|
if (s == null) return null;
|
||||||
|
String t = s.trim();
|
||||||
|
if (t.isEmpty()) return null;
|
||||||
|
return t.length() > max ? t.substring(0, max) : t;
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-5
@@ -11,12 +11,13 @@ import java.util.List;
|
|||||||
public record CampaignImportProposal(List<ArcProposal> arcs, List<NpcProposal> npcs) {
|
public record CampaignImportProposal(List<ArcProposal> arcs, List<NpcProposal> npcs) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code existingId} (nullable) : si présent, le nœud existe DÉJÀ dans la
|
* {@code type} = "LINEAR" ou "HUB" (mappé sur {@link ArcType} à l'apply).
|
||||||
* campagne (rempli côté UI lors de la revue pré-chargée) → l'apply ne le
|
* <p>
|
||||||
* recrée pas, il l'utilise comme parent des nouveaux enfants. Null = à créer.
|
* {@code existingId} (nullable, porté aussi par Chapter/SceneProposal) : si présent,
|
||||||
|
* le nœud existe DÉJÀ dans la campagne (rempli côté UI lors de la revue pré-chargée)
|
||||||
|
* → l'apply ne le recrée pas, il l'utilise comme parent des nouveaux enfants.
|
||||||
|
* Null = à créer.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** {@code type} = "LINEAR" ou "HUB" (mappé sur {@link ArcType} à l'apply). */
|
|
||||||
public record ArcProposal(
|
public record ArcProposal(
|
||||||
String name, String description, String type,
|
String name, String description, String type,
|
||||||
List<ChapterProposal> chapters, String existingId) {
|
List<ChapterProposal> chapters, String existingId) {
|
||||||
|
|||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface CampaignContentSearchRepository {
|
||||||
|
List<CampaignContentHit> searchByName(String query);
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.ports;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie (Mentor d'écriture) : demande à l'IA de proposer des réponses aux
|
||||||
|
* questions d'une méthode guidée à partir de l'idée de départ du MJ. Implémenté par un
|
||||||
|
* client du Brain. One-shot ; rien n'est enregistré (le MJ relit et corrige dans l'assistant).
|
||||||
|
*/
|
||||||
|
public interface GuidedMethodAssistant {
|
||||||
|
|
||||||
|
/** Choix possible d'une question à choix : valeur technique + libellé lisible. */
|
||||||
|
record Choice(String value, String label) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Une question de la méthode, décrite par le front (libellés dans la langue du MJ).
|
||||||
|
*
|
||||||
|
* @param key clé de réponse (ex. {@code node1.name})
|
||||||
|
* @param label libellé de la question
|
||||||
|
* @param hint aide (exemple de réponse attendue), optionnelle
|
||||||
|
* @param step titre de l'étape, optionnel
|
||||||
|
* @param options choix possibles (vide pour une question libre)
|
||||||
|
*/
|
||||||
|
record Question(String key, String label, String hint, String step, List<Choice> options) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param methodName nom de la méthode (« Enquête en nœuds »…)
|
||||||
|
* @param principle principe de la méthode, suivi du rôle de chaque étape (comme dans l'assistant manuel)
|
||||||
|
* @param idea idée de départ du MJ (peut être vide)
|
||||||
|
* @param context contexte de la campagne (nom, description, système)
|
||||||
|
* @param questions questions auxquelles répondre
|
||||||
|
* @param existing réponses déjà écrites par le MJ (à respecter)
|
||||||
|
* @return une réponse proposée par clé (clés demandées uniquement)
|
||||||
|
*/
|
||||||
|
Map<String, String> answer(String methodName, String principle, String idea, String context,
|
||||||
|
List<Question> questions, Map<String, String> existing);
|
||||||
|
}
|
||||||
@@ -2,11 +2,9 @@ package com.loremind.domain.campaigncontext.quest;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Condition de déblocage d'une quête (Chapter dans un Arc HUB).
|
* Condition de déblocage d'une quête (Chapter dans un Arc HUB).
|
||||||
*
|
|
||||||
* Sealed : la liste des types est CLOSE et connue à la compilation. Pour ajouter
|
* Sealed : la liste des types est CLOSE et connue à la compilation. Pour ajouter
|
||||||
* un nouveau type (ex : NpcMet), il faudra l'ajouter ici ET dans
|
* un nouveau type (ex : NpcMet), il faudra l'ajouter ici ET dans
|
||||||
* {@link PrerequisiteEvaluator}.
|
* {@link PrerequisiteEvaluator}.
|
||||||
*
|
|
||||||
* Sémantique MVP : une quête a une LISTE de prérequis, tous combinés en ET logique
|
* Sémantique MVP : une quête a une LISTE de prérequis, tous combinés en ET logique
|
||||||
* (pas de OR pour le moment).
|
* (pas de OR pour le moment).
|
||||||
*/
|
*/
|
||||||
|
|||||||
+7
-11
@@ -7,7 +7,6 @@ import java.util.Set;
|
|||||||
/**
|
/**
|
||||||
* Service de domaine (pur, sans effet de bord) : évalue les prérequis d'une quête
|
* Service de domaine (pur, sans effet de bord) : évalue les prérequis d'une quête
|
||||||
* et en dérive le {@link QuestStatus} effectif.
|
* et en dérive le {@link QuestStatus} effectif.
|
||||||
*
|
|
||||||
* NB Java 17 : on utilise instanceof pattern matching (finalisé en Java 16) plutôt que
|
* NB Java 17 : on utilise instanceof pattern matching (finalisé en Java 16) plutôt que
|
||||||
* switch pattern matching (preview en 17, final en 21). La perte de l'exhaustivité
|
* switch pattern matching (preview en 17, final en 21). La perte de l'exhaustivité
|
||||||
* compile-time est compensée par le throw final qui fait crasher tout nouvel
|
* compile-time est compensée par le throw final qui fait crasher tout nouvel
|
||||||
@@ -51,15 +50,12 @@ public final class PrerequisiteEvaluator {
|
|||||||
List<Prerequisite> prerequisites,
|
List<Prerequisite> prerequisites,
|
||||||
EvaluationContext ctx
|
EvaluationContext ctx
|
||||||
) {
|
) {
|
||||||
switch (progression) {
|
return switch (progression) {
|
||||||
case COMPLETED: return QuestStatus.COMPLETED;
|
case COMPLETED -> QuestStatus.COMPLETED;
|
||||||
case IN_PROGRESS: return QuestStatus.IN_PROGRESS;
|
case IN_PROGRESS -> QuestStatus.IN_PROGRESS;
|
||||||
case NOT_STARTED:
|
case NOT_STARTED -> areAllSatisfied(prerequisites, ctx)
|
||||||
return areAllSatisfied(prerequisites, ctx)
|
? QuestStatus.AVAILABLE
|
||||||
? QuestStatus.AVAILABLE
|
: QuestStatus.LOCKED;
|
||||||
: QuestStatus.LOCKED;
|
};
|
||||||
default:
|
|
||||||
throw new IllegalStateException("ProgressionStatus non géré : " + progression);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,10 @@ package com.loremind.domain.campaigncontext.quest;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Statut de progression d'une quête (= Chapter dans un Arc HUB), piloté manuellement par le MJ.
|
* Statut de progression d'une quête (= Chapter dans un Arc HUB), piloté manuellement par le MJ.
|
||||||
*
|
|
||||||
* NOT_STARTED : pas encore commencée. Peut être visible (AVAILABLE) ou cachée (LOCKED)
|
* NOT_STARTED : pas encore commencée. Peut être visible (AVAILABLE) ou cachée (LOCKED)
|
||||||
* selon les prérequis — voir {@link QuestStatus}.
|
* selon les prérequis — voir {@link QuestStatus}.
|
||||||
* IN_PROGRESS : démarrée par le MJ via le bouton "Démarrer cette quête".
|
* IN_PROGRESS : démarrée par le MJ via le bouton "Démarrer cette quête".
|
||||||
* COMPLETED : marquée terminée par le MJ.
|
* COMPLETED : marquée terminée par le MJ.
|
||||||
*
|
|
||||||
* NB : un Chapter d'Arc LINEAR conserve NOT_STARTED par défaut sans impact visible.
|
* NB : un Chapter d'Arc LINEAR conserve NOT_STARTED par défaut sans impact visible.
|
||||||
*/
|
*/
|
||||||
public enum ProgressionStatus {
|
public enum ProgressionStatus {
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ package com.loremind.domain.campaigncontext.quest;
|
|||||||
* Statut effectif d'une quête tel qu'affiché dans la vue Hub.
|
* Statut effectif d'une quête tel qu'affiché dans la vue Hub.
|
||||||
* DÉRIVÉ — jamais persisté. Calculé par {@link PrerequisiteEvaluator} à partir
|
* DÉRIVÉ — jamais persisté. Calculé par {@link PrerequisiteEvaluator} à partir
|
||||||
* de la {@link ProgressionStatus} persistée et de l'évaluation des prérequis.
|
* de la {@link ProgressionStatus} persistée et de l'évaluation des prérequis.
|
||||||
*
|
|
||||||
* Table de vérité :
|
* Table de vérité :
|
||||||
* NOT_STARTED + prérequis non remplis -> LOCKED
|
* NOT_STARTED + prérequis non remplis -> LOCKED
|
||||||
* NOT_STARTED + prérequis remplis -> AVAILABLE
|
* NOT_STARTED + prérequis remplis -> AVAILABLE
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ public class Arc {
|
|||||||
private String gmNotes; // Notes privées du MJ (non exportées vers FoundryVTT)
|
private String gmNotes; // Notes privées du MJ (non exportées vers FoundryVTT)
|
||||||
private String rewards; // Récompenses et progression
|
private String rewards; // Récompenses et progression
|
||||||
private String resolution; // Dénouement prévu
|
private String resolution; // Dénouement prévu
|
||||||
|
private String hiddenTruth; // Histoire cachée : ce qui s'est vraiment passé (réservé au MJ)
|
||||||
|
private String hooks; // Accroches : pourquoi les personnages s'en mêlent (une par ligne)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IDs des pages du Lore associées à cet arc (weak cross-context references).
|
* IDs des pages du Lore associées à cet arc (weak cross-context references).
|
||||||
|
|||||||
@@ -48,6 +48,8 @@ public class Scene {
|
|||||||
|
|
||||||
// === Combat ou rencontre ===
|
// === Combat ou rencontre ===
|
||||||
private String combatDifficulty; // Difficulté estimée
|
private String combatDifficulty; // Difficulté estimée
|
||||||
|
private String tactics; // Tactique et moral des adversaires (quand fuient-ils, se rendent-ils ?)
|
||||||
|
private String purpose; // Utilité : ce que l'histoire perd si on coupe la scène
|
||||||
private String enemies; // Liste des ennemis et créatures (texte libre)
|
private String enemies; // Liste des ennemis et créatures (texte libre)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.writingreview;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Famille d'une remarque de relecture (Mentor d'écriture, phase M2). Sert à
|
||||||
|
* regrouper les conseils côté front ; n'implique aucune gravité : une remarque de
|
||||||
|
* relecture est un conseil d'auteur, jamais un blocage.
|
||||||
|
*/
|
||||||
|
public enum WritingRemarkCategory {
|
||||||
|
/** Pouvoir des joueurs : vrais choix, chemins multiples, issues alternatives. */
|
||||||
|
AGENCY,
|
||||||
|
/** Rythme : variété des scènes, lisibilité de la structure. */
|
||||||
|
PACING,
|
||||||
|
/** Enjeux : ce que les joueurs risquent, pourquoi l'adversité agit. */
|
||||||
|
STAKES,
|
||||||
|
/** Narration : textes lus aux joueurs. */
|
||||||
|
NARRATION
|
||||||
|
}
|
||||||
@@ -35,6 +35,9 @@ public class GameSystem {
|
|||||||
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||||
private String rulesMarkdown;
|
private String rulesMarkdown;
|
||||||
|
|
||||||
|
/** Version anglaise des règles ({@code rulesMarkdown} = version française). Nullable. */
|
||||||
|
private String rulesMarkdownEn;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
|
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
|
||||||
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
|
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
|
||||||
@@ -158,7 +161,18 @@ public class GameSystem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static boolean equalsIgnoreCase(String a, String b) {
|
private static boolean equalsIgnoreCase(String a, String b) {
|
||||||
if (a == null || b == null) return a == b;
|
if (a == null || b == null) return a == null && b == null;
|
||||||
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Règles dans la langue demandée ({@code en} → anglais, sinon français), avec repli sur
|
||||||
|
* l'autre version si celle-ci est vide : un système importé dans une seule langue reste lisible.
|
||||||
|
*/
|
||||||
|
public String rulesFor(String language) {
|
||||||
|
boolean english = "en".equalsIgnoreCase(language);
|
||||||
|
String preferred = english ? rulesMarkdownEn : rulesMarkdown;
|
||||||
|
String fallback = english ? rulesMarkdown : rulesMarkdownEn;
|
||||||
|
return preferred != null && !preferred.isBlank() ? preferred : fallback;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,5 +16,14 @@ import java.util.Map;
|
|||||||
public record RulesImportResult(
|
public record RulesImportResult(
|
||||||
Map<String, String> sections,
|
Map<String, String> sections,
|
||||||
int pageCount,
|
int pageCount,
|
||||||
int ocrPageCount) {
|
int ocrPageCount,
|
||||||
|
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
|
||||||
|
Map<String, Map<String, String>> sectionsByLanguage,
|
||||||
|
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
|
||||||
|
String sourceLanguage) {
|
||||||
|
|
||||||
|
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
|
||||||
|
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
|
||||||
|
this(sections, pageCount, ocrPageCount, Map.of(), null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import lombok.Builder;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Licence Patreon installee dans cette instance LoreMind.
|
|
||||||
* <p>
|
|
||||||
* Singleton (une seule licence par instance, identifiee logiquement par
|
|
||||||
* {@code id = "current"}). Contient le JWT brut emis par le relais OAuth
|
|
||||||
* + les claims extraits a la verification, plus l'etat operationnel
|
|
||||||
* (derniere tentative de refresh, succes/echec).
|
|
||||||
* <p>
|
|
||||||
* <b>Note securite :</b> {@link #rawJwt} est stocke tel quel ; sa signature
|
|
||||||
* Ed25519 est verifiee a chaque lecture. Pas besoin de chiffrement au repos
|
|
||||||
* supplementaire — un attaquant qui a acces a la base a deja l'instance,
|
|
||||||
* et le JWT ne donne aucun pouvoir au-dela du canal beta de cette instance.
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
public class License {
|
|
||||||
|
|
||||||
private String id;
|
|
||||||
|
|
||||||
private String rawJwt;
|
|
||||||
|
|
||||||
private String patreonUserId;
|
|
||||||
|
|
||||||
private String tierId;
|
|
||||||
|
|
||||||
private String instanceId;
|
|
||||||
|
|
||||||
private Instant issuedAt;
|
|
||||||
|
|
||||||
private Instant expiresAt;
|
|
||||||
|
|
||||||
private Instant lastRefreshAttemptAt;
|
|
||||||
|
|
||||||
private boolean lastRefreshSucceeded;
|
|
||||||
|
|
||||||
private boolean betaChannelEnabled;
|
|
||||||
|
|
||||||
private Instant createdAt;
|
|
||||||
|
|
||||||
private Instant updatedAt;
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Claims extraits d'un JWT licence apres verification de signature.
|
|
||||||
* Immuable.
|
|
||||||
*/
|
|
||||||
public record LicenseClaims(
|
|
||||||
String subject,
|
|
||||||
String tierId,
|
|
||||||
String instanceId,
|
|
||||||
Instant issuedAt,
|
|
||||||
Instant expiresAt
|
|
||||||
) {}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Vue immuable de la licence pour exposition vers les couches superieures.
|
|
||||||
* Decouple le domaine du DTO web et permet de calculer le {@link LicenseStatus}
|
|
||||||
* a un instant donne sans muter l'entite.
|
|
||||||
*/
|
|
||||||
public record LicenseSnapshot(
|
|
||||||
LicenseStatus status,
|
|
||||||
String patreonUserId,
|
|
||||||
String tierId,
|
|
||||||
String instanceId,
|
|
||||||
Instant expiresAt,
|
|
||||||
Instant lastRefreshAttemptAt,
|
|
||||||
boolean lastRefreshSucceeded,
|
|
||||||
boolean betaChannelEnabled
|
|
||||||
) {
|
|
||||||
public static LicenseSnapshot none() {
|
|
||||||
return new LicenseSnapshot(LicenseStatus.NONE, null, null, null, null, null, false, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Etat operationnel de la licence vis-a-vis de l'acces beta.
|
|
||||||
* <p>
|
|
||||||
* Calcule a partir de la presence de licence + son JWT exp + grace period.
|
|
||||||
* <ul>
|
|
||||||
* <li>{@link #NONE} : aucune licence installee</li>
|
|
||||||
* <li>{@link #VALID} : JWT non expire, acces beta autorise</li>
|
|
||||||
* <li>{@link #GRACE} : JWT expire mais dans la periode de tolerance ;
|
|
||||||
* acces beta toujours autorise, l'UI doit avertir</li>
|
|
||||||
* <li>{@link #EXPIRED} : au-dela de la grace period, acces beta refuse</li>
|
|
||||||
* <li>{@link #UNVERIFIABLE} : JWT impossible a verifier (cle publique manquante,
|
|
||||||
* signature invalide, claims malformes) — traite comme NONE pour la securite</li>
|
|
||||||
* </ul>
|
|
||||||
*/
|
|
||||||
public enum LicenseStatus {
|
|
||||||
NONE,
|
|
||||||
VALID,
|
|
||||||
GRACE,
|
|
||||||
EXPIRED,
|
|
||||||
UNVERIFIABLE
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Credentials de pull pour un registry Docker, distribues par le relais
|
|
||||||
* apres verification d'un JWT licence valide.
|
|
||||||
* <p>
|
|
||||||
* {@code expiresAt} peut etre {@code null} si le credential est statique
|
|
||||||
* (cas du PAT GHCR partage en MVP) ; sinon, l'instance doit re-demander
|
|
||||||
* de nouveaux credentials avant cette date.
|
|
||||||
*/
|
|
||||||
public record RegistryCredentials(
|
|
||||||
String registry,
|
|
||||||
String username,
|
|
||||||
String password,
|
|
||||||
Instant expiresAt
|
|
||||||
) {}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.RegistryCredentials;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie : ecriture du docker config.json partage avec Watchtower.
|
|
||||||
* <p>
|
|
||||||
* Le fichier sert a Watchtower pour s'authentifier au registry prive (GHCR)
|
|
||||||
* lors du pull des images du canal beta. Volume Docker {@code docker-config}
|
|
||||||
* monte sur Core (en ecriture) et sur Watchtower (en lecture, via la variable
|
|
||||||
* {@code DOCKER_CONFIG}).
|
|
||||||
*/
|
|
||||||
public interface DockerConfigWriter {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ecrit ou met a jour les credentials pour le registry indique.
|
|
||||||
* Cree le fichier s'il n'existe pas, conserve les autres registries deja
|
|
||||||
* presents (en theorie : aucun, mais defensif).
|
|
||||||
*/
|
|
||||||
void writeCredentials(RegistryCredentials credentials) throws IOException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Supprime le fichier de credentials. Appele quand la licence est invalidee
|
|
||||||
* ou que le toggle beta passe a OFF.
|
|
||||||
*/
|
|
||||||
void clear() throws IOException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true si le fichier de creds existe actuellement.
|
|
||||||
*/
|
|
||||||
boolean isPresent();
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.LicenseClaims;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie : verification de signature et extraction des claims
|
|
||||||
* d'un JWT emis par le relais.
|
|
||||||
* <p>
|
|
||||||
* Implemente cote infrastructure avec la cle publique Ed25519 embarquee
|
|
||||||
* (SPKI PEM via configuration {@code licensing.jwt.public-key}).
|
|
||||||
*/
|
|
||||||
public interface JwtVerifier {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifie la signature, l'issuer, l'audience et l'expiration du JWT.
|
|
||||||
* @throws JwtVerificationException si la signature est invalide ou les claims malformes
|
|
||||||
*/
|
|
||||||
LicenseClaims verify(String rawJwt) throws JwtVerificationException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true si la cle publique est configuree et utilisable.
|
|
||||||
* Permet a l'application de masquer la feature licensing si pas configuree.
|
|
||||||
*/
|
|
||||||
boolean isConfigured();
|
|
||||||
|
|
||||||
class JwtVerificationException extends Exception {
|
|
||||||
public JwtVerificationException(String message) {
|
|
||||||
super(message);
|
|
||||||
}
|
|
||||||
public JwtVerificationException(String message, Throwable cause) {
|
|
||||||
super(message, cause);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.RegistryCredentials;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie vers le service relais OAuth Patreon.
|
|
||||||
* Encapsule les appels HTTP : refresh JWT et fetch registry credentials.
|
|
||||||
*/
|
|
||||||
public interface LicenseRelay {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Demande au relais l'URL OAuth a ouvrir pour connecter le compte Patreon.
|
|
||||||
*/
|
|
||||||
String buildConnectUrl(String instanceId);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Demande au relais de renouveler un JWT existant. Le relais re-verifie
|
|
||||||
* le tier Patreon de l'utilisateur ; renvoie un nouveau JWT si toujours
|
|
||||||
* actif, ou leve {@link RelayException} sinon.
|
|
||||||
*/
|
|
||||||
String refreshToken(String currentJwt) throws RelayException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Demande au relais les credentials de pull du registry beta.
|
|
||||||
*/
|
|
||||||
RegistryCredentials fetchRegistryCredentials(String currentJwt) throws RelayException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Erreurs distinctes emises par le relais. Permet au service application
|
|
||||||
* de differencier "tier expire" (action utilisateur) de "relais down"
|
|
||||||
* (action transitoire, garde la grace period).
|
|
||||||
*/
|
|
||||||
class RelayException extends Exception {
|
|
||||||
private final RelayErrorKind kind;
|
|
||||||
|
|
||||||
public RelayException(RelayErrorKind kind, String message) {
|
|
||||||
super(message);
|
|
||||||
this.kind = kind;
|
|
||||||
}
|
|
||||||
|
|
||||||
public RelayException(RelayErrorKind kind, String message, Throwable cause) {
|
|
||||||
super(message, cause);
|
|
||||||
this.kind = kind;
|
|
||||||
}
|
|
||||||
|
|
||||||
public RelayErrorKind getKind() {
|
|
||||||
return kind;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum RelayErrorKind {
|
|
||||||
/** Le relais est joignable mais refuse : tier non actif, JWT trop ancien, etc. */
|
|
||||||
REJECTED,
|
|
||||||
/** Le relais a renvoye un JWT mais il est invalide / non parsable. */
|
|
||||||
BAD_RESPONSE,
|
|
||||||
/** Le relais est injoignable / 5xx / timeout. */
|
|
||||||
TRANSIENT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.License;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie pour la persistance de la licence installee.
|
|
||||||
* <p>
|
|
||||||
* Une seule licence par instance ({@code id = "current"} par convention).
|
|
||||||
*/
|
|
||||||
public interface LicenseRepository {
|
|
||||||
|
|
||||||
Optional<License> findCurrent();
|
|
||||||
|
|
||||||
License save(License license);
|
|
||||||
|
|
||||||
void deleteCurrent();
|
|
||||||
}
|
|
||||||
@@ -21,6 +21,9 @@ public interface SessionRepository {
|
|||||||
/** Retourne UNE session active dans l'app (sémantique « legacy » — multi-actives possibles). */
|
/** Retourne UNE session active dans l'app (sémantique « legacy » — multi-actives possibles). */
|
||||||
Optional<Session> findActive();
|
Optional<Session> findActive();
|
||||||
|
|
||||||
|
/** Toutes les sessions en cours (toutes Parties confondues), la plus récente d'abord. */
|
||||||
|
List<Session> findAllActive();
|
||||||
|
|
||||||
/** Retourne la session active du Playthrough donné, s'il y en a une. */
|
/** Retourne la session active du Playthrough donné, s'il y en a une. */
|
||||||
Optional<Session> findActiveByPlaythroughId(String playthroughId);
|
Optional<Session> findActiveByPlaythroughId(String playthroughId);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package com.loremind.domain.remoteaccess;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Faits bruts sur la machine hôte, lus par le système (pas d'interprétation ici) :
|
||||||
|
* réseaux connectés avec leur catégorie Windows, et règles ENTRANTES du pare-feu qui
|
||||||
|
* visent l'exécutable de l'application.
|
||||||
|
*
|
||||||
|
* @param supported vérification possible sur ce système (Windows uniquement)
|
||||||
|
* @param program exécutable visé par les règles (DM Loremind.exe en bureau)
|
||||||
|
* @param networks réseaux connectés
|
||||||
|
* @param rules règles entrantes du pare-feu pour ce programme
|
||||||
|
* @param thirdPartyFirewalls pare-feu tiers déclarés à Windows (Bitdefender, Norton…) : ils filtrent
|
||||||
|
* EN PLUS du pare-feu Windows, avec leurs propres règles, illisibles d'ici
|
||||||
|
* @param platform {@code windows} ou {@code linux}
|
||||||
|
* @param linuxFirewall Linux : pare-feu actif détecté ({@code ufw}, {@code firewalld}, {@code none})
|
||||||
|
* @param port port réseau de l'accès distant (Linux : port à ouvrir)
|
||||||
|
* @param portOpen Linux : port autorisé par le pare-feu ; {@code null} = impossible à savoir sans
|
||||||
|
* droits administrateur (ex. règles ufw illisibles)
|
||||||
|
*/
|
||||||
|
public record NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules,
|
||||||
|
List<String> thirdPartyFirewalls, String platform, String linuxFirewall,
|
||||||
|
int port, Boolean portOpen) {
|
||||||
|
|
||||||
|
public static final String WINDOWS = "windows";
|
||||||
|
public static final String LINUX = "linux";
|
||||||
|
|
||||||
|
/** Instantané Windows (réseaux, règles du pare-feu, pare-feu tiers). */
|
||||||
|
public NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules,
|
||||||
|
List<String> thirdPartyFirewalls) {
|
||||||
|
this(supported, program, networks, rules, thirdPartyFirewalls, WINDOWS, null, 0, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Instantané Linux : pare-feu actif et état du port quand il est lisible. */
|
||||||
|
public static NetworkSnapshot linux(String linuxFirewall, int port, Boolean portOpen) {
|
||||||
|
return new NetworkSnapshot(true, null, List.of(), List.of(), List.of(), LINUX, linuxFirewall, port, portOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Catégorie Windows : {@code Public}, {@code Private} ou {@code DomainAuthenticated}. */
|
||||||
|
public record Network(String name, String alias, String category) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param action {@code Allow} ou {@code Block}
|
||||||
|
* @param profile profils couverts : {@code Any}, ou liste comme {@code Private, Public}
|
||||||
|
* @param enabled {@code True} / {@code False}
|
||||||
|
*/
|
||||||
|
public record FirewallRule(String action, String profile, String enabled) {}
|
||||||
|
|
||||||
|
public static NetworkSnapshot unsupported() {
|
||||||
|
return new NetworkSnapshot(false, null, List.of(), List.of(), List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.loremind.domain.remoteaccess;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Réglage de l'accès distant (singleton) : activé ou non, et port réseau ouvert
|
||||||
|
* sur le réseau local quand il l'est.
|
||||||
|
*
|
||||||
|
* @param enabled accès depuis le réseau local autorisé
|
||||||
|
* @param port port réseau dédié (distinct du port local de l'application)
|
||||||
|
*/
|
||||||
|
public record RemoteAccessConfig(boolean enabled, int port) {
|
||||||
|
|
||||||
|
/** Port proposé par défaut : libre en pratique, et distinct du 8080 local. */
|
||||||
|
public static final int DEFAULT_PORT = 8765;
|
||||||
|
|
||||||
|
public static RemoteAccessConfig disabledByDefault() {
|
||||||
|
return new RemoteAccessConfig(false, DEFAULT_PORT);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.loremind.domain.remoteaccess;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Appareil (tablette, téléphone) autorisé à accéder à l'application de bureau depuis
|
||||||
|
* le réseau local, après appairage par code.
|
||||||
|
* <p>
|
||||||
|
* <b>Sécurité :</b> seule l'empreinte SHA-256 du jeton est conservée ; le jeton en
|
||||||
|
* clair n'existe que dans le cookie de l'appareil. Révoquer = supprimer la ligne.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class RemoteDevice {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
/** Nom choisi à l'appairage (« Tablette de Léa »), pour s'y retrouver dans la liste. */
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** Empreinte SHA-256 (hex) du jeton d'appareil. */
|
||||||
|
private String tokenHash;
|
||||||
|
|
||||||
|
private String userAgent;
|
||||||
|
|
||||||
|
private Instant createdAt;
|
||||||
|
|
||||||
|
private Instant lastSeenAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.loremind.domain.remoteaccess.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port vers le système hôte pour que l'accès distant fonctionne vraiment : sans règle
|
||||||
|
* de pare-feu, ou sur un réseau classé « Public », Windows jette en silence les requêtes
|
||||||
|
* de la tablette (elle charge sans fin).
|
||||||
|
*/
|
||||||
|
public interface HostNetworkAccess {
|
||||||
|
|
||||||
|
/** Résultat de la demande d'autorisation dans le pare-feu. */
|
||||||
|
enum FirewallFixOutcome { APPLIED, CANCELLED, FAILED, UNSUPPORTED }
|
||||||
|
|
||||||
|
/** Lecture seule, sans droits administrateur. {@code port} : port réseau de l'accès distant. */
|
||||||
|
NetworkSnapshot inspect(int port);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Autorise l'application en entrée sur les réseaux privés. Passe par la confirmation
|
||||||
|
* administrateur du système (UAC) : bloque jusqu'à la réponse de l'utilisateur.
|
||||||
|
*/
|
||||||
|
FirewallFixOutcome allowThroughFirewall();
|
||||||
|
|
||||||
|
/** Ouvre la page des réglages réseau du système (pour passer un Wi-Fi en « Privé »). */
|
||||||
|
void openNetworkSettings();
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.loremind.domain.remoteaccess.ports;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port vers le « second guichet » réseau de l'application de bureau : un connecteur
|
||||||
|
* HTTP ouvert sur le réseau local (toutes interfaces) à côté du connecteur habituel,
|
||||||
|
* qui reste limité à la machine (127.0.0.1).
|
||||||
|
* <p>
|
||||||
|
* Tout ce qui arrive par ce connecteur vient d'un autre appareil (ou de la machine
|
||||||
|
* elle-même via son adresse réseau) et doit présenter un jeton d'appareil.
|
||||||
|
*/
|
||||||
|
public interface LanConnector {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ouvre le connecteur sur ce port (le referme d'abord s'il tournait sur un autre).
|
||||||
|
*
|
||||||
|
* @throws IllegalStateException si le port est déjà occupé ou ne peut pas être ouvert
|
||||||
|
*/
|
||||||
|
void start(int port);
|
||||||
|
|
||||||
|
void stop();
|
||||||
|
|
||||||
|
/** Port du connecteur ouvert, ou -1 s'il est fermé. */
|
||||||
|
int runningPort();
|
||||||
|
|
||||||
|
/** Adresses IPv4 de la machine sur le réseau local (pour composer l'URL à taper). */
|
||||||
|
List<String> lanAddresses();
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.domain.remoteaccess.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/** Port de persistance du réglage d'accès distant (singleton). */
|
||||||
|
public interface RemoteAccessConfigRepository {
|
||||||
|
|
||||||
|
Optional<RemoteAccessConfig> find();
|
||||||
|
|
||||||
|
RemoteAccessConfig save(RemoteAccessConfig config);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.loremind.domain.remoteaccess.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/** Port de persistance des appareils appairés. */
|
||||||
|
public interface RemoteDeviceRepository {
|
||||||
|
|
||||||
|
RemoteDevice save(RemoteDevice device);
|
||||||
|
|
||||||
|
Optional<RemoteDevice> findByTokenHash(String tokenHash);
|
||||||
|
|
||||||
|
List<RemoteDevice> findAll();
|
||||||
|
|
||||||
|
void touch(String id, Instant lastSeenAt);
|
||||||
|
|
||||||
|
boolean deleteById(String id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.loremind.domain.shared.ports;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port : langue de l'interface de l'utilisateur courant ({@code fr} ou {@code en}), pour les
|
||||||
|
* contenus qui existent en deux langues (règles d'un système de jeu). Implémenté côté web.
|
||||||
|
*/
|
||||||
|
public interface CurrentLanguage {
|
||||||
|
|
||||||
|
/** Code court de la langue courante ({@code fr} par défaut). */
|
||||||
|
String get();
|
||||||
|
}
|
||||||
@@ -26,22 +26,25 @@ import java.util.function.Consumer;
|
|||||||
@Component
|
@Component
|
||||||
public class BrainCampaignAdaptClient implements CampaignPdfAdvisor {
|
public class BrainCampaignAdaptClient implements CampaignPdfAdvisor {
|
||||||
|
|
||||||
private static final String ADAPT_PATH = "/adapt/campaign/stream";
|
|
||||||
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
||||||
new ParameterizedTypeReference<>() {};
|
new ParameterizedTypeReference<>() {};
|
||||||
|
|
||||||
private final WebClient webClient;
|
private final WebClient webClient;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final long timeoutSeconds;
|
private final long timeoutSeconds;
|
||||||
|
// Route du Brain surchargeable par config (défaut = contrat d'API actuel).
|
||||||
|
private final String adaptPath;
|
||||||
|
|
||||||
public BrainCampaignAdaptClient(
|
public BrainCampaignAdaptClient(
|
||||||
WebClient.Builder webClientBuilder,
|
WebClient.Builder webClientBuilder,
|
||||||
ObjectMapper objectMapper,
|
ObjectMapper objectMapper,
|
||||||
@Value("${brain.base-url}") String baseUrl,
|
@Value("${brain.base-url}") String baseUrl,
|
||||||
@Value("${brain.import-timeout-seconds:600}") long timeoutSeconds) {
|
@Value("${brain.import-timeout-seconds:600}") long timeoutSeconds,
|
||||||
|
@Value("${brain.paths.adapt-campaign:/adapt/campaign/stream}") String adaptPath) {
|
||||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||||
this.objectMapper = objectMapper;
|
this.objectMapper = objectMapper;
|
||||||
this.timeoutSeconds = timeoutSeconds;
|
this.timeoutSeconds = timeoutSeconds;
|
||||||
|
this.adaptPath = adaptPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -65,7 +68,7 @@ public class BrainCampaignAdaptClient implements CampaignPdfAdvisor {
|
|||||||
parts.part("messages", (messagesJson == null || messagesJson.isBlank()) ? "[]" : messagesJson);
|
parts.part("messages", (messagesJson == null || messagesJson.isBlank()) ? "[]" : messagesJson);
|
||||||
|
|
||||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||||
.uri(ADAPT_PATH)
|
.uri(adaptPath)
|
||||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||||
|
|||||||
@@ -36,24 +36,37 @@ import java.util.function.Consumer;
|
|||||||
@Component
|
@Component
|
||||||
public class BrainCampaignImportClient implements CampaignPdfImporter {
|
public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||||
|
|
||||||
private static final String IMPORT_CAMPAIGN_STREAM_PATH = "/import/campaign/stream";
|
|
||||||
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
||||||
new ParameterizedTypeReference<>() {};
|
new ParameterizedTypeReference<>() {};
|
||||||
|
/** Champ JSON répété du proposal d'arbre (arc/chapitre/scène/salle/PNJ). */
|
||||||
|
private static final String FIELD_DESCRIPTION = "description";
|
||||||
|
|
||||||
private final WebClient webClient;
|
private final WebClient webClient;
|
||||||
private final BrainSseImportSupport sse;
|
private final BrainSseImportSupport sse;
|
||||||
private final long importTimeoutSeconds;
|
private final long importTimeoutSeconds;
|
||||||
|
// Route du Brain surchargeable par config (défaut = contrat d'API actuel).
|
||||||
|
private final String importCampaignStreamPath;
|
||||||
|
|
||||||
public BrainCampaignImportClient(
|
public BrainCampaignImportClient(
|
||||||
WebClient.Builder webClientBuilder,
|
WebClient.Builder webClientBuilder,
|
||||||
ObjectMapper objectMapper,
|
ObjectMapper objectMapper,
|
||||||
@Value("${brain.base-url}") String baseUrl,
|
@Value("${brain.base-url}") String baseUrl,
|
||||||
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds) {
|
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
|
||||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
@Value("${brain.paths.import-campaign:/import/campaign/stream}") String importCampaignStreamPath) {
|
||||||
|
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
|
||||||
this.sse = new BrainSseImportSupport(objectMapper);
|
this.sse = new BrainSseImportSupport(objectMapper);
|
||||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||||
|
this.importCampaignStreamPath = importCampaignStreamPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Callbacks de streaming groupés (réduit le nombre de paramètres de handleEvent). */
|
||||||
|
private record ImportCallbacks(
|
||||||
|
Consumer<CampaignImportProgress> onProgress,
|
||||||
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
|
Consumer<CampaignImportProposal> onDone,
|
||||||
|
Consumer<Throwable> onError) {}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void importCampaignStreaming(
|
public void importCampaignStreaming(
|
||||||
byte[] pdfBytes,
|
byte[] pdfBytes,
|
||||||
@@ -69,7 +82,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
.filename(filename == null || filename.isBlank() ? "campaign.pdf" : filename);
|
.filename(filename == null || filename.isBlank() ? "campaign.pdf" : filename);
|
||||||
|
|
||||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||||
.uri(IMPORT_CAMPAIGN_STREAM_PATH)
|
.uri(importCampaignStreamPath)
|
||||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||||
@@ -80,12 +93,11 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
int[] pageCount = {0};
|
int[] pageCount = {0};
|
||||||
int[] ocrPageCount = {0};
|
int[] ocrPageCount = {0};
|
||||||
boolean[] terminated = {false};
|
boolean[] terminated = {false};
|
||||||
|
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onError);
|
||||||
|
|
||||||
sse.runStream(
|
sse.runStream(
|
||||||
flux, importTimeoutSeconds, terminated,
|
flux, importTimeoutSeconds, terminated,
|
||||||
event -> handleEvent(
|
event -> handleEvent(event, pageCount, ocrPageCount, terminated, callbacks),
|
||||||
event, pageCount, ocrPageCount, terminated,
|
|
||||||
onProgress, onHeartbeat, onStatus, onDone, onError),
|
|
||||||
onError, CampaignImportException::new);
|
onError, CampaignImportException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,11 +106,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
int[] pageCount,
|
int[] pageCount,
|
||||||
int[] ocrPageCount,
|
int[] ocrPageCount,
|
||||||
boolean[] terminated,
|
boolean[] terminated,
|
||||||
Consumer<CampaignImportProgress> onProgress,
|
ImportCallbacks callbacks) {
|
||||||
Runnable onHeartbeat,
|
|
||||||
Consumer<String> onStatus,
|
|
||||||
Consumer<CampaignImportProposal> onDone,
|
|
||||||
Consumer<Throwable> onError) {
|
|
||||||
|
|
||||||
String event = ssEvent.event();
|
String event = ssEvent.event();
|
||||||
String data = ssEvent.data() == null ? "" : ssEvent.data();
|
String data = ssEvent.data() == null ? "" : ssEvent.data();
|
||||||
@@ -106,27 +114,27 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
if ("heartbeat".equals(event)) {
|
if ("heartbeat".equals(event)) {
|
||||||
// Keep-alive du Brain pendant un appel LLM long : à PROPAGER jusqu'au
|
// Keep-alive du Brain pendant un appel LLM long : à PROPAGER jusqu'au
|
||||||
// navigateur, sinon nginx (proxy_read_timeout) coupe le SSE Core→front.
|
// navigateur, sinon nginx (proxy_read_timeout) coupe le SSE Core→front.
|
||||||
onHeartbeat.run();
|
callbacks.onHeartbeat().run();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("status".equals(event)) {
|
if ("status".equals(event)) {
|
||||||
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
||||||
// re-découpé…) : affiché par l'UI au lieu de n'exister qu'en logs.
|
// re-découpé…) : affiché par l'UI au lieu de n'exister qu'en logs.
|
||||||
onStatus.accept(sse.readMessage(data));
|
callbacks.onStatus().accept(sse.readMessage(data));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("chunk_failed".equals(event)) {
|
if ("chunk_failed".equals(event)) {
|
||||||
onStatus.accept(sse.chunkFailedStatus(data));
|
callbacks.onStatus().accept(sse.chunkFailedStatus(data));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("error".equals(event)) {
|
if ("error".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
onError.accept(new CampaignImportException(
|
callbacks.onError().accept(new CampaignImportException(
|
||||||
"Le Brain a signalé une erreur : " + sse.readMessage(data)));
|
"Le Brain a signalé une erreur : " + sse.readMessage(data)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("extracting".equals(event)) {
|
if ("extracting".equals(event)) {
|
||||||
onProgress.accept(new CampaignImportProgress(0, 0, 0, 0, 0, 0, 0, 0));
|
callbacks.onProgress().accept(new CampaignImportProgress(0, 0, 0, 0, 0, 0, 0, 0));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,10 +144,10 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
if ("start".equals(event)) {
|
if ("start".equals(event)) {
|
||||||
pageCount[0] = node.path("page_count").asInt();
|
pageCount[0] = node.path("page_count").asInt();
|
||||||
ocrPageCount[0] = node.path("ocr_page_count").asInt();
|
ocrPageCount[0] = node.path("ocr_page_count").asInt();
|
||||||
onProgress.accept(new CampaignImportProgress(
|
callbacks.onProgress().accept(new CampaignImportProgress(
|
||||||
0, node.path("total").asInt(), pageCount[0], ocrPageCount[0], 0, 0, 0, 0));
|
0, node.path("total").asInt(), pageCount[0], ocrPageCount[0], 0, 0, 0, 0));
|
||||||
} else if ("progress".equals(event)) {
|
} else if ("progress".equals(event)) {
|
||||||
onProgress.accept(new CampaignImportProgress(
|
callbacks.onProgress().accept(new CampaignImportProgress(
|
||||||
node.path("current").asInt(),
|
node.path("current").asInt(),
|
||||||
node.path("total").asInt(),
|
node.path("total").asInt(),
|
||||||
pageCount[0],
|
pageCount[0],
|
||||||
@@ -150,7 +158,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
node.path("npc_count").asInt()));
|
node.path("npc_count").asInt()));
|
||||||
} else if ("done".equals(event)) {
|
} else if ("done".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
onDone.accept(new CampaignImportProposal(
|
callbacks.onDone().accept(new CampaignImportProposal(
|
||||||
toArcs(node.path("arcs")), toNpcs(node.path("npcs"))));
|
toArcs(node.path("arcs")), toNpcs(node.path("npcs"))));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -163,7 +171,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
for (JsonNode arc : arcsNode) {
|
for (JsonNode arc : arcsNode) {
|
||||||
arcs.add(new ArcProposal(
|
arcs.add(new ArcProposal(
|
||||||
text(arc, "name"),
|
text(arc, "name"),
|
||||||
text(arc, "description"),
|
text(arc, FIELD_DESCRIPTION),
|
||||||
text(arc, "type"),
|
text(arc, "type"),
|
||||||
toChapters(arc.path("chapters")),
|
toChapters(arc.path("chapters")),
|
||||||
null));
|
null));
|
||||||
@@ -178,7 +186,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
for (JsonNode ch : chaptersNode) {
|
for (JsonNode ch : chaptersNode) {
|
||||||
chapters.add(new ChapterProposal(
|
chapters.add(new ChapterProposal(
|
||||||
text(ch, "name"),
|
text(ch, "name"),
|
||||||
text(ch, "description"),
|
text(ch, FIELD_DESCRIPTION),
|
||||||
toScenes(ch.path("scenes")),
|
toScenes(ch.path("scenes")),
|
||||||
null));
|
null));
|
||||||
}
|
}
|
||||||
@@ -191,7 +199,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
if (scenesNode != null && scenesNode.isArray()) {
|
if (scenesNode != null && scenesNode.isArray()) {
|
||||||
for (JsonNode sc : scenesNode) {
|
for (JsonNode sc : scenesNode) {
|
||||||
scenes.add(new SceneProposal(
|
scenes.add(new SceneProposal(
|
||||||
text(sc, "name"), text(sc, "description"),
|
text(sc, "name"), text(sc, FIELD_DESCRIPTION),
|
||||||
text(sc, "player_narration"), text(sc, "gm_notes"),
|
text(sc, "player_narration"), text(sc, "gm_notes"),
|
||||||
toRooms(sc.path("rooms")), null));
|
toRooms(sc.path("rooms")), null));
|
||||||
}
|
}
|
||||||
@@ -204,7 +212,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
if (roomsNode != null && roomsNode.isArray()) {
|
if (roomsNode != null && roomsNode.isArray()) {
|
||||||
for (JsonNode rm : roomsNode) {
|
for (JsonNode rm : roomsNode) {
|
||||||
rooms.add(new RoomProposal(
|
rooms.add(new RoomProposal(
|
||||||
text(rm, "name"), text(rm, "description"),
|
text(rm, "name"), text(rm, FIELD_DESCRIPTION),
|
||||||
text(rm, "enemies"), text(rm, "loot")));
|
text(rm, "enemies"), text(rm, "loot")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,7 +223,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
List<NpcProposal> npcs = new ArrayList<>();
|
List<NpcProposal> npcs = new ArrayList<>();
|
||||||
if (npcsNode != null && npcsNode.isArray()) {
|
if (npcsNode != null && npcsNode.isArray()) {
|
||||||
for (JsonNode n : npcsNode) {
|
for (JsonNode n : npcsNode) {
|
||||||
npcs.add(new NpcProposal(text(n, "name"), text(n, "description")));
|
npcs.add(new NpcProposal(text(n, "name"), text(n, FIELD_DESCRIPTION)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return npcs;
|
return npcs;
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.stream.Collectors;
|
import java.util.function.ToIntFunction;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper d'infrastructure : traduit un ChatRequest (domaine) vers le dict JSON
|
* Helper d'infrastructure : traduit un ChatRequest (domaine) vers le dict JSON
|
||||||
@@ -40,11 +40,14 @@ import java.util.stream.Collectors;
|
|||||||
@Component
|
@Component
|
||||||
public class BrainChatPayloadBuilder {
|
public class BrainChatPayloadBuilder {
|
||||||
|
|
||||||
|
private static final String KEY_DESCRIPTION = "description";
|
||||||
|
private static final String KEY_TITLE = "title";
|
||||||
|
|
||||||
public Map<String, Object> build(ChatRequest request) {
|
public Map<String, Object> build(ChatRequest request) {
|
||||||
Map<String, Object> root = new LinkedHashMap<>();
|
Map<String, Object> root = new LinkedHashMap<>();
|
||||||
root.put("messages", request.messages().stream()
|
root.put("messages", request.messages().stream()
|
||||||
.map(this::messageToMap)
|
.map(this::messageToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
|
|
||||||
if (request.loreContext() != null) {
|
if (request.loreContext() != null) {
|
||||||
root.put("lore_context", loreContextToMap(request.loreContext()));
|
root.put("lore_context", loreContextToMap(request.loreContext()));
|
||||||
@@ -75,25 +78,25 @@ public class BrainChatPayloadBuilder {
|
|||||||
map.put("started_at", sc.startedAt().toString());
|
map.put("started_at", sc.startedAt().toString());
|
||||||
}
|
}
|
||||||
map.put("entries", sc.entries() != null
|
map.put("entries", sc.entries() != null
|
||||||
? sc.entries().stream().map(this::journalEntryToMap).collect(Collectors.toList())
|
? sc.entries().stream().map(this::journalEntryToMap).toList()
|
||||||
: List.of());
|
: List.of());
|
||||||
// Évènements des sessions précédentes : omis si vide (campagne sur sa 1re session).
|
// Évènements des sessions précédentes : omis si vide (campagne sur sa 1re session).
|
||||||
if (sc.previousEvents() != null && !sc.previousEvents().isEmpty()) {
|
if (sc.previousEvents() != null && !sc.previousEvents().isEmpty()) {
|
||||||
map.put("previous_events", sc.previousEvents().stream()
|
map.put("previous_events", sc.previousEvents().stream()
|
||||||
.map(this::journalEntryToMap)
|
.map(this::journalEntryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
// État Hub (quêtes / flags). Toutes les listes sont omises si vides pour ne pas
|
// État Hub (quêtes / flags). Toutes les listes sont omises si vides pour ne pas
|
||||||
// saturer le prompt sur les campagnes sans Hub.
|
// saturer le prompt sur les campagnes sans Hub.
|
||||||
if (sc.availableQuests() != null && !sc.availableQuests().isEmpty()) {
|
if (sc.availableQuests() != null && !sc.availableQuests().isEmpty()) {
|
||||||
map.put("available_quests", sc.availableQuests().stream()
|
map.put("available_quests", sc.availableQuests().stream()
|
||||||
.map(this::questSummaryToMap)
|
.map(this::questSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
if (sc.inProgressQuests() != null && !sc.inProgressQuests().isEmpty()) {
|
if (sc.inProgressQuests() != null && !sc.inProgressQuests().isEmpty()) {
|
||||||
map.put("in_progress_quests", sc.inProgressQuests().stream()
|
map.put("in_progress_quests", sc.inProgressQuests().stream()
|
||||||
.map(this::questSummaryToMap)
|
.map(this::questSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
if (sc.lockedQuestTitles() != null && !sc.lockedQuestTitles().isEmpty()) {
|
if (sc.lockedQuestTitles() != null && !sc.lockedQuestTitles().isEmpty()) {
|
||||||
map.put("locked_quest_titles", sc.lockedQuestTitles());
|
map.put("locked_quest_titles", sc.lockedQuestTitles());
|
||||||
@@ -108,7 +111,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("name", q.name());
|
map.put("name", q.name());
|
||||||
map.put("arc_name", q.arcName());
|
map.put("arc_name", q.arcName());
|
||||||
putIfText(map, "description", q.description());
|
putIfText(map, KEY_DESCRIPTION, q.description());
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,7 +150,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
for (Map.Entry<String, List<PageSummary>> e : ctx.folders().entrySet()) {
|
for (Map.Entry<String, List<PageSummary>> e : ctx.folders().entrySet()) {
|
||||||
foldersMap.put(e.getKey(), e.getValue().stream()
|
foldersMap.put(e.getKey(), e.getValue().stream()
|
||||||
.map(this::pageSummaryToMap)
|
.map(this::pageSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
map.put("folders", foldersMap);
|
map.put("folders", foldersMap);
|
||||||
map.put("tags", ctx.tags());
|
map.put("tags", ctx.tags());
|
||||||
@@ -156,7 +159,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
|
|
||||||
private Map<String, Object> pageSummaryToMap(PageSummary ps) {
|
private Map<String, Object> pageSummaryToMap(PageSummary ps) {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("title", ps.title());
|
map.put(KEY_TITLE, ps.title());
|
||||||
map.put("template_name", ps.templateName());
|
map.put("template_name", ps.templateName());
|
||||||
// values/tags/related_page_titles : omis si vides pour alléger le payload.
|
// values/tags/related_page_titles : omis si vides pour alléger le payload.
|
||||||
if (ps.values() != null && !ps.values().isEmpty()) {
|
if (ps.values() != null && !ps.values().isEmpty()) {
|
||||||
@@ -173,7 +176,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
|
|
||||||
private Map<String, Object> pageContextToMap(PageContext pc) {
|
private Map<String, Object> pageContextToMap(PageContext pc) {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("title", pc.title());
|
map.put(KEY_TITLE, pc.title());
|
||||||
map.put("template_name", pc.templateName());
|
map.put("template_name", pc.templateName());
|
||||||
map.put("template_fields", pc.templateFields());
|
map.put("template_fields", pc.templateFields());
|
||||||
map.put("values", pc.values());
|
map.put("values", pc.values());
|
||||||
@@ -186,18 +189,18 @@ public class BrainChatPayloadBuilder {
|
|||||||
map.put("campaign_description", ctx.campaignDescription());
|
map.put("campaign_description", ctx.campaignDescription());
|
||||||
map.put("arcs", ctx.arcs().stream()
|
map.put("arcs", ctx.arcs().stream()
|
||||||
.map(this::arcSummaryToMap)
|
.map(this::arcSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
// Liste des PJ : omise si aucun pour alléger le prompt des campagnes sans fiches.
|
// Liste des PJ : omise si aucun pour alléger le prompt des campagnes sans fiches.
|
||||||
if (ctx.characters() != null && !ctx.characters().isEmpty()) {
|
if (ctx.characters() != null && !ctx.characters().isEmpty()) {
|
||||||
map.put("characters", ctx.characters().stream()
|
map.put("characters", ctx.characters().stream()
|
||||||
.map(this::characterSummaryToMap)
|
.map(this::characterSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
// Liste des PNJ : symétrique aux PJ, omise si vide pour alléger le payload.
|
// Liste des PNJ : symétrique aux PJ, omise si vide pour alléger le payload.
|
||||||
if (ctx.npcs() != null && !ctx.npcs().isEmpty()) {
|
if (ctx.npcs() != null && !ctx.npcs().isEmpty()) {
|
||||||
map.put("npcs", ctx.npcs().stream()
|
map.put("npcs", ctx.npcs().stream()
|
||||||
.map(this::npcSummaryToMap)
|
.map(this::npcSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
@@ -224,13 +227,14 @@ public class BrainChatPayloadBuilder {
|
|||||||
T entity,
|
T entity,
|
||||||
Function<T, String> nameExtractor,
|
Function<T, String> nameExtractor,
|
||||||
Function<T, String> descriptionExtractor,
|
Function<T, String> descriptionExtractor,
|
||||||
Function<T, Integer> illustrationCountExtractor,
|
ToIntFunction<T> illustrationCountExtractor,
|
||||||
BiConsumer<Map<String, Object>, T> childSerializer) {
|
BiConsumer<Map<String, Object>, T> childSerializer) {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("name", nameExtractor.apply(entity));
|
map.put("name", nameExtractor.apply(entity));
|
||||||
map.put("description", descriptionExtractor.apply(entity));
|
map.put(KEY_DESCRIPTION, descriptionExtractor.apply(entity));
|
||||||
if (illustrationCountExtractor.apply(entity) > 0) {
|
int illustrationCount = illustrationCountExtractor.applyAsInt(entity);
|
||||||
map.put("illustration_count", illustrationCountExtractor.apply(entity));
|
if (illustrationCount > 0) {
|
||||||
|
map.put("illustration_count", illustrationCount);
|
||||||
}
|
}
|
||||||
childSerializer.accept(map, entity);
|
childSerializer.accept(map, entity);
|
||||||
return map;
|
return map;
|
||||||
@@ -249,7 +253,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
}
|
}
|
||||||
map.put("chapters", arc.chapters().stream()
|
map.put("chapters", arc.chapters().stream()
|
||||||
.map(this::chapterSummaryToMap)
|
.map(this::chapterSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,7 +265,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
ChapterSummary::illustrationCount,
|
ChapterSummary::illustrationCount,
|
||||||
(map, chapter) -> map.put("scenes", chapter.scenes().stream()
|
(map, chapter) -> map.put("scenes", chapter.scenes().stream()
|
||||||
.map(this::sceneSummaryToMap)
|
.map(this::sceneSummaryToMap)
|
||||||
.collect(Collectors.toList())));
|
.toList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> sceneSummaryToMap(SceneSummary s) {
|
private Map<String, Object> sceneSummaryToMap(SceneSummary s) {
|
||||||
@@ -275,13 +279,13 @@ public class BrainChatPayloadBuilder {
|
|||||||
if (s.branches() != null && !s.branches().isEmpty()) {
|
if (s.branches() != null && !s.branches().isEmpty()) {
|
||||||
map.put("branches", s.branches().stream()
|
map.put("branches", s.branches().stream()
|
||||||
.map(this::branchHintToMap)
|
.map(this::branchHintToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
// Pièces du lieu explorable : omises si scène classique.
|
// Pièces du lieu explorable : omises si scène classique.
|
||||||
if (s.rooms() != null && !s.rooms().isEmpty()) {
|
if (s.rooms() != null && !s.rooms().isEmpty()) {
|
||||||
map.put("rooms", s.rooms().stream()
|
map.put("rooms", s.rooms().stream()
|
||||||
.map(this::roomSummaryToMap)
|
.map(this::roomSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -298,7 +302,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("name", r.name());
|
map.put("name", r.name());
|
||||||
if (r.floor() != null) map.put("floor", r.floor());
|
if (r.floor() != null) map.put("floor", r.floor());
|
||||||
putIfText(map, "description", r.description());
|
putIfText(map, KEY_DESCRIPTION, r.description());
|
||||||
putIfText(map, "enemies", r.enemies());
|
putIfText(map, "enemies", r.enemies());
|
||||||
if (r.branches() != null && !r.branches().isEmpty()) {
|
if (r.branches() != null && !r.branches().isEmpty()) {
|
||||||
map.put("branches", r.branches().stream().map(b -> {
|
map.put("branches", r.branches().stream().map(b -> {
|
||||||
@@ -307,7 +311,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
bm.put("target_room_name", b.targetRoomName());
|
bm.put("target_room_name", b.targetRoomName());
|
||||||
putIfText(bm, "condition", b.condition());
|
putIfText(bm, "condition", b.condition());
|
||||||
return bm;
|
return bm;
|
||||||
}).collect(Collectors.toList()));
|
}).toList());
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
@@ -315,7 +319,7 @@ public class BrainChatPayloadBuilder {
|
|||||||
private Map<String, Object> narrativeEntityToMap(NarrativeEntityContext ne) {
|
private Map<String, Object> narrativeEntityToMap(NarrativeEntityContext ne) {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
map.put("entity_type", ne.entityType());
|
map.put("entity_type", ne.entityType());
|
||||||
map.put("title", ne.title());
|
map.put(KEY_TITLE, ne.title());
|
||||||
map.put("fields", ne.fields());
|
map.put("fields", ne.fields());
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import java.time.Duration;
|
|||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adaptateur : appelle le Brain POST /summarize/conversation-title pour
|
* Adaptateur : appelle le Brain POST /summarize/conversation-title pour
|
||||||
@@ -45,7 +44,7 @@ public class BrainConversationTitleClient implements ConversationTitleGenerator
|
|||||||
.map(m -> Map.<String, Object>of(
|
.map(m -> Map.<String, Object>of(
|
||||||
"role", m.getRole(),
|
"role", m.getRole(),
|
||||||
"content", m.getContent() == null ? "" : m.getContent()))
|
"content", m.getContent() == null ? "" : m.getContent()))
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : propositions de réponses aux méthodes guidées via le Brain
|
||||||
|
* ({@code POST /generate/guided-answers}, one-shot). La langue de l'interface est relayée par
|
||||||
|
* l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainGuidedAnswersClient implements GuidedMethodAssistant {
|
||||||
|
|
||||||
|
private static final String PATH = "/generate/guided-answers";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainGuidedAnswersClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, String> answer(String methodName, String principle, String idea, String context,
|
||||||
|
List<Question> questions, Map<String, String> existing) {
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("method_name", nz(methodName));
|
||||||
|
req.put("method_principle", nz(principle));
|
||||||
|
req.put("idea", nz(idea));
|
||||||
|
req.put("context", nz(context));
|
||||||
|
req.put("fields", toPayload(questions));
|
||||||
|
req.put("existing", existing == null ? Map.of() : existing);
|
||||||
|
return parse(call(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<Map<String, Object>> toPayload(List<Question> questions) {
|
||||||
|
List<Map<String, Object>> out = new ArrayList<>();
|
||||||
|
for (Question q : questions) {
|
||||||
|
Map<String, Object> f = new LinkedHashMap<>();
|
||||||
|
f.put("key", q.key());
|
||||||
|
f.put("label", nz(q.label()).isEmpty() ? q.key() : q.label());
|
||||||
|
f.put("hint", nz(q.hint()));
|
||||||
|
f.put("step", nz(q.step()));
|
||||||
|
List<Map<String, String>> options = new ArrayList<>();
|
||||||
|
if (q.options() != null) {
|
||||||
|
for (Choice c : q.options()) {
|
||||||
|
if (c != null && c.value() != null) options.add(Map.of("value", c.value(), "label", nz(c.label())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.put("options", options);
|
||||||
|
out.add(f);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> call(Map<String, Object> req) {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new NarrativeAssistException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new NarrativeAssistException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new NarrativeAssistException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, String> parse(Map<String, Object> resp) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (resp.get("answers") instanceof Map<?, ?> m) {
|
||||||
|
m.forEach((k, v) -> {
|
||||||
|
if (k != null && v != null) out.put(k.toString(), v.toString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String s) {
|
||||||
|
return s == null ? "" : s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,6 +24,7 @@ import java.util.Map;
|
|||||||
public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
||||||
|
|
||||||
private static final String GENERATE_PATH = "/generate/item-catalog";
|
private static final String GENERATE_PATH = "/generate/item-catalog";
|
||||||
|
private static final String KEY_DESCRIPTION = "description";
|
||||||
|
|
||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
private final String baseUrl;
|
private final String baseUrl;
|
||||||
@@ -36,10 +37,25 @@ public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
public GeneratedCatalog generate(String description, String context) {
|
public GeneratedCatalog generate(String description, String context) {
|
||||||
|
Map<String, Object> resp = callBrain(description, context);
|
||||||
|
|
||||||
|
List<CatalogItem> items = parseItems(resp.get("items"));
|
||||||
|
if (items.isEmpty()) {
|
||||||
|
throw new ItemCatalogGenerationException("Aucun objet généré — réessaie ou reformule.");
|
||||||
|
}
|
||||||
|
String name = asString(resp.get("name"));
|
||||||
|
return new GeneratedCatalog(
|
||||||
|
name != null && !name.isBlank() ? name : description,
|
||||||
|
asString(resp.get(KEY_DESCRIPTION)),
|
||||||
|
items);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST one-shot vers le Brain ; toute erreur devient une ItemCatalogGenerationException parlante. */
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> callBrain(String description, String context) {
|
||||||
Map<String, Object> req = new LinkedHashMap<>();
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
req.put("description", description == null ? "" : description);
|
req.put(KEY_DESCRIPTION, description == null ? "" : description);
|
||||||
req.put("context", context == null ? "" : context);
|
req.put("context", context == null ? "" : context);
|
||||||
|
|
||||||
HttpHeaders headers = new HttpHeaders();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
@@ -60,30 +76,38 @@ public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
|||||||
if (resp == null) {
|
if (resp == null) {
|
||||||
throw new ItemCatalogGenerationException("Le Brain a renvoyé une réponse vide.");
|
throw new ItemCatalogGenerationException("Le Brain a renvoyé une réponse vide.");
|
||||||
}
|
}
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Items valides de la réponse (entrées malformées ou sans nom ignorées). */
|
||||||
|
private static List<CatalogItem> parseItems(Object rawItems) {
|
||||||
List<CatalogItem> items = new ArrayList<>();
|
List<CatalogItem> items = new ArrayList<>();
|
||||||
Object rawItems = resp.get("items");
|
|
||||||
if (rawItems instanceof List<?> list) {
|
if (rawItems instanceof List<?> list) {
|
||||||
for (Object item : list) {
|
for (Object raw : list) {
|
||||||
if (!(item instanceof Map<?, ?> m)) continue;
|
CatalogItem item = toItem(raw);
|
||||||
String name = asString(m.get("name"));
|
if (item != null) {
|
||||||
if (name == null || name.isBlank()) continue;
|
items.add(item);
|
||||||
items.add(CatalogItem.builder()
|
}
|
||||||
.name(name)
|
|
||||||
.price(asString(m.get("price")))
|
|
||||||
.category(asString(m.get("category")))
|
|
||||||
.description(asString(m.get("description")))
|
|
||||||
.build());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (items.isEmpty()) {
|
return items;
|
||||||
throw new ItemCatalogGenerationException("Aucun objet généré — réessaie ou reformule.");
|
}
|
||||||
|
|
||||||
|
/** Un CatalogItem depuis une entrée brute, ou null si malformée / sans nom. */
|
||||||
|
private static CatalogItem toItem(Object raw) {
|
||||||
|
if (!(raw instanceof Map<?, ?> m)) {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
String name = asString(resp.get("name"));
|
String name = asString(m.get("name"));
|
||||||
return new GeneratedCatalog(
|
if (name == null || name.isBlank()) {
|
||||||
name != null && !name.isBlank() ? name : description,
|
return null;
|
||||||
asString(resp.get("description")),
|
}
|
||||||
items);
|
return CatalogItem.builder()
|
||||||
|
.name(name)
|
||||||
|
.price(asString(m.get("price")))
|
||||||
|
.category(asString(m.get("category")))
|
||||||
|
.description(asString(m.get(KEY_DESCRIPTION)))
|
||||||
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String asString(Object o) {
|
private static String asString(Object o) {
|
||||||
|
|||||||
@@ -39,20 +39,9 @@ public class BrainNarrativeFieldClient implements NarrativeFieldAssistant {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
public List<ProposedField> assist(String entityType, String context, String instruction, List<FieldSpec> fields) {
|
public List<ProposedField> assist(String entityType, String context, String instruction, List<FieldSpec> fields) {
|
||||||
List<Map<String, String>> fieldPayload = new ArrayList<>();
|
List<Map<String, String>> fieldPayload = buildFieldPayload(fields);
|
||||||
Set<String> allowed = new HashSet<>();
|
Set<String> allowed = allowedKeys(fields);
|
||||||
if (fields != null) {
|
|
||||||
for (FieldSpec f : fields) {
|
|
||||||
if (f == null || f.key() == null) continue;
|
|
||||||
allowed.add(f.key());
|
|
||||||
Map<String, String> fm = new LinkedHashMap<>();
|
|
||||||
fm.put("key", f.key());
|
|
||||||
fm.put("label", f.label() == null ? f.key() : f.label());
|
|
||||||
fieldPayload.add(fm);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, Object> req = new LinkedHashMap<>();
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
req.put("entity_type", entityType == null ? "" : entityType);
|
req.put("entity_type", entityType == null ? "" : entityType);
|
||||||
@@ -60,6 +49,38 @@ public class BrainNarrativeFieldClient implements NarrativeFieldAssistant {
|
|||||||
req.put("instruction", instruction == null ? "" : instruction);
|
req.put("instruction", instruction == null ? "" : instruction);
|
||||||
req.put("fields", fieldPayload);
|
req.put("fields", fieldPayload);
|
||||||
|
|
||||||
|
Map<String, Object> resp = callBrain(req);
|
||||||
|
return parseProposedFields(resp.get("fields"), allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Payload des champs à étoffer : {key, label} par champ valide (libellé = clé à défaut). */
|
||||||
|
private static List<Map<String, String>> buildFieldPayload(List<FieldSpec> fields) {
|
||||||
|
List<Map<String, String>> payload = new ArrayList<>();
|
||||||
|
for (FieldSpec f : nullSafe(fields)) {
|
||||||
|
if (f != null && f.key() != null) {
|
||||||
|
Map<String, String> fm = new LinkedHashMap<>();
|
||||||
|
fm.put("key", f.key());
|
||||||
|
fm.put("label", f.label() == null ? f.key() : f.label());
|
||||||
|
payload.add(fm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whitelist des clés autorisées en retour (garde-fou contre les clés inventées). */
|
||||||
|
private static Set<String> allowedKeys(List<FieldSpec> fields) {
|
||||||
|
Set<String> allowed = new HashSet<>();
|
||||||
|
for (FieldSpec f : nullSafe(fields)) {
|
||||||
|
if (f != null && f.key() != null) {
|
||||||
|
allowed.add(f.key());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST one-shot vers le Brain ; toute erreur devient une NarrativeAssistException parlante. */
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> callBrain(Map<String, Object> req) {
|
||||||
HttpHeaders headers = new HttpHeaders();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(req, headers);
|
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(req, headers);
|
||||||
@@ -78,18 +99,37 @@ public class BrainNarrativeFieldClient implements NarrativeFieldAssistant {
|
|||||||
if (resp == null) {
|
if (resp == null) {
|
||||||
throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
|
throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
|
||||||
}
|
}
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Champs proposés retenus : clé dans la whitelist ET valeur non vide (trim). */
|
||||||
|
private static List<ProposedField> parseProposedFields(Object rawFields, Set<String> allowed) {
|
||||||
List<ProposedField> out = new ArrayList<>();
|
List<ProposedField> out = new ArrayList<>();
|
||||||
Object rawFields = resp.get("fields");
|
|
||||||
if (rawFields instanceof Map<?, ?> m) {
|
if (rawFields instanceof Map<?, ?> m) {
|
||||||
for (Map.Entry<?, ?> e : m.entrySet()) {
|
for (Map.Entry<?, ?> e : m.entrySet()) {
|
||||||
String key = e.getKey() == null ? null : e.getKey().toString();
|
ProposedField field = toProposedField(e, allowed);
|
||||||
if (key == null || !allowed.contains(key)) continue; // whitelist stricte
|
if (field != null) {
|
||||||
String value = e.getValue() == null ? null : e.getValue().toString();
|
out.add(field);
|
||||||
if (value == null || value.isBlank()) continue; // pas de remplissage vide
|
}
|
||||||
out.add(new ProposedField(key, value.trim()));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Un ProposedField depuis une entrée brute, ou null si clé hors whitelist / valeur vide. */
|
||||||
|
private static ProposedField toProposedField(Map.Entry<?, ?> e, Set<String> allowed) {
|
||||||
|
String key = e.getKey() == null ? null : e.getKey().toString();
|
||||||
|
if (key == null || !allowed.contains(key)) {
|
||||||
|
return null; // whitelist stricte
|
||||||
|
}
|
||||||
|
String value = e.getValue() == null ? null : e.getValue().toString();
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return null; // pas de remplissage vide
|
||||||
|
}
|
||||||
|
return new ProposedField(key, value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<FieldSpec> nullSafe(List<FieldSpec> fields) {
|
||||||
|
return fields != null ? fields : List.of();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import java.time.Duration;
|
|||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adapter de sortie : relaie le chat ANCRÉ (RAG) du Brain via SSE (WebClient).
|
* Adapter de sortie : relaie le chat ANCRÉ (RAG) du Brain via SSE (WebClient).
|
||||||
@@ -26,23 +25,28 @@ import java.util.stream.Collectors;
|
|||||||
@Component
|
@Component
|
||||||
public class BrainNotebookChatClient implements NotebookChatStreamer {
|
public class BrainNotebookChatClient implements NotebookChatStreamer {
|
||||||
|
|
||||||
private static final String PATH = "/chat/notebook/stream";
|
|
||||||
private static final String DEEP_PATH = "/chat/notebook/deep/stream";
|
|
||||||
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
||||||
new ParameterizedTypeReference<>() {};
|
new ParameterizedTypeReference<>() {};
|
||||||
|
|
||||||
private final WebClient webClient;
|
private final WebClient webClient;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final long timeoutSeconds;
|
private final long timeoutSeconds;
|
||||||
|
// Routes du Brain surchargeables par config (défauts = contrat d'API actuel).
|
||||||
|
private final String chatPath;
|
||||||
|
private final String deepChatPath;
|
||||||
|
|
||||||
public BrainNotebookChatClient(
|
public BrainNotebookChatClient(
|
||||||
WebClient.Builder webClientBuilder,
|
WebClient.Builder webClientBuilder,
|
||||||
ObjectMapper objectMapper,
|
ObjectMapper objectMapper,
|
||||||
@Value("${brain.base-url}") String baseUrl,
|
@Value("${brain.base-url}") String baseUrl,
|
||||||
@Value("${brain.import-timeout-seconds:600}") long timeoutSeconds) {
|
@Value("${brain.import-timeout-seconds:600}") long timeoutSeconds,
|
||||||
|
@Value("${brain.paths.notebook-chat:/chat/notebook/stream}") String chatPath,
|
||||||
|
@Value("${brain.paths.notebook-chat-deep:/chat/notebook/deep/stream}") String deepChatPath) {
|
||||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||||
this.objectMapper = objectMapper;
|
this.objectMapper = objectMapper;
|
||||||
this.timeoutSeconds = timeoutSeconds;
|
this.timeoutSeconds = timeoutSeconds;
|
||||||
|
this.chatPath = chatPath;
|
||||||
|
this.deepChatPath = deepChatPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -57,11 +61,11 @@ public class BrainNotebookChatClient implements NotebookChatStreamer {
|
|||||||
payload.put("source_ids", sourceIds);
|
payload.put("source_ids", sourceIds);
|
||||||
payload.put("messages", messages.stream()
|
payload.put("messages", messages.stream()
|
||||||
.map(m -> Map.<String, Object>of("role", m.role(), "content", m.content()))
|
.map(m -> Map.<String, Object>of("role", m.role(), "content", m.content()))
|
||||||
.collect(Collectors.toList()));
|
.toList());
|
||||||
payload.put("context", context == null ? "" : context);
|
payload.put("context", context == null ? "" : context);
|
||||||
|
|
||||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||||
.uri(deep ? DEEP_PATH : PATH)
|
.uri(deep ? deepChatPath : chatPath)
|
||||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ public class BrainNotebookIndexClient implements NotebookIndexer {
|
|||||||
if (resp == null) {
|
if (resp == null) {
|
||||||
throw new NotebookException("Le Brain a renvoyé une réponse vide à l'indexation.");
|
throw new NotebookException("Le Brain a renvoyé une réponse vide à l'indexation.");
|
||||||
}
|
}
|
||||||
return new IndexResult(resp.chunks, resp.pageCount, resp.ocrPageCount);
|
return new IndexResult(resp.getChunks(), resp.getPageCount(), resp.getOcrPageCount());
|
||||||
} catch (ResourceAccessException e) {
|
} catch (ResourceAccessException e) {
|
||||||
throw new NotebookException("Le Brain est injoignable (timeout ou arrêté).", e);
|
throw new NotebookException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
} catch (RestClientResponseException e) {
|
} catch (RestClientResponseException e) {
|
||||||
@@ -89,12 +89,22 @@ public class BrainNotebookIndexClient implements NotebookIndexer {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Réponse JSON du Brain (snake_case). */
|
/**
|
||||||
|
* Réponse JSON du Brain (snake_case). Champs privés + @JsonProperty explicite
|
||||||
|
* sur CHAQUE champ : Jackson n'auto-détecte que les champs publics par défaut,
|
||||||
|
* l'annotation reste nécessaire pour que la désérialisation continue de fonctionner
|
||||||
|
* une fois les champs rendus privés.
|
||||||
|
*/
|
||||||
private static class IndexResponse {
|
private static class IndexResponse {
|
||||||
public int chunks;
|
@JsonProperty("chunks")
|
||||||
|
private int chunks;
|
||||||
@JsonProperty("page_count")
|
@JsonProperty("page_count")
|
||||||
public int pageCount;
|
private int pageCount;
|
||||||
@JsonProperty("ocr_page_count")
|
@JsonProperty("ocr_page_count")
|
||||||
public int ocrPageCount;
|
private int ocrPageCount;
|
||||||
|
|
||||||
|
int getChunks() { return chunks; }
|
||||||
|
int getPageCount() { return pageCount; }
|
||||||
|
int getOcrPageCount() { return ocrPageCount; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,23 +49,7 @@ public class BrainRandomTableClient implements RandomTableGenerator {
|
|||||||
if (resp == null) {
|
if (resp == null) {
|
||||||
throw new RandomTableGenerationException("Le Brain a renvoyé une réponse vide.");
|
throw new RandomTableGenerationException("Le Brain a renvoyé une réponse vide.");
|
||||||
}
|
}
|
||||||
List<RandomTableEntry> entries = new ArrayList<>();
|
List<RandomTableEntry> entries = parseEntries(resp.get("entries"));
|
||||||
Object rawEntries = resp.get("entries");
|
|
||||||
if (rawEntries instanceof List<?> list) {
|
|
||||||
for (Object item : list) {
|
|
||||||
if (!(item instanceof Map<?, ?> m)) continue;
|
|
||||||
Integer min = asInt(m.get("min_roll"));
|
|
||||||
Integer max = asInt(m.get("max_roll"));
|
|
||||||
String label = asString(m.get("label"));
|
|
||||||
if (min == null || max == null || label == null || label.isBlank()) continue;
|
|
||||||
entries.add(RandomTableEntry.builder()
|
|
||||||
.minRoll(min)
|
|
||||||
.maxRoll(Math.max(min, max))
|
|
||||||
.label(label)
|
|
||||||
.detail(asString(m.get("detail")))
|
|
||||||
.build());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (entries.isEmpty()) {
|
if (entries.isEmpty()) {
|
||||||
throw new RandomTableGenerationException("Aucune entrée générée — réessaie ou reformule.");
|
throw new RandomTableGenerationException("Aucune entrée générée — réessaie ou reformule.");
|
||||||
}
|
}
|
||||||
@@ -76,6 +60,39 @@ public class BrainRandomTableClient implements RandomTableGenerator {
|
|||||||
entries);
|
entries);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Entrées valides de la réponse (entrées malformées ou incomplètes ignorées). */
|
||||||
|
private static List<RandomTableEntry> parseEntries(Object rawEntries) {
|
||||||
|
List<RandomTableEntry> entries = new ArrayList<>();
|
||||||
|
if (rawEntries instanceof List<?> list) {
|
||||||
|
for (Object raw : list) {
|
||||||
|
RandomTableEntry entry = toEntry(raw);
|
||||||
|
if (entry != null) {
|
||||||
|
entries.add(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Une RandomTableEntry depuis une entrée brute, ou null si malformée / bornes ou label absents. */
|
||||||
|
private static RandomTableEntry toEntry(Object raw) {
|
||||||
|
if (!(raw instanceof Map<?, ?> m)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Integer min = asInt(m.get("min_roll"));
|
||||||
|
Integer max = asInt(m.get("max_roll"));
|
||||||
|
String label = asString(m.get("label"));
|
||||||
|
if (min == null || max == null || label == null || label.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return RandomTableEntry.builder()
|
||||||
|
.minRoll(min)
|
||||||
|
.maxRoll(Math.max(min, max))
|
||||||
|
.label(label)
|
||||||
|
.detail(asString(m.get("detail")))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String improvise(String tableName, String resultLabel, String resultDetail, String context) {
|
public String improvise(String tableName, String resultLabel, String resultDetail, String context) {
|
||||||
Map<String, Object> req = new LinkedHashMap<>();
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
|||||||
@@ -47,30 +47,45 @@ import java.util.function.Consumer;
|
|||||||
@Component
|
@Component
|
||||||
public class BrainRulesImportClient implements RulesPdfImporter {
|
public class BrainRulesImportClient implements RulesPdfImporter {
|
||||||
|
|
||||||
private static final String IMPORT_RULES_PATH = "/import/rules";
|
|
||||||
private static final String IMPORT_RULES_STREAM_PATH = "/import/rules/stream";
|
|
||||||
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
||||||
new ParameterizedTypeReference<>() {};
|
new ParameterizedTypeReference<>() {};
|
||||||
|
/** Nom de fichier par défaut du PDF de règles (filename absent/vide). */
|
||||||
|
private static final String DEFAULT_FILENAME = "rules.pdf";
|
||||||
|
|
||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
private final WebClient webClient;
|
private final WebClient webClient;
|
||||||
private final BrainSseImportSupport sse;
|
private final BrainSseImportSupport sse;
|
||||||
private final String baseUrl;
|
private final String baseUrl;
|
||||||
private final long importTimeoutSeconds;
|
private final long importTimeoutSeconds;
|
||||||
|
// Routes du Brain surchargeables par config (défauts = contrat d'API actuel).
|
||||||
|
private final String importRulesPath;
|
||||||
|
private final String importRulesStreamPath;
|
||||||
|
|
||||||
public BrainRulesImportClient(
|
public BrainRulesImportClient(
|
||||||
@Qualifier("brainImportRestTemplate") RestTemplate restTemplate,
|
@Qualifier("brainImportRestTemplate") RestTemplate restTemplate,
|
||||||
WebClient.Builder webClientBuilder,
|
WebClient.Builder webClientBuilder,
|
||||||
ObjectMapper objectMapper,
|
ObjectMapper objectMapper,
|
||||||
@Value("${brain.base-url}") String baseUrl,
|
@Value("${brain.base-url}") String baseUrl,
|
||||||
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds) {
|
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
|
||||||
|
@Value("${brain.paths.import-rules:/import/rules}") String importRulesPath,
|
||||||
|
@Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) {
|
||||||
this.restTemplate = restTemplate;
|
this.restTemplate = restTemplate;
|
||||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
|
||||||
this.sse = new BrainSseImportSupport(objectMapper);
|
this.sse = new BrainSseImportSupport(objectMapper);
|
||||||
this.baseUrl = baseUrl;
|
this.baseUrl = baseUrl;
|
||||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||||
|
this.importRulesPath = importRulesPath;
|
||||||
|
this.importRulesStreamPath = importRulesStreamPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Callbacks de streaming groupés (réduit le nombre de paramètres de handleEvent). */
|
||||||
|
private record ImportCallbacks(
|
||||||
|
Consumer<RulesImportProgress> onProgress,
|
||||||
|
Runnable onHeartbeat,
|
||||||
|
Consumer<String> onStatus,
|
||||||
|
Consumer<RulesImportResult> onDone,
|
||||||
|
Consumer<Throwable> onError) {}
|
||||||
|
|
||||||
// --- One-shot (bloquant) -------------------------------------------------
|
// --- One-shot (bloquant) -------------------------------------------------
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -79,19 +94,21 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||||
|
|
||||||
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
||||||
body.add("file", sse.filePart(pdfBytes, filename, "rules.pdf"));
|
body.add("file", sse.filePart(pdfBytes, filename, DEFAULT_FILENAME));
|
||||||
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
|
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
BrainRulesImportResponse response = restTemplate.postForObject(
|
BrainRulesImportResponse response = restTemplate.postForObject(
|
||||||
baseUrl + IMPORT_RULES_PATH, entity, BrainRulesImportResponse.class);
|
baseUrl + importRulesPath, entity, BrainRulesImportResponse.class);
|
||||||
if (response == null || response.getSections() == null) {
|
if (response == null || response.getSections() == null) {
|
||||||
throw new RulesImportException("Le Brain a renvoyé une réponse vide.");
|
throw new RulesImportException("Le Brain a renvoyé une réponse vide.");
|
||||||
}
|
}
|
||||||
return new RulesImportResult(
|
return new RulesImportResult(
|
||||||
Map.copyOf(response.getSections()),
|
Map.copyOf(response.getSections()),
|
||||||
response.getPageCount(),
|
response.getPageCount(),
|
||||||
response.getOcrPageCount());
|
response.getOcrPageCount(),
|
||||||
|
response.getSectionsByLanguage() != null ? response.getSectionsByLanguage() : Map.of(),
|
||||||
|
response.getSourceLanguage());
|
||||||
} catch (ResourceAccessException e) {
|
} catch (ResourceAccessException e) {
|
||||||
throw new RulesImportException(
|
throw new RulesImportException(
|
||||||
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
||||||
@@ -119,11 +136,11 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
Consumer<Throwable> onError) {
|
Consumer<Throwable> onError) {
|
||||||
|
|
||||||
MultipartBodyBuilder parts = new MultipartBodyBuilder();
|
MultipartBodyBuilder parts = new MultipartBodyBuilder();
|
||||||
parts.part("file", sse.filePart(pdfBytes, filename, "rules.pdf"))
|
parts.part("file", sse.filePart(pdfBytes, filename, DEFAULT_FILENAME))
|
||||||
.filename(filename == null || filename.isBlank() ? "rules.pdf" : filename);
|
.filename(filename == null || filename.isBlank() ? DEFAULT_FILENAME : filename);
|
||||||
|
|
||||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||||
.uri(IMPORT_RULES_STREAM_PATH)
|
.uri(importRulesStreamPath)
|
||||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||||
@@ -136,12 +153,11 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
int[] pageCount = {0};
|
int[] pageCount = {0};
|
||||||
int[] ocrPageCount = {0};
|
int[] ocrPageCount = {0};
|
||||||
boolean[] terminated = {false};
|
boolean[] terminated = {false};
|
||||||
|
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onError);
|
||||||
|
|
||||||
sse.runStream(
|
sse.runStream(
|
||||||
flux, importTimeoutSeconds, terminated,
|
flux, importTimeoutSeconds, terminated,
|
||||||
event -> handleEvent(
|
event -> handleEvent(event, pageCount, ocrPageCount, terminated, callbacks),
|
||||||
event, pageCount, ocrPageCount, terminated,
|
|
||||||
onProgress, onHeartbeat, onStatus, onDone, onError),
|
|
||||||
onError, RulesImportException::new);
|
onError, RulesImportException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,11 +166,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
int[] pageCount,
|
int[] pageCount,
|
||||||
int[] ocrPageCount,
|
int[] ocrPageCount,
|
||||||
boolean[] terminated,
|
boolean[] terminated,
|
||||||
Consumer<RulesImportProgress> onProgress,
|
ImportCallbacks callbacks) {
|
||||||
Runnable onHeartbeat,
|
|
||||||
Consumer<String> onStatus,
|
|
||||||
Consumer<RulesImportResult> onDone,
|
|
||||||
Consumer<Throwable> onError) {
|
|
||||||
|
|
||||||
String event = ssEvent.event();
|
String event = ssEvent.event();
|
||||||
String data = ssEvent.data() == null ? "" : ssEvent.data();
|
String data = ssEvent.data() == null ? "" : ssEvent.data();
|
||||||
@@ -163,28 +175,28 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
// Keep-alive du Brain pendant un appel LLM long : à PROPAGER jusqu'au
|
// Keep-alive du Brain pendant un appel LLM long : à PROPAGER jusqu'au
|
||||||
// navigateur, sinon nginx (proxy_read_timeout) coupe le SSE Core→front
|
// navigateur, sinon nginx (proxy_read_timeout) coupe le SSE Core→front
|
||||||
// resté silencieux pendant tout le traitement du morceau.
|
// resté silencieux pendant tout le traitement du morceau.
|
||||||
onHeartbeat.run();
|
callbacks.onHeartbeat().run();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("status".equals(event)) {
|
if ("status".equals(event)) {
|
||||||
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
||||||
// re-découpé…) : affiché par l'UI au lieu de n'exister qu'en logs.
|
// re-découpé…) : affiché par l'UI au lieu de n'exister qu'en logs.
|
||||||
onStatus.accept(sse.readMessage(data));
|
callbacks.onStatus().accept(sse.readMessage(data));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("chunk_failed".equals(event)) {
|
if ("chunk_failed".equals(event)) {
|
||||||
onStatus.accept(sse.chunkFailedStatus(data));
|
callbacks.onStatus().accept(sse.chunkFailedStatus(data));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("error".equals(event)) {
|
if ("error".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
onError.accept(new RulesImportException(
|
callbacks.onError().accept(new RulesImportException(
|
||||||
"Le Brain a signalé une erreur : " + sse.readMessage(data)));
|
"Le Brain a signalé une erreur : " + sse.readMessage(data)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if ("extracting".equals(event)) {
|
if ("extracting".equals(event)) {
|
||||||
// Phase d'extraction : total inconnu (0) → l'UI affiche "Extraction…".
|
// Phase d'extraction : total inconnu (0) → l'UI affiche "Extraction…".
|
||||||
onProgress.accept(new RulesImportProgress(0, 0, 0, 0, List.of()));
|
callbacks.onProgress().accept(new RulesImportProgress(0, 0, 0, 0, List.of()));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,10 +206,10 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
if ("start".equals(event)) {
|
if ("start".equals(event)) {
|
||||||
pageCount[0] = node.path("page_count").asInt();
|
pageCount[0] = node.path("page_count").asInt();
|
||||||
ocrPageCount[0] = node.path("ocr_page_count").asInt();
|
ocrPageCount[0] = node.path("ocr_page_count").asInt();
|
||||||
onProgress.accept(new RulesImportProgress(
|
callbacks.onProgress().accept(new RulesImportProgress(
|
||||||
0, node.path("total").asInt(), pageCount[0], ocrPageCount[0], List.of()));
|
0, node.path("total").asInt(), pageCount[0], ocrPageCount[0], List.of()));
|
||||||
} else if ("progress".equals(event)) {
|
} else if ("progress".equals(event)) {
|
||||||
onProgress.accept(new RulesImportProgress(
|
callbacks.onProgress().accept(new RulesImportProgress(
|
||||||
node.path("current").asInt(),
|
node.path("current").asInt(),
|
||||||
node.path("total").asInt(),
|
node.path("total").asInt(),
|
||||||
pageCount[0],
|
pageCount[0],
|
||||||
@@ -205,15 +217,26 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
toStringList(node.path("new_sections"))));
|
toStringList(node.path("new_sections"))));
|
||||||
} else if ("done".equals(event)) {
|
} else if ("done".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
onDone.accept(new RulesImportResult(
|
callbacks.onDone().accept(new RulesImportResult(
|
||||||
toStringMap(node.path("sections")),
|
toStringMap(node.path("sections")),
|
||||||
node.path("page_count").asInt(),
|
node.path("page_count").asInt(),
|
||||||
node.path("ocr_page_count").asInt()));
|
node.path("ocr_page_count").asInt(),
|
||||||
|
toLanguageMap(node.path("sections_by_language")),
|
||||||
|
node.path("source_language").asText(null)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Helpers -------------------------------------------------------------
|
// --- Helpers -------------------------------------------------------------
|
||||||
|
|
||||||
|
/** {code langue → sections} : règles en deux langues (vide si le Brain ne les fournit pas). */
|
||||||
|
private Map<String, Map<String, String>> toLanguageMap(JsonNode node) {
|
||||||
|
Map<String, Map<String, String>> out = new java.util.LinkedHashMap<>();
|
||||||
|
if (node != null && node.isObject()) {
|
||||||
|
node.fields().forEachRemaining(e -> out.put(e.getKey(), toStringMap(e.getValue())));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
private List<String> toStringList(JsonNode array) {
|
private List<String> toStringList(JsonNode array) {
|
||||||
List<String> out = new ArrayList<>();
|
List<String> out = new ArrayList<>();
|
||||||
if (array != null && array.isArray()) {
|
if (array != null && array.isArray()) {
|
||||||
|
|||||||
@@ -23,4 +23,11 @@ class BrainRulesImportResponse {
|
|||||||
|
|
||||||
@JsonProperty("ocr_page_count")
|
@JsonProperty("ocr_page_count")
|
||||||
private int ocrPageCount;
|
private int ocrPageCount;
|
||||||
|
|
||||||
|
/** Règles en deux langues : {code langue → sections} (absent d'un Brain antérieur). */
|
||||||
|
@JsonProperty("sections_by_language")
|
||||||
|
private Map<String, Map<String, String>> sectionsByLanguage;
|
||||||
|
|
||||||
|
@JsonProperty("source_language")
|
||||||
|
private String sourceLanguage;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,23 +62,38 @@ public class BrainSceneDraftClient implements SceneDraftAssistant {
|
|||||||
if (resp == null) {
|
if (resp == null) {
|
||||||
throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
|
throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
|
||||||
}
|
}
|
||||||
|
return parseScenes(resp.get("scenes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ébauches valides de la réponse (entrées malformées ou sans titre ignorées). */
|
||||||
|
private static List<SceneDraft> parseScenes(Object rawScenes) {
|
||||||
List<SceneDraft> out = new ArrayList<>();
|
List<SceneDraft> out = new ArrayList<>();
|
||||||
Object rawScenes = resp.get("scenes");
|
|
||||||
if (rawScenes instanceof List<?> list) {
|
if (rawScenes instanceof List<?> list) {
|
||||||
for (Object item : list) {
|
for (Object raw : list) {
|
||||||
if (!(item instanceof Map<?, ?> m)) continue;
|
SceneDraft draft = toSceneDraft(raw);
|
||||||
String name = asString(m.get("name"));
|
if (draft != null) {
|
||||||
if (name == null || name.isBlank()) continue; // un titre est obligatoire
|
out.add(draft);
|
||||||
out.add(new SceneDraft(
|
}
|
||||||
name.trim(),
|
|
||||||
trimOrNull(asString(m.get("description"))),
|
|
||||||
trimOrNull(asString(m.get("playerNarration")))));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Une SceneDraft depuis une entrée brute, ou null si malformée / sans titre. */
|
||||||
|
private static SceneDraft toSceneDraft(Object raw) {
|
||||||
|
if (!(raw instanceof Map<?, ?> m)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String name = asString(m.get("name"));
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
return null; // un titre est obligatoire
|
||||||
|
}
|
||||||
|
return new SceneDraft(
|
||||||
|
name.trim(),
|
||||||
|
trimOrNull(asString(m.get("description"))),
|
||||||
|
trimOrNull(asString(m.get("playerNarration"))));
|
||||||
|
}
|
||||||
|
|
||||||
private static String asString(Object o) {
|
private static String asString(Object o) {
|
||||||
return o != null ? o.toString() : null;
|
return o != null ? o.toString() : null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import org.springframework.stereotype.Component;
|
|||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
@@ -41,7 +42,7 @@ public class BrainSidecar {
|
|||||||
private final BrainSidecarProperties props;
|
private final BrainSidecarProperties props;
|
||||||
private final String internalSecret;
|
private final String internalSecret;
|
||||||
|
|
||||||
private volatile Process process;
|
private final AtomicReference<Process> process = new AtomicReference<>();
|
||||||
|
|
||||||
public BrainSidecar(BrainSidecarProperties props,
|
public BrainSidecar(BrainSidecarProperties props,
|
||||||
@Value("${brain.internal-secret:}") String internalSecret) {
|
@Value("${brain.internal-secret:}") String internalSecret) {
|
||||||
@@ -75,9 +76,10 @@ public class BrainSidecar {
|
|||||||
// (cf. Settings.internal_shared_secret cote Python -> env INTERNAL_SHARED_SECRET)
|
// (cf. Settings.internal_shared_secret cote Python -> env INTERNAL_SHARED_SECRET)
|
||||||
pb.environment().put("INTERNAL_SHARED_SECRET", internalSecret);
|
pb.environment().put("INTERNAL_SHARED_SECRET", internalSecret);
|
||||||
|
|
||||||
this.process = pb.start();
|
Process started = pb.start();
|
||||||
|
this.process.set(started);
|
||||||
log.info("[Brain] Sidecar demarre (pid={}, cwd={}).",
|
log.info("[Brain] Sidecar demarre (pid={}, cwd={}).",
|
||||||
process.pid(), workingDir != null ? workingDir : "<heritee>");
|
started.pid(), workingDir != null ? workingDir : "<heritee>");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
||||||
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
||||||
@@ -87,7 +89,7 @@ public class BrainSidecar {
|
|||||||
|
|
||||||
@PreDestroy
|
@PreDestroy
|
||||||
public void stop() {
|
public void stop() {
|
||||||
Process p = this.process;
|
Process p = this.process.get();
|
||||||
if (p == null || !p.isAlive()) {
|
if (p == null || !p.isAlive()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
|||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
import org.springframework.http.codec.ServerSentEvent;
|
import org.springframework.http.codec.ServerSentEvent;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
@@ -22,6 +23,24 @@ import java.util.function.Consumer;
|
|||||||
*/
|
*/
|
||||||
final class BrainSseImportSupport {
|
final class BrainSseImportSupport {
|
||||||
|
|
||||||
|
/** Champ JSON standard des events SSE du Brain portant un message lisible. */
|
||||||
|
private static final String MESSAGE_FIELD = "message";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Taille max d'UN évènement SSE. L'évènement {@code done} porte tout le résultat de
|
||||||
|
* l'import (règles d'un livre entier, en deux langues ; arbre complet d'une campagne) :
|
||||||
|
* la limite par défaut de WebClient (256 Ko) faisait échouer l'import au tout dernier
|
||||||
|
* moment (DataBufferLimitException), après des minutes d'analyse.
|
||||||
|
*/
|
||||||
|
static final int MAX_EVENT_BYTES = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
/** WebClient d'import : évènements volumineux acceptés (voir {@link #MAX_EVENT_BYTES}). */
|
||||||
|
static WebClient importWebClient(WebClient.Builder builder, String baseUrl) {
|
||||||
|
return builder.baseUrl(baseUrl)
|
||||||
|
.codecs(c -> c.defaultCodecs().maxInMemorySize(MAX_EVENT_BYTES))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
BrainSseImportSupport(ObjectMapper objectMapper) {
|
BrainSseImportSupport(ObjectMapper objectMapper) {
|
||||||
@@ -50,8 +69,8 @@ final class BrainSseImportSupport {
|
|||||||
/** Champ {@code message} du JSON, ou la {@code data} brute si non-JSON / champ absent. */
|
/** Champ {@code message} du JSON, ou la {@code data} brute si non-JSON / champ absent. */
|
||||||
String readMessage(String data) {
|
String readMessage(String data) {
|
||||||
JsonNode node = readJson(data);
|
JsonNode node = readJson(data);
|
||||||
if (node != null && node.hasNonNull("message")) {
|
if (node != null && node.hasNonNull(MESSAGE_FIELD)) {
|
||||||
return node.get("message").asText();
|
return node.get(MESSAGE_FIELD).asText();
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
@@ -59,8 +78,8 @@ final class BrainSseImportSupport {
|
|||||||
/** Statut lisible « Morceau x/y ignoré[ : message] » depuis un payload {@code chunk_failed}. */
|
/** Statut lisible « Morceau x/y ignoré[ : message] » depuis un payload {@code chunk_failed}. */
|
||||||
String chunkFailedStatus(String data) {
|
String chunkFailedStatus(String data) {
|
||||||
JsonNode node = readJson(data);
|
JsonNode node = readJson(data);
|
||||||
String msg = node != null && node.hasNonNull("message")
|
String msg = node != null && node.hasNonNull(MESSAGE_FIELD)
|
||||||
? node.get("message").asText() : "";
|
? node.get(MESSAGE_FIELD).asText() : "";
|
||||||
int current = node != null ? node.path("current").asInt() : 0;
|
int current = node != null ? node.path("current").asInt() : 0;
|
||||||
int total = node != null ? node.path("total").asInt() : 0;
|
int total = node != null ? node.path("total").asInt() : 0;
|
||||||
return "Morceau " + current + "/" + total + " ignoré"
|
return "Morceau " + current + "/" + total + " ignoré"
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ public class DesktopBrowserOpener {
|
|||||||
private static final Logger log = LoggerFactory.getLogger(DesktopBrowserOpener.class);
|
private static final Logger log = LoggerFactory.getLogger(DesktopBrowserOpener.class);
|
||||||
|
|
||||||
@EventListener(ApplicationReadyEvent.class)
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
// S125 : faux positif — commentaire explicatif (prose), pas de code mort.
|
||||||
|
@SuppressWarnings("java:S125")
|
||||||
public void onReady() {
|
public void onReady() {
|
||||||
// Ferme le splash natif (affiche par la JVM via -splash des le double-clic)
|
// Ferme le splash natif (affiche par la JVM via -splash des le double-clic)
|
||||||
// juste avant d'ouvrir le navigateur : le relais visuel est assure.
|
// juste avant d'ouvrir le navigateur : le relais visuel est assure.
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
package com.loremind.infrastructure.desktop;
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.awt.Desktop;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
import java.nio.channels.FileChannel;
|
import java.nio.channels.FileChannel;
|
||||||
import java.nio.channels.FileLock;
|
import java.nio.channels.FileLock;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
@@ -26,12 +31,26 @@ import java.nio.file.StandardOpenOption;
|
|||||||
* ({@code java.desktop}) pourrait etre absent du runtime reduit par jlink.
|
* ({@code java.desktop}) pourrait etre absent du runtime reduit par jlink.
|
||||||
* On passe donc par la commande systeme d'ouverture d'URL.
|
* On passe donc par la commande systeme d'ouverture d'URL.
|
||||||
*/
|
*/
|
||||||
|
// S4036 : app desktop locale mono-utilisateur — lancement d'utilitaires systeme via PATH
|
||||||
|
// assume, sans contexte d'elevation ni d'input externe.
|
||||||
|
@SuppressWarnings("java:S4036")
|
||||||
public final class DesktopSingleInstance {
|
public final class DesktopSingleInstance {
|
||||||
|
|
||||||
/** Conserve le verrou ouvert pour TOUTE la duree de vie du process (sinon GC = relache). */
|
// Utilisé avant SpringApplication.run() : Logback démarre en config console par
|
||||||
|
// défaut — même destination que l'ancien System.err (cf. DesktopUserConfig).
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DesktopSingleInstance.class);
|
||||||
|
|
||||||
|
private static final String OS_NAME_PROPERTY = "os.name";
|
||||||
|
/** Ouvre URL/fichier/dossier avec l'application par défaut sur Linux. */
|
||||||
|
private static final String XDG_OPEN = "xdg-open";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Conserve le CHANNEL ouvert pour toute la duree de vie du process : un FileLock
|
||||||
|
* reste detenu tant que son channel est ouvert (le verrou est libere a la fermeture
|
||||||
|
* du channel ou a la sortie de la JVM, pas au GC de l'objet FileLock).
|
||||||
|
*/
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
private static FileChannel lockChannel;
|
private static FileChannel lockChannel;
|
||||||
private static FileLock lock;
|
|
||||||
|
|
||||||
private DesktopSingleInstance() {}
|
private DesktopSingleInstance() {}
|
||||||
|
|
||||||
@@ -71,11 +90,11 @@ public final class DesktopSingleInstance {
|
|||||||
Path lockFile = dir.resolve(".instance.lock");
|
Path lockFile = dir.resolve(".instance.lock");
|
||||||
lockChannel = FileChannel.open(lockFile,
|
lockChannel = FileChannel.open(lockFile,
|
||||||
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||||
lock = lockChannel.tryLock();
|
FileLock lock = lockChannel.tryLock();
|
||||||
return lock != null; // null = deja verrouille par une autre instance
|
return lock != null; // null = deja verrouille par une autre instance
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("[Desktop] Verrou d'instance indisponible (" + e.getMessage()
|
log.warn("[Desktop] Verrou d'instance indisponible ({}) — on tente de demarrer quand meme.",
|
||||||
+ ") — on tente de demarrer quand meme.");
|
e.getMessage());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -85,23 +104,43 @@ public final class DesktopSingleInstance {
|
|||||||
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */
|
/**
|
||||||
|
* Ouvre le navigateur par defaut sur une URL quelconque : API standard de Java
|
||||||
|
* (ShellExecute sous Windows), sinon commande du systeme. Plus de {@code rundll32
|
||||||
|
* url.dll} : outil Windows tres detourne par les logiciels malveillants, que des
|
||||||
|
* antivirus signalaient (Avast « IDP.Generic ») quand un programme peu connu le lance.
|
||||||
|
*/
|
||||||
public static void openUrl(String url) {
|
public static void openUrl(String url) {
|
||||||
|
if (browseWithJava(url)) return;
|
||||||
try {
|
try {
|
||||||
String os = System.getProperty("os.name", "").toLowerCase();
|
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||||
ProcessBuilder pb;
|
ProcessBuilder pb;
|
||||||
if (os.contains("win")) {
|
if (os.contains("win")) {
|
||||||
// rundll32 : ouverture d'URL fiable sans dependance graphique Java.
|
// « start » de cmd ; le "" est le titre de fenetre attendu avant l'URL.
|
||||||
pb = new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", url);
|
pb = new ProcessBuilder("cmd", "/c", "start", "", url);
|
||||||
} else if (os.contains("mac")) {
|
} else if (os.contains("mac")) {
|
||||||
pb = new ProcessBuilder("open", url);
|
pb = new ProcessBuilder("open", url);
|
||||||
} else {
|
} else {
|
||||||
pb = new ProcessBuilder("xdg-open", url);
|
pb = new ProcessBuilder(XDG_OPEN, url);
|
||||||
}
|
}
|
||||||
pb.start();
|
pb.start();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("[Desktop] Impossible d'ouvrir le navigateur sur " + url
|
log.warn("[Desktop] Impossible d'ouvrir le navigateur sur {} : {}. Ouvrez-le manuellement.",
|
||||||
+ " : " + e.getMessage() + ". Ouvrez-le manuellement.");
|
url, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@link Desktop#browse} si disponible (jamais en headless) ; false = repli sur une commande. */
|
||||||
|
private static boolean browseWithJava(String url) {
|
||||||
|
try {
|
||||||
|
if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Desktop.getDesktop().browse(URI.create(url));
|
||||||
|
return true;
|
||||||
|
} catch (IOException | RuntimeException e) {
|
||||||
|
log.debug("[Desktop] Ouverture via Desktop.browse impossible ({}), repli sur une commande.", e.getMessage());
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,25 +148,25 @@ public final class DesktopSingleInstance {
|
|||||||
public static void openFolder(Path dir) {
|
public static void openFolder(Path dir) {
|
||||||
try {
|
try {
|
||||||
Files.createDirectories(dir);
|
Files.createDirectories(dir);
|
||||||
String os = System.getProperty("os.name", "").toLowerCase();
|
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||||
ProcessBuilder pb;
|
ProcessBuilder pb;
|
||||||
if (os.contains("win")) {
|
if (os.contains("win")) {
|
||||||
pb = new ProcessBuilder("explorer.exe", dir.toString());
|
pb = new ProcessBuilder("explorer.exe", dir.toString());
|
||||||
} else if (os.contains("mac")) {
|
} else if (os.contains("mac")) {
|
||||||
pb = new ProcessBuilder("open", dir.toString());
|
pb = new ProcessBuilder("open", dir.toString());
|
||||||
} else {
|
} else {
|
||||||
pb = new ProcessBuilder("xdg-open", dir.toString());
|
pb = new ProcessBuilder(XDG_OPEN, dir.toString());
|
||||||
}
|
}
|
||||||
pb.start();
|
pb.start();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("[Desktop] Ouverture du dossier impossible : " + e.getMessage());
|
log.warn("[Desktop] Ouverture du dossier impossible : {}", e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ouvre un fichier texte dans l'editeur par defaut (Bloc-notes sous Windows). */
|
/** Ouvre un fichier texte dans l'editeur par defaut (Bloc-notes sous Windows). */
|
||||||
public static void openInEditor(Path file) {
|
public static void openInEditor(Path file) {
|
||||||
try {
|
try {
|
||||||
String os = System.getProperty("os.name", "").toLowerCase();
|
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||||
ProcessBuilder pb;
|
ProcessBuilder pb;
|
||||||
if (os.contains("win")) {
|
if (os.contains("win")) {
|
||||||
// notepad : toujours present, ouvre proprement un .properties
|
// notepad : toujours present, ouvre proprement un .properties
|
||||||
@@ -136,11 +175,11 @@ public final class DesktopSingleInstance {
|
|||||||
} else if (os.contains("mac")) {
|
} else if (os.contains("mac")) {
|
||||||
pb = new ProcessBuilder("open", "-t", file.toString());
|
pb = new ProcessBuilder("open", "-t", file.toString());
|
||||||
} else {
|
} else {
|
||||||
pb = new ProcessBuilder("xdg-open", file.toString());
|
pb = new ProcessBuilder(XDG_OPEN, file.toString());
|
||||||
}
|
}
|
||||||
pb.start();
|
pb.start();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("[Desktop] Ouverture du fichier impossible : " + e.getMessage());
|
log.warn("[Desktop] Ouverture du fichier impossible : {}", e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ import java.util.Optional;
|
|||||||
* <p>
|
* <p>
|
||||||
* {@code /releases/latest} ne renvoie que les releases stables (pas les
|
* {@code /releases/latest} ne renvoie que les releases stables (pas les
|
||||||
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
|
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
|
||||||
|
* Une version BETA (le canal beta est libre : chaque beta est publiee en
|
||||||
|
* prerelease GitHub) interroge la liste complete des releases, pour etre
|
||||||
|
* prevenue de la beta suivante comme de la version stable qui la remplace.
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
@Profile("local")
|
@Profile("local")
|
||||||
@@ -73,17 +76,18 @@ public class DesktopUpdateService {
|
|||||||
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
|
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
|
||||||
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
|
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
|
||||||
|
|
||||||
|
boolean beta = isPrerelease(currentVersion);
|
||||||
ResponseEntity<JsonNode> resp = http.exchange(
|
ResponseEntity<JsonNode> resp = http.exchange(
|
||||||
releasesApiUrl, HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
beta ? allReleasesUrl(releasesApiUrl) : releasesApiUrl,
|
||||||
JsonNode body = resp.getBody();
|
HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
||||||
if (body == null || body.path("tag_name").isMissingNode()) {
|
JsonNode release = beta ? newestRelease(resp.getBody()) : resp.getBody();
|
||||||
|
if (release == null || release.path("tag_name").isMissingNode()) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
String tag = body.path("tag_name").asText(""); // ex: "v0.15.0"
|
String latest = version(release); // ex: "0.15.0"
|
||||||
String releaseUrl = body.path("html_url").asText(null); // page de la release
|
String releaseUrl = release.path("html_url").asText(null); // page de la release
|
||||||
String latest = tag.startsWith("v") ? tag.substring(1) : tag;
|
|
||||||
|
|
||||||
if (!latest.isBlank() && compareSemver(currentVersion, latest) < 0) {
|
if (!latest.isBlank() && (beta ? compareVersions(currentVersion, latest) : compareSemver(currentVersion, latest)) < 0) {
|
||||||
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
|
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
|
||||||
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
|
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
|
||||||
}
|
}
|
||||||
@@ -99,6 +103,66 @@ public class DesktopUpdateService {
|
|||||||
/** Infos d'une mise a jour disponible. */
|
/** Infos d'une mise a jour disponible. */
|
||||||
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
|
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
|
||||||
|
|
||||||
|
static boolean isPrerelease(String version) {
|
||||||
|
return version.split("\\+", 2)[0].contains("-");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code .../releases/latest} -> {@code .../releases?per_page=30} (prereleases incluses). */
|
||||||
|
static String allReleasesUrl(String latestUrl) {
|
||||||
|
String base = latestUrl.endsWith("/latest") ? latestUrl.substring(0, latestUrl.length() - "/latest".length()) : latestUrl;
|
||||||
|
return base + "?per_page=30";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String version(JsonNode release) {
|
||||||
|
String tag = release.path("tag_name").asText("");
|
||||||
|
return tag.startsWith("v") ? tag.substring(1) : tag;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release publiee la plus recente (stable ou beta), brouillons exclus. */
|
||||||
|
@Nullable
|
||||||
|
static JsonNode newestRelease(@Nullable JsonNode releases) {
|
||||||
|
if (releases == null || !releases.isArray()) return null;
|
||||||
|
JsonNode best = null;
|
||||||
|
for (JsonNode r : releases) {
|
||||||
|
if (r.path("draft").asBoolean(false) || version(r).isBlank()) continue;
|
||||||
|
if (best == null || compareVersions(version(best), version(r)) < 0) best = r;
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Comme {@link #compareSemver} mais tient compte du suffixe : a version egale,
|
||||||
|
* la stable passe devant la beta (1.5.0-beta < 1.5.0), et deux betas se
|
||||||
|
* comparent par leur numero (1.5.0-beta < 1.5.0-beta.2 < 1.5.0-beta.10).
|
||||||
|
*/
|
||||||
|
static int compareVersions(String a, String b) {
|
||||||
|
int cmp = compareSemver(a, b);
|
||||||
|
if (cmp != 0) return cmp;
|
||||||
|
String sa = suffix(a);
|
||||||
|
String sb = suffix(b);
|
||||||
|
if (sa.isEmpty() || sb.isEmpty()) return Boolean.compare(sa.isEmpty(), sb.isEmpty());
|
||||||
|
return compareSuffixes(sa, sb);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String suffix(String version) {
|
||||||
|
String noBuild = version.split("\\+", 2)[0];
|
||||||
|
int dash = noBuild.indexOf('-');
|
||||||
|
return dash < 0 ? "" : noBuild.substring(dash + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compare des suffixes en traitant les nombres comme des nombres (beta.10 > beta.2). */
|
||||||
|
private static int compareSuffixes(String a, String b) {
|
||||||
|
String[] pa = a.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
|
||||||
|
String[] pb = b.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
|
||||||
|
for (int i = 0; i < Math.min(pa.length, pb.length); i++) {
|
||||||
|
boolean na = Character.isDigit(pa[i].charAt(0));
|
||||||
|
boolean nb = Character.isDigit(pb[i].charAt(0));
|
||||||
|
int cmp = na && nb ? Long.compare(Long.parseLong(pa[i]), Long.parseLong(pb[i])) : pa[i].compareTo(pb[i]);
|
||||||
|
if (cmp != 0) return cmp;
|
||||||
|
}
|
||||||
|
return Integer.compare(pa.length, pb.length);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
|
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
|
||||||
* @return <0 si a<b, 0 si egales, >0 si a>b.
|
* @return <0 si a<b, 0 si egales, >0 si a>b.
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user