Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
@@ -82,9 +82,11 @@ jobs:
|
||||
if: failure()
|
||||
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
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: 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
|
||||
@@ -129,3 +129,5 @@ web/coverage/
|
||||
brain/htmlcov/
|
||||
brain/.coverage
|
||||
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
-1
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
||||
app = FastAPI(
|
||||
title="LoreMind Brain",
|
||||
description="Backend IA pour la génération de contenu narratif.",
|
||||
version="1.0.1-beta",
|
||||
version="1.5.0-beta",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
+14
-1
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>1.0.1-beta</version>
|
||||
<version>1.5.0-beta</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
@@ -24,6 +24,19 @@
|
||||
>= 3.18 : corrige CVE-2025-48924 (recursion infinie ClassUtils.getClass).
|
||||
Propriete reconnue par le BOM Spring Boot → s'applique partout. -->
|
||||
<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>
|
||||
|
||||
<dependencies>
|
||||
|
||||
+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.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
@@ -108,6 +109,23 @@ public class CampaignService {
|
||||
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) {
|
||||
return (id == null || id.isBlank()) ? null : id;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||
import com.loremind.domain.shared.ReorderSupport;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -29,8 +30,17 @@ public class NpcService {
|
||||
String campaignId,
|
||||
List<String> relatedPageIds,
|
||||
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) {
|
||||
int order = data.order() != null
|
||||
@@ -47,6 +57,7 @@ public class NpcService {
|
||||
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
|
||||
.folder(normalizeFolder(data.folder()))
|
||||
.order(order)
|
||||
.story(cleanStory(data.story()))
|
||||
.build();
|
||||
return npcRepository.save(npc);
|
||||
}
|
||||
@@ -70,12 +81,22 @@ public class NpcService {
|
||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
|
||||
existing.setFolder(normalizeFolder(data.folder()));
|
||||
if (data.story() != null) {
|
||||
existing.setStory(cleanStory(data.story()));
|
||||
}
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
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) {
|
||||
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) ? */
|
||||
private boolean isContainerOf(Quest quest, Chapter chapter) {
|
||||
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())
|
||||
.map(a -> a.getType() == ArcType.SYSTEM)
|
||||
.orElse(false);
|
||||
@@ -156,6 +161,18 @@ public class QuestService {
|
||||
/**
|
||||
* 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}
|
||||
* 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
|
||||
@@ -167,28 +184,47 @@ public class QuestService {
|
||||
progressionRepository.deleteByQuestId(id);
|
||||
questRepository.deleteById(id);
|
||||
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());
|
||||
for (QuestNodeRef node : nullSafeNodes(quest.getNodes())) {
|
||||
if (node.nodeType() != NodeType.CHAPTER) continue;
|
||||
chapterRepository.findById(node.nodeId()).ifPresent(ch -> {
|
||||
boolean container = isContainerOf(quest, ch);
|
||||
boolean empty = sceneRepository.findByChapterId(ch.getId()).isEmpty();
|
||||
boolean referencedElsewhere = remaining.stream()
|
||||
.anyMatch(q -> nullSafeNodes(q.getNodes()).stream()
|
||||
.anyMatch(n -> n.nodeType() == NodeType.CHAPTER
|
||||
&& ch.getId().equals(n.nodeId())));
|
||||
if (container && empty && !referencedElsewhere) {
|
||||
chapterRepository.deleteById(ch.getId());
|
||||
}
|
||||
if (!container || referencedElsewhere) return;
|
||||
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) {
|
||||
return nodes != null ? nodes : List.of();
|
||||
}
|
||||
|
||||
@@ -125,6 +125,8 @@ public class SceneService {
|
||||
case "playerNarration" -> scene.setPlayerNarration(value);
|
||||
case "choicesConsequences" -> scene.setChoicesConsequences(value);
|
||||
case "combatDifficulty" -> scene.setCombatDifficulty(value);
|
||||
case "tactics" -> scene.setTactics(value);
|
||||
case "purpose" -> scene.setPurpose(value);
|
||||
case "enemies" -> scene.setEnemies(value);
|
||||
case "gmSecretNotes" -> scene.setGmSecretNotes(value);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,11 @@ public class SessionService {
|
||||
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) {
|
||||
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;
|
||||
|
||||
/** Fiche « Publication » (couverture, page technique, crédits…). Null = jamais renseignée. */
|
||||
private CampaignPublication publication;
|
||||
|
||||
public boolean isLinkedToLore() {
|
||||
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. */
|
||||
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 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) {
|
||||
|
||||
/**
|
||||
* {@code existingId} (nullable) : 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).
|
||||
* <p>
|
||||
* {@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(
|
||||
String name, String description, String type,
|
||||
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);
|
||||
}
|
||||
@@ -2,11 +2,9 @@ package com.loremind.domain.campaigncontext.quest;
|
||||
|
||||
/**
|
||||
* 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
|
||||
* un nouveau type (ex : NpcMet), il faudra l'ajouter ici ET dans
|
||||
* {@link PrerequisiteEvaluator}.
|
||||
*
|
||||
* Sémantique MVP : une quête a une LISTE de prérequis, tous combinés en ET logique
|
||||
* (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
|
||||
* et en dérive le {@link QuestStatus} effectif.
|
||||
*
|
||||
* 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é
|
||||
* 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,
|
||||
EvaluationContext ctx
|
||||
) {
|
||||
switch (progression) {
|
||||
case COMPLETED: return QuestStatus.COMPLETED;
|
||||
case IN_PROGRESS: return QuestStatus.IN_PROGRESS;
|
||||
case NOT_STARTED:
|
||||
return areAllSatisfied(prerequisites, ctx)
|
||||
? QuestStatus.AVAILABLE
|
||||
: QuestStatus.LOCKED;
|
||||
default:
|
||||
throw new IllegalStateException("ProgressionStatus non géré : " + progression);
|
||||
}
|
||||
return switch (progression) {
|
||||
case COMPLETED -> QuestStatus.COMPLETED;
|
||||
case IN_PROGRESS -> QuestStatus.IN_PROGRESS;
|
||||
case NOT_STARTED -> areAllSatisfied(prerequisites, ctx)
|
||||
? QuestStatus.AVAILABLE
|
||||
: QuestStatus.LOCKED;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* NOT_STARTED : pas encore commencée. Peut être visible (AVAILABLE) ou cachée (LOCKED)
|
||||
* selon les prérequis — voir {@link QuestStatus}.
|
||||
* IN_PROGRESS : démarrée par le MJ via le bouton "Démarrer cette quête".
|
||||
* COMPLETED : marquée terminée par le MJ.
|
||||
*
|
||||
* NB : un Chapter d'Arc LINEAR conserve NOT_STARTED par défaut sans impact visible.
|
||||
*/
|
||||
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.
|
||||
* DÉRIVÉ — jamais persisté. Calculé par {@link PrerequisiteEvaluator} à partir
|
||||
* de la {@link ProgressionStatus} persistée et de l'évaluation des prérequis.
|
||||
*
|
||||
* Table de vérité :
|
||||
* NOT_STARTED + prérequis non remplis -> LOCKED
|
||||
* 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 rewards; // Récompenses et progression
|
||||
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).
|
||||
|
||||
@@ -48,6 +48,8 @@ public class Scene {
|
||||
|
||||
// === Combat ou rencontre ===
|
||||
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)
|
||||
|
||||
/**
|
||||
|
||||
+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
|
||||
}
|
||||
@@ -158,7 +158,7 @@ public class GameSystem {
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,9 @@ public interface SessionRepository {
|
||||
/** Retourne UNE session active dans l'app (sémantique « legacy » — multi-actives possibles). */
|
||||
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. */
|
||||
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);
|
||||
}
|
||||
@@ -26,22 +26,25 @@ import java.util.function.Consumer;
|
||||
@Component
|
||||
public class BrainCampaignAdaptClient implements CampaignPdfAdvisor {
|
||||
|
||||
private static final String ADAPT_PATH = "/adapt/campaign/stream";
|
||||
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
||||
new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final WebClient webClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final long timeoutSeconds;
|
||||
// Route du Brain surchargeable par config (défaut = contrat d'API actuel).
|
||||
private final String adaptPath;
|
||||
|
||||
public BrainCampaignAdaptClient(
|
||||
WebClient.Builder webClientBuilder,
|
||||
ObjectMapper objectMapper,
|
||||
@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.objectMapper = objectMapper;
|
||||
this.timeoutSeconds = timeoutSeconds;
|
||||
this.adaptPath = adaptPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -65,7 +68,7 @@ public class BrainCampaignAdaptClient implements CampaignPdfAdvisor {
|
||||
parts.part("messages", (messagesJson == null || messagesJson.isBlank()) ? "[]" : messagesJson);
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(ADAPT_PATH)
|
||||
.uri(adaptPath)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
|
||||
@@ -36,24 +36,37 @@ import java.util.function.Consumer;
|
||||
@Component
|
||||
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 =
|
||||
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 BrainSseImportSupport sse;
|
||||
private final long importTimeoutSeconds;
|
||||
// Route du Brain surchargeable par config (défaut = contrat d'API actuel).
|
||||
private final String importCampaignStreamPath;
|
||||
|
||||
public BrainCampaignImportClient(
|
||||
WebClient.Builder webClientBuilder,
|
||||
ObjectMapper objectMapper,
|
||||
@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-campaign:/import/campaign/stream}") String importCampaignStreamPath) {
|
||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||
this.sse = new BrainSseImportSupport(objectMapper);
|
||||
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
|
||||
public void importCampaignStreaming(
|
||||
byte[] pdfBytes,
|
||||
@@ -69,7 +82,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
.filename(filename == null || filename.isBlank() ? "campaign.pdf" : filename);
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(IMPORT_CAMPAIGN_STREAM_PATH)
|
||||
.uri(importCampaignStreamPath)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
@@ -80,12 +93,11 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
int[] pageCount = {0};
|
||||
int[] ocrPageCount = {0};
|
||||
boolean[] terminated = {false};
|
||||
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onError);
|
||||
|
||||
sse.runStream(
|
||||
flux, importTimeoutSeconds, terminated,
|
||||
event -> handleEvent(
|
||||
event, pageCount, ocrPageCount, terminated,
|
||||
onProgress, onHeartbeat, onStatus, onDone, onError),
|
||||
event -> handleEvent(event, pageCount, ocrPageCount, terminated, callbacks),
|
||||
onError, CampaignImportException::new);
|
||||
}
|
||||
|
||||
@@ -94,11 +106,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
int[] pageCount,
|
||||
int[] ocrPageCount,
|
||||
boolean[] terminated,
|
||||
Consumer<CampaignImportProgress> onProgress,
|
||||
Runnable onHeartbeat,
|
||||
Consumer<String> onStatus,
|
||||
Consumer<CampaignImportProposal> onDone,
|
||||
Consumer<Throwable> onError) {
|
||||
ImportCallbacks callbacks) {
|
||||
|
||||
String event = ssEvent.event();
|
||||
String data = ssEvent.data() == null ? "" : ssEvent.data();
|
||||
@@ -106,27 +114,27 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
if ("heartbeat".equals(event)) {
|
||||
// Keep-alive du Brain pendant un appel LLM long : à PROPAGER jusqu'au
|
||||
// navigateur, sinon nginx (proxy_read_timeout) coupe le SSE Core→front.
|
||||
onHeartbeat.run();
|
||||
callbacks.onHeartbeat().run();
|
||||
return;
|
||||
}
|
||||
if ("status".equals(event)) {
|
||||
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
||||
// 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;
|
||||
}
|
||||
if ("chunk_failed".equals(event)) {
|
||||
onStatus.accept(sse.chunkFailedStatus(data));
|
||||
callbacks.onStatus().accept(sse.chunkFailedStatus(data));
|
||||
return;
|
||||
}
|
||||
if ("error".equals(event)) {
|
||||
terminated[0] = true;
|
||||
onError.accept(new CampaignImportException(
|
||||
callbacks.onError().accept(new CampaignImportException(
|
||||
"Le Brain a signalé une erreur : " + sse.readMessage(data)));
|
||||
return;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -136,10 +144,10 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
if ("start".equals(event)) {
|
||||
pageCount[0] = node.path("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));
|
||||
} else if ("progress".equals(event)) {
|
||||
onProgress.accept(new CampaignImportProgress(
|
||||
callbacks.onProgress().accept(new CampaignImportProgress(
|
||||
node.path("current").asInt(),
|
||||
node.path("total").asInt(),
|
||||
pageCount[0],
|
||||
@@ -150,7 +158,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
node.path("npc_count").asInt()));
|
||||
} else if ("done".equals(event)) {
|
||||
terminated[0] = true;
|
||||
onDone.accept(new CampaignImportProposal(
|
||||
callbacks.onDone().accept(new CampaignImportProposal(
|
||||
toArcs(node.path("arcs")), toNpcs(node.path("npcs"))));
|
||||
}
|
||||
}
|
||||
@@ -163,7 +171,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
for (JsonNode arc : arcsNode) {
|
||||
arcs.add(new ArcProposal(
|
||||
text(arc, "name"),
|
||||
text(arc, "description"),
|
||||
text(arc, FIELD_DESCRIPTION),
|
||||
text(arc, "type"),
|
||||
toChapters(arc.path("chapters")),
|
||||
null));
|
||||
@@ -178,7 +186,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
for (JsonNode ch : chaptersNode) {
|
||||
chapters.add(new ChapterProposal(
|
||||
text(ch, "name"),
|
||||
text(ch, "description"),
|
||||
text(ch, FIELD_DESCRIPTION),
|
||||
toScenes(ch.path("scenes")),
|
||||
null));
|
||||
}
|
||||
@@ -191,7 +199,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
if (scenesNode != null && scenesNode.isArray()) {
|
||||
for (JsonNode sc : scenesNode) {
|
||||
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"),
|
||||
toRooms(sc.path("rooms")), null));
|
||||
}
|
||||
@@ -204,7 +212,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
if (roomsNode != null && roomsNode.isArray()) {
|
||||
for (JsonNode rm : roomsNode) {
|
||||
rooms.add(new RoomProposal(
|
||||
text(rm, "name"), text(rm, "description"),
|
||||
text(rm, "name"), text(rm, FIELD_DESCRIPTION),
|
||||
text(rm, "enemies"), text(rm, "loot")));
|
||||
}
|
||||
}
|
||||
@@ -215,7 +223,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
List<NpcProposal> npcs = new ArrayList<>();
|
||||
if (npcsNode != null && npcsNode.isArray()) {
|
||||
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;
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
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
|
||||
@@ -40,11 +40,14 @@ import java.util.stream.Collectors;
|
||||
@Component
|
||||
public class BrainChatPayloadBuilder {
|
||||
|
||||
private static final String KEY_DESCRIPTION = "description";
|
||||
private static final String KEY_TITLE = "title";
|
||||
|
||||
public Map<String, Object> build(ChatRequest request) {
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
root.put("messages", request.messages().stream()
|
||||
.map(this::messageToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
|
||||
if (request.loreContext() != null) {
|
||||
root.put("lore_context", loreContextToMap(request.loreContext()));
|
||||
@@ -75,25 +78,25 @@ public class BrainChatPayloadBuilder {
|
||||
map.put("started_at", sc.startedAt().toString());
|
||||
}
|
||||
map.put("entries", sc.entries() != null
|
||||
? sc.entries().stream().map(this::journalEntryToMap).collect(Collectors.toList())
|
||||
? sc.entries().stream().map(this::journalEntryToMap).toList()
|
||||
: List.of());
|
||||
// Évènements des sessions précédentes : omis si vide (campagne sur sa 1re session).
|
||||
if (sc.previousEvents() != null && !sc.previousEvents().isEmpty()) {
|
||||
map.put("previous_events", sc.previousEvents().stream()
|
||||
.map(this::journalEntryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
// État Hub (quêtes / flags). Toutes les listes sont omises si vides pour ne pas
|
||||
// saturer le prompt sur les campagnes sans Hub.
|
||||
if (sc.availableQuests() != null && !sc.availableQuests().isEmpty()) {
|
||||
map.put("available_quests", sc.availableQuests().stream()
|
||||
.map(this::questSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
if (sc.inProgressQuests() != null && !sc.inProgressQuests().isEmpty()) {
|
||||
map.put("in_progress_quests", sc.inProgressQuests().stream()
|
||||
.map(this::questSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
if (sc.lockedQuestTitles() != null && !sc.lockedQuestTitles().isEmpty()) {
|
||||
map.put("locked_quest_titles", sc.lockedQuestTitles());
|
||||
@@ -108,7 +111,7 @@ public class BrainChatPayloadBuilder {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("name", q.name());
|
||||
map.put("arc_name", q.arcName());
|
||||
putIfText(map, "description", q.description());
|
||||
putIfText(map, KEY_DESCRIPTION, q.description());
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -147,7 +150,7 @@ public class BrainChatPayloadBuilder {
|
||||
for (Map.Entry<String, List<PageSummary>> e : ctx.folders().entrySet()) {
|
||||
foldersMap.put(e.getKey(), e.getValue().stream()
|
||||
.map(this::pageSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
map.put("folders", foldersMap);
|
||||
map.put("tags", ctx.tags());
|
||||
@@ -156,7 +159,7 @@ public class BrainChatPayloadBuilder {
|
||||
|
||||
private Map<String, Object> pageSummaryToMap(PageSummary ps) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("title", ps.title());
|
||||
map.put(KEY_TITLE, ps.title());
|
||||
map.put("template_name", ps.templateName());
|
||||
// values/tags/related_page_titles : omis si vides pour alléger le payload.
|
||||
if (ps.values() != null && !ps.values().isEmpty()) {
|
||||
@@ -173,7 +176,7 @@ public class BrainChatPayloadBuilder {
|
||||
|
||||
private Map<String, Object> pageContextToMap(PageContext pc) {
|
||||
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_fields", pc.templateFields());
|
||||
map.put("values", pc.values());
|
||||
@@ -186,18 +189,18 @@ public class BrainChatPayloadBuilder {
|
||||
map.put("campaign_description", ctx.campaignDescription());
|
||||
map.put("arcs", ctx.arcs().stream()
|
||||
.map(this::arcSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
// Liste des PJ : omise si aucun pour alléger le prompt des campagnes sans fiches.
|
||||
if (ctx.characters() != null && !ctx.characters().isEmpty()) {
|
||||
map.put("characters", ctx.characters().stream()
|
||||
.map(this::characterSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
// Liste des PNJ : symétrique aux PJ, omise si vide pour alléger le payload.
|
||||
if (ctx.npcs() != null && !ctx.npcs().isEmpty()) {
|
||||
map.put("npcs", ctx.npcs().stream()
|
||||
.map(this::npcSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -224,13 +227,14 @@ public class BrainChatPayloadBuilder {
|
||||
T entity,
|
||||
Function<T, String> nameExtractor,
|
||||
Function<T, String> descriptionExtractor,
|
||||
Function<T, Integer> illustrationCountExtractor,
|
||||
ToIntFunction<T> illustrationCountExtractor,
|
||||
BiConsumer<Map<String, Object>, T> childSerializer) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("name", nameExtractor.apply(entity));
|
||||
map.put("description", descriptionExtractor.apply(entity));
|
||||
if (illustrationCountExtractor.apply(entity) > 0) {
|
||||
map.put("illustration_count", illustrationCountExtractor.apply(entity));
|
||||
map.put(KEY_DESCRIPTION, descriptionExtractor.apply(entity));
|
||||
int illustrationCount = illustrationCountExtractor.applyAsInt(entity);
|
||||
if (illustrationCount > 0) {
|
||||
map.put("illustration_count", illustrationCount);
|
||||
}
|
||||
childSerializer.accept(map, entity);
|
||||
return map;
|
||||
@@ -249,7 +253,7 @@ public class BrainChatPayloadBuilder {
|
||||
}
|
||||
map.put("chapters", arc.chapters().stream()
|
||||
.map(this::chapterSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -261,7 +265,7 @@ public class BrainChatPayloadBuilder {
|
||||
ChapterSummary::illustrationCount,
|
||||
(map, chapter) -> map.put("scenes", chapter.scenes().stream()
|
||||
.map(this::sceneSummaryToMap)
|
||||
.collect(Collectors.toList())));
|
||||
.toList()));
|
||||
}
|
||||
|
||||
private Map<String, Object> sceneSummaryToMap(SceneSummary s) {
|
||||
@@ -275,13 +279,13 @@ public class BrainChatPayloadBuilder {
|
||||
if (s.branches() != null && !s.branches().isEmpty()) {
|
||||
map.put("branches", s.branches().stream()
|
||||
.map(this::branchHintToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
// Pièces du lieu explorable : omises si scène classique.
|
||||
if (s.rooms() != null && !s.rooms().isEmpty()) {
|
||||
map.put("rooms", s.rooms().stream()
|
||||
.map(this::roomSummaryToMap)
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -298,7 +302,7 @@ public class BrainChatPayloadBuilder {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("name", r.name());
|
||||
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());
|
||||
if (r.branches() != null && !r.branches().isEmpty()) {
|
||||
map.put("branches", r.branches().stream().map(b -> {
|
||||
@@ -307,7 +311,7 @@ public class BrainChatPayloadBuilder {
|
||||
bm.put("target_room_name", b.targetRoomName());
|
||||
putIfText(bm, "condition", b.condition());
|
||||
return bm;
|
||||
}).collect(Collectors.toList()));
|
||||
}).toList());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -315,7 +319,7 @@ public class BrainChatPayloadBuilder {
|
||||
private Map<String, Object> narrativeEntityToMap(NarrativeEntityContext ne) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("entity_type", ne.entityType());
|
||||
map.put("title", ne.title());
|
||||
map.put(KEY_TITLE, ne.title());
|
||||
map.put("fields", ne.fields());
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Adaptateur : appelle le Brain POST /summarize/conversation-title pour
|
||||
@@ -45,7 +44,7 @@ public class BrainConversationTitleClient implements ConversationTitleGenerator
|
||||
.map(m -> Map.<String, Object>of(
|
||||
"role", m.getRole(),
|
||||
"content", m.getContent() == null ? "" : m.getContent()))
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
@@ -24,6 +24,7 @@ import java.util.Map;
|
||||
public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
||||
|
||||
private static final String GENERATE_PATH = "/generate/item-catalog";
|
||||
private static final String KEY_DESCRIPTION = "description";
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
private final String baseUrl;
|
||||
@@ -36,10 +37,25 @@ public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
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<>();
|
||||
req.put("description", description == null ? "" : description);
|
||||
req.put(KEY_DESCRIPTION, description == null ? "" : description);
|
||||
req.put("context", context == null ? "" : context);
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
@@ -60,30 +76,38 @@ public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
||||
if (resp == null) {
|
||||
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<>();
|
||||
Object rawItems = resp.get("items");
|
||||
if (rawItems instanceof List<?> list) {
|
||||
for (Object item : list) {
|
||||
if (!(item instanceof Map<?, ?> m)) continue;
|
||||
String name = asString(m.get("name"));
|
||||
if (name == null || name.isBlank()) continue;
|
||||
items.add(CatalogItem.builder()
|
||||
.name(name)
|
||||
.price(asString(m.get("price")))
|
||||
.category(asString(m.get("category")))
|
||||
.description(asString(m.get("description")))
|
||||
.build());
|
||||
for (Object raw : list) {
|
||||
CatalogItem item = toItem(raw);
|
||||
if (item != null) {
|
||||
items.add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (items.isEmpty()) {
|
||||
throw new ItemCatalogGenerationException("Aucun objet généré — réessaie ou reformule.");
|
||||
return items;
|
||||
}
|
||||
|
||||
/** 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"));
|
||||
return new GeneratedCatalog(
|
||||
name != null && !name.isBlank() ? name : description,
|
||||
asString(resp.get("description")),
|
||||
items);
|
||||
String name = asString(m.get("name"));
|
||||
if (name == null || name.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
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) {
|
||||
|
||||
@@ -39,20 +39,9 @@ public class BrainNarrativeFieldClient implements NarrativeFieldAssistant {
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<ProposedField> assist(String entityType, String context, String instruction, List<FieldSpec> fields) {
|
||||
List<Map<String, String>> fieldPayload = new ArrayList<>();
|
||||
Set<String> allowed = new HashSet<>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
List<Map<String, String>> fieldPayload = buildFieldPayload(fields);
|
||||
Set<String> allowed = allowedKeys(fields);
|
||||
|
||||
Map<String, Object> req = new LinkedHashMap<>();
|
||||
req.put("entity_type", entityType == null ? "" : entityType);
|
||||
@@ -60,6 +49,38 @@ public class BrainNarrativeFieldClient implements NarrativeFieldAssistant {
|
||||
req.put("instruction", instruction == null ? "" : instruction);
|
||||
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();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(req, headers);
|
||||
@@ -78,18 +99,37 @@ public class BrainNarrativeFieldClient implements NarrativeFieldAssistant {
|
||||
if (resp == null) {
|
||||
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<>();
|
||||
Object rawFields = resp.get("fields");
|
||||
if (rawFields instanceof Map<?, ?> m) {
|
||||
for (Map.Entry<?, ?> e : m.entrySet()) {
|
||||
String key = e.getKey() == null ? null : e.getKey().toString();
|
||||
if (key == null || !allowed.contains(key)) continue; // whitelist stricte
|
||||
String value = e.getValue() == null ? null : e.getValue().toString();
|
||||
if (value == null || value.isBlank()) continue; // pas de remplissage vide
|
||||
out.add(new ProposedField(key, value.trim()));
|
||||
ProposedField field = toProposedField(e, allowed);
|
||||
if (field != null) {
|
||||
out.add(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Adapter de sortie : relaie le chat ANCRÉ (RAG) du Brain via SSE (WebClient).
|
||||
@@ -26,23 +25,28 @@ import java.util.stream.Collectors;
|
||||
@Component
|
||||
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 =
|
||||
new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final WebClient webClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
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(
|
||||
WebClient.Builder webClientBuilder,
|
||||
ObjectMapper objectMapper,
|
||||
@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.objectMapper = objectMapper;
|
||||
this.timeoutSeconds = timeoutSeconds;
|
||||
this.chatPath = chatPath;
|
||||
this.deepChatPath = deepChatPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -57,11 +61,11 @@ public class BrainNotebookChatClient implements NotebookChatStreamer {
|
||||
payload.put("source_ids", sourceIds);
|
||||
payload.put("messages", messages.stream()
|
||||
.map(m -> Map.<String, Object>of("role", m.role(), "content", m.content()))
|
||||
.collect(Collectors.toList()));
|
||||
.toList());
|
||||
payload.put("context", context == null ? "" : context);
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(deep ? DEEP_PATH : PATH)
|
||||
.uri(deep ? deepChatPath : chatPath)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
|
||||
@@ -55,7 +55,7 @@ public class BrainNotebookIndexClient implements NotebookIndexer {
|
||||
if (resp == null) {
|
||||
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) {
|
||||
throw new NotebookException("Le Brain est injoignable (timeout ou arrêté).", 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 {
|
||||
public int chunks;
|
||||
@JsonProperty("chunks")
|
||||
private int chunks;
|
||||
@JsonProperty("page_count")
|
||||
public int pageCount;
|
||||
private int pageCount;
|
||||
@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) {
|
||||
throw new RandomTableGenerationException("Le Brain a renvoyé une réponse vide.");
|
||||
}
|
||||
List<RandomTableEntry> entries = new ArrayList<>();
|
||||
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());
|
||||
}
|
||||
}
|
||||
List<RandomTableEntry> entries = parseEntries(resp.get("entries"));
|
||||
if (entries.isEmpty()) {
|
||||
throw new RandomTableGenerationException("Aucune entrée générée — réessaie ou reformule.");
|
||||
}
|
||||
@@ -76,6 +60,39 @@ public class BrainRandomTableClient implements RandomTableGenerator {
|
||||
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
|
||||
public String improvise(String tableName, String resultLabel, String resultDetail, String context) {
|
||||
Map<String, Object> req = new LinkedHashMap<>();
|
||||
|
||||
@@ -47,30 +47,45 @@ import java.util.function.Consumer;
|
||||
@Component
|
||||
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 =
|
||||
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 WebClient webClient;
|
||||
private final BrainSseImportSupport sse;
|
||||
private final String baseUrl;
|
||||
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(
|
||||
@Qualifier("brainImportRestTemplate") RestTemplate restTemplate,
|
||||
WebClient.Builder webClientBuilder,
|
||||
ObjectMapper objectMapper,
|
||||
@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.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||
this.sse = new BrainSseImportSupport(objectMapper);
|
||||
this.baseUrl = baseUrl;
|
||||
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) -------------------------------------------------
|
||||
|
||||
@Override
|
||||
@@ -79,12 +94,12 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||
|
||||
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);
|
||||
|
||||
try {
|
||||
BrainRulesImportResponse response = restTemplate.postForObject(
|
||||
baseUrl + IMPORT_RULES_PATH, entity, BrainRulesImportResponse.class);
|
||||
baseUrl + importRulesPath, entity, BrainRulesImportResponse.class);
|
||||
if (response == null || response.getSections() == null) {
|
||||
throw new RulesImportException("Le Brain a renvoyé une réponse vide.");
|
||||
}
|
||||
@@ -119,11 +134,11 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
Consumer<Throwable> onError) {
|
||||
|
||||
MultipartBodyBuilder parts = new MultipartBodyBuilder();
|
||||
parts.part("file", sse.filePart(pdfBytes, filename, "rules.pdf"))
|
||||
.filename(filename == null || filename.isBlank() ? "rules.pdf" : filename);
|
||||
parts.part("file", sse.filePart(pdfBytes, filename, DEFAULT_FILENAME))
|
||||
.filename(filename == null || filename.isBlank() ? DEFAULT_FILENAME : filename);
|
||||
|
||||
Flux<ServerSentEvent<String>> flux = webClient.post()
|
||||
.uri(IMPORT_RULES_STREAM_PATH)
|
||||
.uri(importRulesStreamPath)
|
||||
.header(UserLanguageHolder.HEADER, UserLanguageHolder.get())
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.accept(MediaType.TEXT_EVENT_STREAM)
|
||||
@@ -136,12 +151,11 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
int[] pageCount = {0};
|
||||
int[] ocrPageCount = {0};
|
||||
boolean[] terminated = {false};
|
||||
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onError);
|
||||
|
||||
sse.runStream(
|
||||
flux, importTimeoutSeconds, terminated,
|
||||
event -> handleEvent(
|
||||
event, pageCount, ocrPageCount, terminated,
|
||||
onProgress, onHeartbeat, onStatus, onDone, onError),
|
||||
event -> handleEvent(event, pageCount, ocrPageCount, terminated, callbacks),
|
||||
onError, RulesImportException::new);
|
||||
}
|
||||
|
||||
@@ -150,11 +164,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
int[] pageCount,
|
||||
int[] ocrPageCount,
|
||||
boolean[] terminated,
|
||||
Consumer<RulesImportProgress> onProgress,
|
||||
Runnable onHeartbeat,
|
||||
Consumer<String> onStatus,
|
||||
Consumer<RulesImportResult> onDone,
|
||||
Consumer<Throwable> onError) {
|
||||
ImportCallbacks callbacks) {
|
||||
|
||||
String event = ssEvent.event();
|
||||
String data = ssEvent.data() == null ? "" : ssEvent.data();
|
||||
@@ -163,28 +173,28 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
// Keep-alive du Brain pendant un appel LLM long : à PROPAGER jusqu'au
|
||||
// navigateur, sinon nginx (proxy_read_timeout) coupe le SSE Core→front
|
||||
// resté silencieux pendant tout le traitement du morceau.
|
||||
onHeartbeat.run();
|
||||
callbacks.onHeartbeat().run();
|
||||
return;
|
||||
}
|
||||
if ("status".equals(event)) {
|
||||
// Message d'attente lisible (retry sur fournisseur saturé, morceau
|
||||
// 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;
|
||||
}
|
||||
if ("chunk_failed".equals(event)) {
|
||||
onStatus.accept(sse.chunkFailedStatus(data));
|
||||
callbacks.onStatus().accept(sse.chunkFailedStatus(data));
|
||||
return;
|
||||
}
|
||||
if ("error".equals(event)) {
|
||||
terminated[0] = true;
|
||||
onError.accept(new RulesImportException(
|
||||
callbacks.onError().accept(new RulesImportException(
|
||||
"Le Brain a signalé une erreur : " + sse.readMessage(data)));
|
||||
return;
|
||||
}
|
||||
if ("extracting".equals(event)) {
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -194,10 +204,10 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
if ("start".equals(event)) {
|
||||
pageCount[0] = node.path("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()));
|
||||
} else if ("progress".equals(event)) {
|
||||
onProgress.accept(new RulesImportProgress(
|
||||
callbacks.onProgress().accept(new RulesImportProgress(
|
||||
node.path("current").asInt(),
|
||||
node.path("total").asInt(),
|
||||
pageCount[0],
|
||||
@@ -205,7 +215,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
toStringList(node.path("new_sections"))));
|
||||
} else if ("done".equals(event)) {
|
||||
terminated[0] = true;
|
||||
onDone.accept(new RulesImportResult(
|
||||
callbacks.onDone().accept(new RulesImportResult(
|
||||
toStringMap(node.path("sections")),
|
||||
node.path("page_count").asInt(),
|
||||
node.path("ocr_page_count").asInt()));
|
||||
|
||||
@@ -62,23 +62,38 @@ public class BrainSceneDraftClient implements SceneDraftAssistant {
|
||||
if (resp == null) {
|
||||
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<>();
|
||||
Object rawScenes = resp.get("scenes");
|
||||
if (rawScenes instanceof List<?> list) {
|
||||
for (Object item : list) {
|
||||
if (!(item instanceof Map<?, ?> m)) continue;
|
||||
String name = asString(m.get("name"));
|
||||
if (name == null || name.isBlank()) continue; // un titre est obligatoire
|
||||
out.add(new SceneDraft(
|
||||
name.trim(),
|
||||
trimOrNull(asString(m.get("description"))),
|
||||
trimOrNull(asString(m.get("playerNarration")))));
|
||||
for (Object raw : list) {
|
||||
SceneDraft draft = toSceneDraft(raw);
|
||||
if (draft != null) {
|
||||
out.add(draft);
|
||||
}
|
||||
}
|
||||
}
|
||||
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) {
|
||||
return o != null ? o.toString() : null;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -41,7 +42,7 @@ public class BrainSidecar {
|
||||
private final BrainSidecarProperties props;
|
||||
private final String internalSecret;
|
||||
|
||||
private volatile Process process;
|
||||
private final AtomicReference<Process> process = new AtomicReference<>();
|
||||
|
||||
public BrainSidecar(BrainSidecarProperties props,
|
||||
@Value("${brain.internal-secret:}") String internalSecret) {
|
||||
@@ -75,9 +76,10 @@ public class BrainSidecar {
|
||||
// (cf. Settings.internal_shared_secret cote Python -> env INTERNAL_SHARED_SECRET)
|
||||
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={}).",
|
||||
process.pid(), workingDir != null ? workingDir : "<heritee>");
|
||||
started.pid(), workingDir != null ? workingDir : "<heritee>");
|
||||
} catch (IOException e) {
|
||||
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
||||
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
||||
@@ -87,7 +89,7 @@ public class BrainSidecar {
|
||||
|
||||
@PreDestroy
|
||||
public void stop() {
|
||||
Process p = this.process;
|
||||
Process p = this.process.get();
|
||||
if (p == null || !p.isAlive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ import java.util.function.Consumer;
|
||||
*/
|
||||
final class BrainSseImportSupport {
|
||||
|
||||
/** Champ JSON standard des events SSE du Brain portant un message lisible. */
|
||||
private static final String MESSAGE_FIELD = "message";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
BrainSseImportSupport(ObjectMapper objectMapper) {
|
||||
@@ -50,8 +53,8 @@ final class BrainSseImportSupport {
|
||||
/** Champ {@code message} du JSON, ou la {@code data} brute si non-JSON / champ absent. */
|
||||
String readMessage(String data) {
|
||||
JsonNode node = readJson(data);
|
||||
if (node != null && node.hasNonNull("message")) {
|
||||
return node.get("message").asText();
|
||||
if (node != null && node.hasNonNull(MESSAGE_FIELD)) {
|
||||
return node.get(MESSAGE_FIELD).asText();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -59,8 +62,8 @@ final class BrainSseImportSupport {
|
||||
/** Statut lisible « Morceau x/y ignoré[ : message] » depuis un payload {@code chunk_failed}. */
|
||||
String chunkFailedStatus(String data) {
|
||||
JsonNode node = readJson(data);
|
||||
String msg = node != null && node.hasNonNull("message")
|
||||
? node.get("message").asText() : "";
|
||||
String msg = node != null && node.hasNonNull(MESSAGE_FIELD)
|
||||
? node.get(MESSAGE_FIELD).asText() : "";
|
||||
int current = node != null ? node.path("current").asInt() : 0;
|
||||
int total = node != null ? node.path("total").asInt() : 0;
|
||||
return "Morceau " + current + "/" + total + " ignoré"
|
||||
|
||||
@@ -26,6 +26,8 @@ public class DesktopBrowserOpener {
|
||||
private static final Logger log = LoggerFactory.getLogger(DesktopBrowserOpener.class);
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
// S125 : faux positif — commentaire explicatif (prose), pas de code mort.
|
||||
@SuppressWarnings("java:S125")
|
||||
public void onReady() {
|
||||
// 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.
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
@@ -26,12 +29,26 @@ import java.nio.file.StandardOpenOption;
|
||||
* ({@code java.desktop}) pourrait etre absent du runtime reduit par jlink.
|
||||
* 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 {
|
||||
|
||||
/** 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")
|
||||
private static FileChannel lockChannel;
|
||||
private static FileLock lock;
|
||||
|
||||
private DesktopSingleInstance() {}
|
||||
|
||||
@@ -71,11 +88,11 @@ public final class DesktopSingleInstance {
|
||||
Path lockFile = dir.resolve(".instance.lock");
|
||||
lockChannel = FileChannel.open(lockFile,
|
||||
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||
lock = lockChannel.tryLock();
|
||||
FileLock lock = lockChannel.tryLock();
|
||||
return lock != null; // null = deja verrouille par une autre instance
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Verrou d'instance indisponible (" + e.getMessage()
|
||||
+ ") — on tente de demarrer quand meme.");
|
||||
log.warn("[Desktop] Verrou d'instance indisponible ({}) — on tente de demarrer quand meme.",
|
||||
e.getMessage());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -88,7 +105,7 @@ public final class DesktopSingleInstance {
|
||||
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */
|
||||
public static void openUrl(String url) {
|
||||
try {
|
||||
String os = System.getProperty("os.name", "").toLowerCase();
|
||||
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||
ProcessBuilder pb;
|
||||
if (os.contains("win")) {
|
||||
// rundll32 : ouverture d'URL fiable sans dependance graphique Java.
|
||||
@@ -96,12 +113,12 @@ public final class DesktopSingleInstance {
|
||||
} else if (os.contains("mac")) {
|
||||
pb = new ProcessBuilder("open", url);
|
||||
} else {
|
||||
pb = new ProcessBuilder("xdg-open", url);
|
||||
pb = new ProcessBuilder(XDG_OPEN, url);
|
||||
}
|
||||
pb.start();
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Impossible d'ouvrir le navigateur sur " + url
|
||||
+ " : " + e.getMessage() + ". Ouvrez-le manuellement.");
|
||||
log.warn("[Desktop] Impossible d'ouvrir le navigateur sur {} : {}. Ouvrez-le manuellement.",
|
||||
url, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,25 +126,25 @@ public final class DesktopSingleInstance {
|
||||
public static void openFolder(Path dir) {
|
||||
try {
|
||||
Files.createDirectories(dir);
|
||||
String os = System.getProperty("os.name", "").toLowerCase();
|
||||
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||
ProcessBuilder pb;
|
||||
if (os.contains("win")) {
|
||||
pb = new ProcessBuilder("explorer.exe", dir.toString());
|
||||
} else if (os.contains("mac")) {
|
||||
pb = new ProcessBuilder("open", dir.toString());
|
||||
} else {
|
||||
pb = new ProcessBuilder("xdg-open", dir.toString());
|
||||
pb = new ProcessBuilder(XDG_OPEN, dir.toString());
|
||||
}
|
||||
pb.start();
|
||||
} 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). */
|
||||
public static void openInEditor(Path file) {
|
||||
try {
|
||||
String os = System.getProperty("os.name", "").toLowerCase();
|
||||
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||
ProcessBuilder pb;
|
||||
if (os.contains("win")) {
|
||||
// notepad : toujours present, ouvre proprement un .properties
|
||||
@@ -136,11 +153,11 @@ public final class DesktopSingleInstance {
|
||||
} else if (os.contains("mac")) {
|
||||
pb = new ProcessBuilder("open", "-t", file.toString());
|
||||
} else {
|
||||
pb = new ProcessBuilder("xdg-open", file.toString());
|
||||
pb = new ProcessBuilder(XDG_OPEN, file.toString());
|
||||
}
|
||||
pb.start();
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Ouverture du fichier impossible : " + e.getMessage());
|
||||
log.warn("[Desktop] Ouverture du fichier impossible : {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
@@ -30,6 +33,14 @@ import java.util.Properties;
|
||||
*/
|
||||
public final class DesktopUserConfig {
|
||||
|
||||
// Utilisé AVANT SpringApplication.run() : Logback s'initialise avec sa config
|
||||
// par défaut (console), puis Spring reprend la main — même destination que
|
||||
// l'ancien System.out, mais horodaté et uniforme avec le reste des logs.
|
||||
private static final Logger log = LoggerFactory.getLogger(DesktopUserConfig.class);
|
||||
|
||||
/** Clé partagée fichier utilisateur / propriété système / Spring. */
|
||||
private static final String SERVER_PORT_PROPERTY = "server.port";
|
||||
|
||||
private DesktopUserConfig() {}
|
||||
|
||||
private static final String DEFAULT_TEMPLATE = """
|
||||
@@ -69,10 +80,10 @@ public final class DesktopUserConfig {
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, DEFAULT_TEMPLATE);
|
||||
System.out.println("[Desktop] Config utilisateur creee : " + file);
|
||||
log.info("[Desktop] Config utilisateur creee : {}", file);
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Impossible de creer " + file + " : " + e.getMessage()
|
||||
+ " — defauts utilises (port 8080, admin/admin).");
|
||||
log.warn("[Desktop] Impossible de creer {} : {} — defauts utilises (port 8080, admin/admin).",
|
||||
file, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,13 +98,13 @@ public final class DesktopUserConfig {
|
||||
int wanted = configuredPort();
|
||||
int chosen = isPortFree(wanted) ? wanted : findFreePort(wanted);
|
||||
if (chosen != wanted) {
|
||||
System.out.println("[Desktop] Port " + wanted + " occupe — repli sur le port libre " + chosen + ".");
|
||||
log.info("[Desktop] Port {} occupe — repli sur le port libre {}.", wanted, chosen);
|
||||
}
|
||||
System.setProperty("server.port", String.valueOf(chosen));
|
||||
System.setProperty(SERVER_PORT_PROPERTY, String.valueOf(chosen));
|
||||
try {
|
||||
Files.writeString(portFile(), String.valueOf(chosen));
|
||||
} catch (IOException e) {
|
||||
System.err.println("[Desktop] Ecriture du port impossible (" + e.getMessage() + ").");
|
||||
log.warn("[Desktop] Ecriture du port impossible ({}).", e.getMessage());
|
||||
}
|
||||
return chosen;
|
||||
}
|
||||
@@ -104,7 +115,7 @@ public final class DesktopUserConfig {
|
||||
* → port configuré → 8080.
|
||||
*/
|
||||
public static int runningPort() {
|
||||
String sys = System.getProperty("server.port");
|
||||
String sys = System.getProperty(SERVER_PORT_PROPERTY);
|
||||
if (sys != null && !sys.isBlank()) {
|
||||
try { return Integer.parseInt(sys.trim()); } catch (NumberFormatException ignored) { /* fallthrough */ }
|
||||
}
|
||||
@@ -124,7 +135,7 @@ public final class DesktopUserConfig {
|
||||
Properties props = new Properties();
|
||||
try (InputStream in = Files.newInputStream(file)) {
|
||||
props.load(in);
|
||||
String v = props.getProperty("server.port");
|
||||
String v = props.getProperty(SERVER_PORT_PROPERTY);
|
||||
if (v != null && !v.isBlank()) {
|
||||
return Integer.parseInt(v.trim());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Mode bureau : choisit l'accès au pare-feu selon le système — Windows (PowerShell, UAC),
|
||||
* Linux (ufw / firewalld, lecture sans root), sinon rien à vérifier (macOS…).
|
||||
*/
|
||||
@Configuration
|
||||
@Profile("local")
|
||||
public class HostNetworkAccessConfig {
|
||||
|
||||
@Bean
|
||||
public HostNetworkAccess hostNetworkAccess(ObjectMapper objectMapper) {
|
||||
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
|
||||
if (os.startsWith("windows")) return new WindowsHostNetworkAccess(objectMapper);
|
||||
if (os.contains("linux")) return new LinuxHostNetworkAccess();
|
||||
return new UnsupportedHostNetworkAccess();
|
||||
}
|
||||
|
||||
/** Système sans vérification prise en charge : le front n'affiche pas de diagnostic. */
|
||||
static final class UnsupportedHostNetworkAccess implements HostNetworkAccess {
|
||||
@Override public NetworkSnapshot inspect(int port) { return NetworkSnapshot.unsupported(); }
|
||||
@Override public FirewallFixOutcome allowThroughFirewall() { return FirewallFixOutcome.UNSUPPORTED; }
|
||||
@Override public void openNetworkSettings() { /* rien à ouvrir */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Pare-feu sous Linux (Debian, Ubuntu, Fedora…) pour l'accès distant, SANS droits root.
|
||||
* <p>
|
||||
* Ce qu'on peut savoir sans root : quel pare-feu est actif — {@code ufw} via
|
||||
* {@code /etc/ufw/ufw.conf} (lisible par tous), {@code firewalld} via {@code systemctl} — et,
|
||||
* pour firewalld seulement, si le port est ouvert ({@code firewall-cmd --query-port}, autorisé
|
||||
* aux utilisateurs). Les règles d'ufw ne se lisent qu'en root : l'état du port reste alors
|
||||
* inconnu et le front affiche la commande à lancer. Pas d'autorisation en un clic : sur un
|
||||
* serveur sans écran, aucune fenêtre ne peut demander le mot de passe administrateur.
|
||||
* <p>
|
||||
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Linux.
|
||||
*/
|
||||
public class LinuxHostNetworkAccess implements HostNetworkAccess {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(LinuxHostNetworkAccess.class);
|
||||
private static final long COMMAND_TIMEOUT_S = 10;
|
||||
|
||||
static final String UFW = "ufw";
|
||||
static final String FIREWALLD = "firewalld";
|
||||
static final String NONE = "none";
|
||||
|
||||
private final Path ufwConf;
|
||||
|
||||
public LinuxHostNetworkAccess() {
|
||||
this(Path.of("/etc/ufw/ufw.conf"));
|
||||
}
|
||||
|
||||
LinuxHostNetworkAccess(Path ufwConf) {
|
||||
this.ufwConf = ufwConf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NetworkSnapshot inspect(int port) {
|
||||
if (ufwEnabled(readQuietly(ufwConf))) {
|
||||
// Règles d'ufw illisibles sans root : état du port inconnu.
|
||||
return NetworkSnapshot.linux(UFW, port, null);
|
||||
}
|
||||
if ("active".equals(run(List.of("systemctl", "is-active", FIREWALLD)).output().trim())) {
|
||||
return NetworkSnapshot.linux(FIREWALLD, port, firewalldPortOpen(port));
|
||||
}
|
||||
return NetworkSnapshot.linux(NONE, port, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FirewallFixOutcome allowThroughFirewall() {
|
||||
return FirewallFixOutcome.UNSUPPORTED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openNetworkSettings() {
|
||||
// Pas de réglage réseau « Public / Privé » à basculer sous Linux.
|
||||
}
|
||||
|
||||
/** {@code firewall-cmd --query-port} : « yes » (0) / « no » (1) ; autre = inconnu. */
|
||||
private Boolean firewalldPortOpen(int port) {
|
||||
Result r = run(List.of("firewall-cmd", "--query-port=" + port + "/tcp"));
|
||||
return interpretQuery(r.exitCode(), r.output());
|
||||
}
|
||||
|
||||
static Boolean interpretQuery(int exitCode, String output) {
|
||||
String out = output == null ? "" : output.trim().toLowerCase(Locale.ROOT);
|
||||
if (exitCode == 0 && out.startsWith("yes")) return true;
|
||||
if (exitCode == 1 && out.startsWith("no")) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** {@code ENABLED=yes} dans ufw.conf (guillemets et casse tolérés). */
|
||||
static boolean ufwEnabled(String conf) {
|
||||
if (conf == null) return false;
|
||||
return conf.lines()
|
||||
.map(String::trim)
|
||||
.filter(l -> !l.startsWith("#"))
|
||||
.map(l -> l.replace("\"", "").replace("'", "").replace(" ", ""))
|
||||
.anyMatch(l -> l.equalsIgnoreCase("ENABLED=yes"));
|
||||
}
|
||||
|
||||
private static String readQuietly(Path file) {
|
||||
try {
|
||||
return Files.isReadable(file) ? Files.readString(file, StandardCharsets.UTF_8) : null;
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private record Result(int exitCode, String output) {}
|
||||
|
||||
/** Commande système sans shell (pas d'interprétation), avec délai ; absente → code -1. */
|
||||
private static Result run(List<String> command) {
|
||||
try {
|
||||
Process p = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
p.getOutputStream().close();
|
||||
if (!p.waitFor(COMMAND_TIMEOUT_S, TimeUnit.SECONDS)) {
|
||||
p.destroyForcibly();
|
||||
return new Result(-1, "");
|
||||
}
|
||||
return new Result(p.exitValue(), new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
|
||||
} catch (IOException e) {
|
||||
log.debug("Commande {} indisponible : {}", command.get(0), e.getMessage());
|
||||
return new Result(-1, "");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return new Result(-1, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Mode bureau : rouvre l'accès distant au démarrage s'il avait été activé. */
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class RemoteAccessBootstrap {
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemoteAccessBootstrap(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void reopenIfEnabled() {
|
||||
remoteAccessService.applySavedConfig();
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,13 @@ public class SystemTrayManager {
|
||||
open.addActionListener(e -> DesktopSingleInstance.openAppInBrowser());
|
||||
popup.add(open);
|
||||
|
||||
// Acces distant : ouvre la section Parametres ou l'on active l'acces
|
||||
// depuis une tablette et ou l'on affiche le code d'appairage.
|
||||
MenuItem remote = new MenuItem("Connecter une tablette…");
|
||||
remote.addActionListener(e -> DesktopSingleInstance.openUrl(
|
||||
"http://localhost:" + DesktopUserConfig.runningPort() + "/settings?section=remote-access"));
|
||||
popup.add(remote);
|
||||
|
||||
popup.addSeparator();
|
||||
|
||||
// Reglages : ouvre loremind.properties (port, identifiants admin) dans
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import org.apache.catalina.connector.Connector;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.apache.coyote.http11.AbstractHttp11Protocol;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.SocketException;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Second connecteur HTTP de Tomcat, ouvert À CHAUD sur toutes les interfaces quand le MJ
|
||||
* active l'accès distant (mode bureau uniquement).
|
||||
* <p>
|
||||
* Pourquoi un second connecteur plutôt que d'ouvrir le principal : le connecteur habituel
|
||||
* reste sur 127.0.0.1 (aucun changement de comportement, pas d'alerte du pare-feu Windows
|
||||
* chez qui n'active rien), et le port d'arrivée suffit à distinguer une requête locale d'une
|
||||
* requête venue du réseau (cf. {@code RemoteAccessFilter}). Ouverture et fermeture sans
|
||||
* redémarrer l'application.
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class TomcatLanConnector implements LanConnector {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(TomcatLanConnector.class);
|
||||
|
||||
/** Interfaces à ignorer pour composer l'URL : réseaux virtuels (VM, WSL, Docker, VPN…). */
|
||||
private static final List<String> VIRTUAL_HINTS = List.of(
|
||||
"virtual", "vmware", "vbox", "hyper-v", "vethernet", "docker", "wsl", "loopback", "tap-", "tun");
|
||||
|
||||
private final ApplicationContext context;
|
||||
private Connector connector;
|
||||
|
||||
public TomcatLanConnector(ApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void start(int port) {
|
||||
if (connector != null && connector.getPort() == port) return;
|
||||
stop();
|
||||
ensurePortFree(port);
|
||||
|
||||
Tomcat tomcat = tomcat();
|
||||
Connector main = tomcat.getConnector();
|
||||
Connector lan = new Connector(main.getProtocolHandlerClassName());
|
||||
lan.setPort(port);
|
||||
lan.setProperty("address", "0.0.0.0");
|
||||
// Mêmes limites d'upload que le connecteur principal (imports PDF volumineux).
|
||||
lan.setMaxPostSize(main.getMaxPostSize());
|
||||
if (main.getProtocolHandler() instanceof AbstractHttp11Protocol<?> mainProtocol
|
||||
&& lan.getProtocolHandler() instanceof AbstractHttp11Protocol<?> lanProtocol) {
|
||||
lanProtocol.setMaxSwallowSize(mainProtocol.getMaxSwallowSize());
|
||||
}
|
||||
try {
|
||||
tomcat.getService().addConnector(lan); // démarre le connecteur : le service tourne déjà
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalStateException("Impossible d'ouvrir le port " + port + " : " + e.getMessage(), e);
|
||||
}
|
||||
connector = lan;
|
||||
log.info("Accès distant : connecteur réseau ouvert sur le port {}", port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
if (connector == null) return;
|
||||
try {
|
||||
tomcat().getService().removeConnector(connector);
|
||||
connector.destroy();
|
||||
} catch (Exception e) {
|
||||
log.warn("Fermeture du connecteur réseau incomplète : {}", e.getMessage());
|
||||
}
|
||||
log.info("Accès distant : connecteur réseau fermé (port {})", connector.getPort());
|
||||
connector = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int runningPort() {
|
||||
return connector != null ? connector.getPort() : -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> lanAddresses() {
|
||||
try {
|
||||
return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
|
||||
.filter(TomcatLanConnector::isPhysicalAndUp)
|
||||
.flatMap(nic -> Collections.list(nic.getInetAddresses()).stream())
|
||||
.filter(a -> a instanceof Inet4Address && a.isSiteLocalAddress())
|
||||
.map(a -> a.getHostAddress())
|
||||
.distinct()
|
||||
// Box domestique d'abord (192.168.x), puis 10.x / 172.16-31.x.
|
||||
.sorted(Comparator.comparing((String ip) -> !ip.startsWith("192.168.")).thenComparing(ip -> ip))
|
||||
.toList();
|
||||
} catch (SocketException e) {
|
||||
log.warn("Lecture des interfaces réseau impossible : {}", e.getMessage());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPhysicalAndUp(NetworkInterface nic) {
|
||||
try {
|
||||
if (!nic.isUp() || nic.isLoopback() || nic.isVirtual() || nic.isPointToPoint()) return false;
|
||||
} catch (SocketException e) {
|
||||
return false;
|
||||
}
|
||||
String label = (nic.getName() + " " + nic.getDisplayName()).toLowerCase(Locale.ROOT);
|
||||
return VIRTUAL_HINTS.stream().noneMatch(label::contains);
|
||||
}
|
||||
|
||||
/** Vérification préalable pour un message clair (sinon Tomcat ne log qu'une trace obscure). */
|
||||
private static void ensurePortFree(int port) {
|
||||
try (ServerSocket probe = new ServerSocket()) {
|
||||
probe.setReuseAddress(false);
|
||||
probe.bind(new InetSocketAddress(port));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Le port " + port + " est déjà utilisé par une autre application.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Tomcat tomcat() {
|
||||
if (context instanceof ServletWebServerApplicationContext web) {
|
||||
WebServer server = web.getWebServer();
|
||||
if (server instanceof TomcatWebServer tomcatServer) {
|
||||
return tomcatServer.getTomcat();
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Serveur web embarqué indisponible.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Accès au réseau et au pare-feu de Windows pour l'accès distant (mode bureau).
|
||||
* <p>
|
||||
* Lecture via PowerShell, sans droits administrateur. L'autorisation dans le pare-feu
|
||||
* passe par {@code Start-Process -Verb RunAs} : Windows affiche sa confirmation
|
||||
* administrateur (UAC) et l'utilisateur garde la main. La règle créée n'ouvre DM Loremind
|
||||
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
|
||||
* (réglage système, jamais modifié par l'application).
|
||||
* <p>
|
||||
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
|
||||
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
|
||||
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
|
||||
* <p>
|
||||
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows.
|
||||
*/
|
||||
public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WindowsHostNetworkAccess.class);
|
||||
|
||||
static final String RULE_NAME = "DM Loremind (accès tablette)";
|
||||
private static final long INSPECT_TIMEOUT_S = 20;
|
||||
/** Le temps pour l'utilisateur de lire et de répondre à la fenêtre UAC. */
|
||||
private static final long ELEVATION_TIMEOUT_S = 180;
|
||||
/** Code Windows ERROR_CANCELLED : l'utilisateur a refusé la confirmation administrateur. */
|
||||
private static final int EXIT_CANCELLED = 1223;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public WindowsHostNetworkAccess(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NetworkSnapshot inspect(int port) {
|
||||
String program = currentProgram();
|
||||
if (!isWindows() || program == null) return NetworkSnapshot.unsupported();
|
||||
try {
|
||||
String json = runPowerShell(inspectScript(program), INSPECT_TIMEOUT_S).output();
|
||||
return parseSnapshot(objectMapper, program, json);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("Accès distant : lecture du réseau / pare-feu impossible : {}", e.getMessage());
|
||||
return NetworkSnapshot.unsupported();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return NetworkSnapshot.unsupported();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FirewallFixOutcome allowThroughFirewall() {
|
||||
String program = currentProgram();
|
||||
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
|
||||
String outer = "try {\n"
|
||||
+ " $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
|
||||
+ "-ArgumentList @('-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','"
|
||||
+ encode(allowScript(program)) + "')\n"
|
||||
+ " exit $p.ExitCode\n"
|
||||
+ "} catch { exit " + EXIT_CANCELLED + " }\n";
|
||||
try {
|
||||
int exit = runPowerShell(outer, ELEVATION_TIMEOUT_S).exitCode();
|
||||
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
|
||||
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
|
||||
log.info("Accès distant : autorisation pare-feu → {}", outcome);
|
||||
return outcome;
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("Accès distant : autorisation pare-feu impossible : {}", e.getMessage());
|
||||
return FirewallFixOutcome.FAILED;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return FirewallFixOutcome.FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openNetworkSettings() {
|
||||
if (!isWindows()) return;
|
||||
try {
|
||||
// « État du réseau » : le réseau connecté et son bouton « Propriétés » (type de profil).
|
||||
new ProcessBuilder("cmd", "/c", "start", "", "ms-settings:network-status").start();
|
||||
} catch (IOException e) {
|
||||
log.warn("Ouverture des réglages réseau impossible : {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// --- Scripts --------------------------------------------------------------------------
|
||||
|
||||
/** Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris). */
|
||||
static String inspectScript(String program) {
|
||||
return "$ErrorActionPreference = 'SilentlyContinue'\n"
|
||||
// Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués.
|
||||
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"
|
||||
+ "$p = '" + psQuote(program) + "'\n"
|
||||
+ "$nets =@(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
|
||||
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } })\n"
|
||||
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
||||
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
||||
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
||||
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n"
|
||||
// Pare-feu TIERS déclarés au Centre de sécurité (le pare-feu Windows n'y figure pas) :
|
||||
// ils filtrent en plus de Windows, avec des règles qu'on ne peut pas lire.
|
||||
+ "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | "
|
||||
+ "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' })\n"
|
||||
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
|
||||
+ "ConvertTo-Json -Depth 4 -Compress\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Exécuté ÉLEVÉ : retire les blocages entrants visant CE programme (créés par un « Annuler »
|
||||
* dans la fenêtre du pare-feu, ils l'emporteraient sur toute autorisation), remplace notre
|
||||
* propre règle si elle existe, puis autorise sur les réseaux privés uniquement.
|
||||
*/
|
||||
static String allowScript(String program) {
|
||||
String name = psQuote(RULE_NAME);
|
||||
return "try {\n"
|
||||
+ " $p = '" + psQuote(program) + "'\n"
|
||||
+ " Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
||||
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
||||
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' -and $_.Action.ToString() -eq 'Block' } | "
|
||||
+ "Remove-NetFirewallRule\n"
|
||||
+ " Get-NetFirewallRule -DisplayName '" + name + "' -ErrorAction SilentlyContinue | Remove-NetFirewallRule\n"
|
||||
+ " New-NetFirewallRule -DisplayName '" + name + "' -Direction Inbound -Program $p -Action Allow "
|
||||
+ "-Profile Private -ErrorAction Stop | Out-Null\n"
|
||||
+ " exit 0\n"
|
||||
+ "} catch { exit 2 }\n";
|
||||
}
|
||||
|
||||
static NetworkSnapshot parseSnapshot(ObjectMapper mapper, String program, String json) throws IOException {
|
||||
JsonNode root = mapper.readTree(json == null || json.isBlank() ? "{}" : json.trim());
|
||||
List<NetworkSnapshot.Network> networks = new ArrayList<>();
|
||||
for (JsonNode n : array(root.path("networks"))) {
|
||||
networks.add(new NetworkSnapshot.Network(text(n, "name"), text(n, "alias"), text(n, "category")));
|
||||
}
|
||||
List<NetworkSnapshot.FirewallRule> rules = new ArrayList<>();
|
||||
for (JsonNode r : array(root.path("rules"))) {
|
||||
rules.add(new NetworkSnapshot.FirewallRule(text(r, "action"), text(r, "profile"), text(r, "enabled")));
|
||||
}
|
||||
List<String> thirdParty = new ArrayList<>();
|
||||
for (JsonNode f : array(root.path("thirdPartyFirewalls"))) {
|
||||
if (f.isTextual() && !f.asText().isBlank()) thirdParty.add(f.asText());
|
||||
}
|
||||
return new NetworkSnapshot(true, program, networks, rules, thirdParty);
|
||||
}
|
||||
|
||||
/** ConvertTo-Json écrit un objet seul (pas un tableau) quand la liste n'a qu'un élément. */
|
||||
private static Iterable<JsonNode> array(JsonNode node) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) return List.of();
|
||||
return node.isArray() ? node : List.of(node);
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
return v == null || v.isNull() ? null : v.asText();
|
||||
}
|
||||
|
||||
static String psQuote(String value) {
|
||||
return value.replace("'", "''");
|
||||
}
|
||||
|
||||
static String encode(String script) {
|
||||
return Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_16LE));
|
||||
}
|
||||
|
||||
// --- Exécution ------------------------------------------------------------------------
|
||||
|
||||
private record Result(int exitCode, String output) {}
|
||||
|
||||
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
|
||||
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive",
|
||||
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
||||
.start();
|
||||
process.getOutputStream().close();
|
||||
// Lecture en parallèle : un tampon de sortie plein bloquerait le processus avant sa fin.
|
||||
CompletableFuture<String> output = CompletableFuture.supplyAsync(() -> {
|
||||
try (InputStream out = process.getInputStream()) {
|
||||
return new String(out.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
return "";
|
||||
}
|
||||
});
|
||||
if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("PowerShell n'a pas répondu en " + timeoutSeconds + " s");
|
||||
}
|
||||
return new Result(process.exitValue(), output.join());
|
||||
}
|
||||
|
||||
private static boolean isWindows() {
|
||||
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
|
||||
}
|
||||
|
||||
/** Exécutable du processus courant : DM Loremind.exe en bureau (java.exe en développement). */
|
||||
private static String currentProgram() {
|
||||
return ProcessHandle.current().info().command().orElse(null);
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -37,6 +37,9 @@ public class FileDockerConfigWriter implements DockerConfigWriter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FileDockerConfigWriter.class);
|
||||
|
||||
/** Cle racine du config.json Docker portant les registres authentifies. */
|
||||
private static final String AUTHS_KEY = "auths";
|
||||
|
||||
private final Path configPath;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -62,9 +65,9 @@ public class FileDockerConfigWriter implements DockerConfigWriter {
|
||||
root = mapper.createObjectNode();
|
||||
}
|
||||
|
||||
ObjectNode auths = root.has("auths") && root.get("auths").isObject()
|
||||
? (ObjectNode) root.get("auths")
|
||||
: root.putObject("auths");
|
||||
ObjectNode auths = root.has(AUTHS_KEY) && root.get(AUTHS_KEY).isObject()
|
||||
? (ObjectNode) root.get(AUTHS_KEY)
|
||||
: root.putObject(AUTHS_KEY);
|
||||
|
||||
String b64 = Base64.getEncoder().encodeToString(
|
||||
(credentials.username() + ":" + credentials.password()).getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
@@ -8,7 +8,7 @@ import com.nimbusds.jose.crypto.Ed25519Verifier;
|
||||
import com.nimbusds.jose.jwk.OctetKeyPair;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.bouncycastle.asn1.ASN1Sequence;
|
||||
import org.bouncycastle.asn1.ASN1Primitive;
|
||||
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -21,8 +21,8 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Verifie les JWT EdDSA/Ed25519 emis par le relais Patreon.
|
||||
@@ -88,25 +88,48 @@ public class NimbusJwtVerifier implements JwtVerifier {
|
||||
|
||||
@Override
|
||||
public LicenseClaims verify(String rawJwt) throws JwtVerificationException {
|
||||
ensureConfigured();
|
||||
ensureNotBlank(rawJwt);
|
||||
|
||||
SignedJWT signed = parseJwt(rawJwt);
|
||||
ensureExpectedAlgorithm(signed);
|
||||
verifySignature(signed);
|
||||
|
||||
JWTClaimsSet claims = parseClaims(signed);
|
||||
ensureExpectedIssuer(claims);
|
||||
ensureExpectedAudience(claims);
|
||||
|
||||
return toLicenseClaims(claims);
|
||||
}
|
||||
|
||||
private void ensureConfigured() throws JwtVerificationException {
|
||||
if (publicKey == null) {
|
||||
throw new JwtVerificationException("JWT verifier not configured");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureNotBlank(String rawJwt) throws JwtVerificationException {
|
||||
if (rawJwt == null || rawJwt.isBlank()) {
|
||||
throw new JwtVerificationException("JWT is empty");
|
||||
}
|
||||
}
|
||||
|
||||
SignedJWT signed;
|
||||
private static SignedJWT parseJwt(String rawJwt) throws JwtVerificationException {
|
||||
try {
|
||||
signed = SignedJWT.parse(rawJwt);
|
||||
return SignedJWT.parse(rawJwt);
|
||||
} catch (ParseException e) {
|
||||
throw new JwtVerificationException("JWT parse error: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureExpectedAlgorithm(SignedJWT signed) throws JwtVerificationException {
|
||||
JWSAlgorithm alg = signed.getHeader().getAlgorithm();
|
||||
if (!JWSAlgorithm.EdDSA.equals(alg)) {
|
||||
throw new JwtVerificationException("Unexpected JWT algorithm: " + alg);
|
||||
}
|
||||
}
|
||||
|
||||
private void verifySignature(SignedJWT signed) throws JwtVerificationException {
|
||||
try {
|
||||
JWSVerifier verifier = new Ed25519Verifier(publicKey);
|
||||
if (!signed.verify(verifier)) {
|
||||
@@ -115,31 +138,43 @@ public class NimbusJwtVerifier implements JwtVerifier {
|
||||
} catch (Exception e) {
|
||||
throw new JwtVerificationException("JWT signature verification failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
JWTClaimsSet claims;
|
||||
private static JWTClaimsSet parseClaims(SignedJWT signed) throws JwtVerificationException {
|
||||
try {
|
||||
claims = signed.getJWTClaimsSet();
|
||||
return signed.getJWTClaimsSet();
|
||||
} catch (ParseException e) {
|
||||
throw new JwtVerificationException("JWT claims parse error", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureExpectedIssuer(JWTClaimsSet claims) throws JwtVerificationException {
|
||||
if (!expectedIssuer.equals(claims.getIssuer())) {
|
||||
throw new JwtVerificationException("JWT issuer mismatch: " + claims.getIssuer());
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureExpectedAudience(JWTClaimsSet claims) throws JwtVerificationException {
|
||||
if (claims.getAudience() == null || !claims.getAudience().contains(expectedAudience)) {
|
||||
throw new JwtVerificationException("JWT audience mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
Date exp = claims.getExpirationTime();
|
||||
Date iat = claims.getIssueTime();
|
||||
/**
|
||||
* Construit les LicenseClaims depuis les claims validés (issuer/audience/signature).
|
||||
* Note : on ne refuse pas un JWT expiré ici. C'est au LicenseService de decider ce
|
||||
* qu'il fait d'un JWT expire (grace period, refresh, etc.). La verification de
|
||||
* signature reste valide tant que la cle existe.
|
||||
*/
|
||||
private static LicenseClaims toLicenseClaims(JWTClaimsSet claims) throws JwtVerificationException {
|
||||
// Nimbus n'expose exp/iat qu'en java.util.Date : converti en Instant SANS variable
|
||||
// Date intermediaire (aucune reference au type legacy dans cette classe).
|
||||
String sub = claims.getSubject();
|
||||
if (exp == null || iat == null || sub == null) {
|
||||
if (claims.getExpirationTime() == null || claims.getIssueTime() == null || sub == null) {
|
||||
throw new JwtVerificationException("JWT missing required claims");
|
||||
}
|
||||
|
||||
// Note : on ne refuse pas un JWT expire ici. C'est au LicenseService
|
||||
// de decider ce qu'il fait d'un JWT expire (grace period, refresh, etc.).
|
||||
// La verification de signature reste valide tant que la cle existe.
|
||||
Instant exp = claims.getExpirationTime().toInstant();
|
||||
Instant iat = claims.getIssueTime().toInstant();
|
||||
|
||||
String tierId;
|
||||
String instanceId;
|
||||
@@ -153,13 +188,7 @@ public class NimbusJwtVerifier implements JwtVerifier {
|
||||
throw new JwtVerificationException("JWT missing tier_id or instance_id");
|
||||
}
|
||||
|
||||
return new LicenseClaims(
|
||||
sub,
|
||||
tierId,
|
||||
instanceId,
|
||||
iat.toInstant(),
|
||||
exp.toInstant()
|
||||
);
|
||||
return new LicenseClaims(sub, tierId, instanceId, iat, exp);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -174,7 +203,7 @@ public class NimbusJwtVerifier implements JwtVerifier {
|
||||
.replace("-----END PUBLIC KEY-----", "")
|
||||
.replaceAll("\\s+", "");
|
||||
byte[] der = Base64.getDecoder().decode(base64);
|
||||
SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Sequence.fromByteArray(der));
|
||||
SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(der));
|
||||
byte[] keyBytes = spki.getPublicKeyData().getOctets();
|
||||
String x = Base64.getUrlEncoder().withoutPadding().encodeToString(keyBytes);
|
||||
return new OctetKeyPair.Builder(com.nimbusds.jose.jwk.Curve.Ed25519, com.nimbusds.jose.util.Base64URL.from(x))
|
||||
|
||||
+23
-12
@@ -31,6 +31,24 @@ public class CharacterNpcMarkdownBackfill {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(CharacterNpcMarkdownBackfill.class);
|
||||
|
||||
// SQL en CONSTANTES de compilation (pas de concaténation avec un paramètre) :
|
||||
// les noms de table sont figés dans les littéraux, aucune donnée dynamique
|
||||
// n'entre dans la requête hors placeholders '?'.
|
||||
// Sélection : fiches avec markdown non vide ET field_values vide ou absent.
|
||||
// field_values peut etre NULL (legacy avant refonte) ou "{}" (refonte appliquee mais sans data).
|
||||
private static final String BACKFILL_WHERE =
|
||||
" WHERE markdown_content IS NOT NULL "
|
||||
+ " AND markdown_content <> '' "
|
||||
+ " AND (field_values IS NULL OR field_values = '' OR field_values = '{}')";
|
||||
private static final String SELECT_CHARACTERS =
|
||||
"SELECT id, markdown_content FROM characters" + BACKFILL_WHERE;
|
||||
private static final String SELECT_NPCS =
|
||||
"SELECT id, markdown_content FROM npcs" + BACKFILL_WHERE;
|
||||
private static final String UPDATE_CHARACTERS =
|
||||
"UPDATE characters SET field_values = ? WHERE id = ?";
|
||||
private static final String UPDATE_NPCS =
|
||||
"UPDATE npcs SET field_values = ? WHERE id = ?";
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -44,8 +62,8 @@ public class CharacterNpcMarkdownBackfill {
|
||||
log.debug("Backfill skip : colonne markdown_content absente (deja migre ou install propre).");
|
||||
return;
|
||||
}
|
||||
int chars = backfillTable("characters");
|
||||
int npcs = backfillTable("npcs");
|
||||
int chars = backfillTable("characters", SELECT_CHARACTERS, UPDATE_CHARACTERS);
|
||||
int npcs = backfillTable("npcs", SELECT_NPCS, UPDATE_NPCS);
|
||||
if (chars + npcs > 0) {
|
||||
log.info("Backfill markdown -> field_values : {} character(s), {} npc(s) migre(s).", chars, npcs);
|
||||
}
|
||||
@@ -65,14 +83,7 @@ public class CharacterNpcMarkdownBackfill {
|
||||
}
|
||||
}
|
||||
|
||||
private int backfillTable(String table) {
|
||||
// Selection : fiches avec markdown non vide ET field_values vide ou absent.
|
||||
// field_values peut etre NULL (legacy avant refonte) ou "{}" (refonte appliquee mais sans data).
|
||||
String selectSql = "SELECT id, markdown_content FROM " + table
|
||||
+ " WHERE markdown_content IS NOT NULL "
|
||||
+ " AND markdown_content <> '' "
|
||||
+ " AND (field_values IS NULL OR field_values = '' OR field_values = '{}')";
|
||||
|
||||
private int backfillTable(String label, String selectSql, String updateSql) {
|
||||
var rows = jdbc.queryForList(selectSql);
|
||||
int migrated = 0;
|
||||
for (var row : rows) {
|
||||
@@ -82,10 +93,10 @@ public class CharacterNpcMarkdownBackfill {
|
||||
try {
|
||||
json = mapper.writeValueAsString(Map.of("Notes", markdown));
|
||||
} catch (Exception e) {
|
||||
log.error("Backfill {} id={} : echec serialisation JSON, ignore. {}", table, id, e.getMessage());
|
||||
log.error("Backfill {} id={} : echec serialisation JSON, ignore. {}", label, id, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
jdbc.update("UPDATE " + table + " SET field_values = ? WHERE id = ?", json, id);
|
||||
jdbc.update(updateSql, json, id);
|
||||
migrated++;
|
||||
}
|
||||
return migrated;
|
||||
|
||||
@@ -35,6 +35,10 @@ public class GameSystemSeeder {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GameSystemSeeder.class);
|
||||
|
||||
private static final String AUTHOR_SEED = "LoreMind seed";
|
||||
private static final String FIELD_HISTOIRE = "Histoire";
|
||||
private static final String FIELD_GALERIE = "Galerie";
|
||||
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
|
||||
public GameSystemSeeder(GameSystemRepository gameSystemRepository) {
|
||||
@@ -81,7 +85,7 @@ public class GameSystemSeeder {
|
||||
GameSystem.builder()
|
||||
.name("Nimble (extrait)")
|
||||
.description("Système léger et narratif, résolution rapide des combats.")
|
||||
.author("LoreMind seed")
|
||||
.author(AUTHOR_SEED)
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(NIMBLE_RULES)
|
||||
.characterTemplate(nimbleCharacterTemplate())
|
||||
@@ -90,7 +94,7 @@ public class GameSystemSeeder {
|
||||
GameSystem.builder()
|
||||
.name("D&D 5e SRD (extrait)")
|
||||
.description("Extrait libre des bases du System Reference Document 5.1.")
|
||||
.author("LoreMind seed")
|
||||
.author(AUTHOR_SEED)
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(DND_SRD_RULES)
|
||||
.characterTemplate(dndCharacterTemplate())
|
||||
@@ -99,7 +103,7 @@ public class GameSystemSeeder {
|
||||
GameSystem.builder()
|
||||
.name("Homebrew Exemple")
|
||||
.description("Template minimaliste à dupliquer pour créer votre propre système.")
|
||||
.author("LoreMind seed")
|
||||
.author(AUTHOR_SEED)
|
||||
.isPublic(false)
|
||||
.rulesMarkdown(HOMEBREW_EXAMPLE)
|
||||
.characterTemplate(genericCharacterTemplate())
|
||||
@@ -113,10 +117,10 @@ public class GameSystemSeeder {
|
||||
/** Template generique PJ — utilise pour Homebrew, backfill, et fallback. */
|
||||
private static List<TemplateField> genericCharacterTemplate() {
|
||||
return List.of(
|
||||
TemplateField.text("Histoire"),
|
||||
TemplateField.text(FIELD_HISTOIRE),
|
||||
TemplateField.text("Personnalite"),
|
||||
TemplateField.text("Apparence"),
|
||||
TemplateField.image("Galerie", ImageLayout.GALLERY),
|
||||
TemplateField.image(FIELD_GALERIE, ImageLayout.GALLERY),
|
||||
TemplateField.text("Notes")
|
||||
);
|
||||
}
|
||||
@@ -137,9 +141,9 @@ public class GameSystemSeeder {
|
||||
TemplateField.number("Blessures graves max"),
|
||||
TemplateField.text("Capacites de classe"),
|
||||
TemplateField.text("Equipement"),
|
||||
TemplateField.text("Histoire"),
|
||||
TemplateField.text(FIELD_HISTOIRE),
|
||||
TemplateField.text("Objectifs personnels"),
|
||||
TemplateField.image("Galerie", ImageLayout.GALLERY)
|
||||
TemplateField.image(FIELD_GALERIE, ImageLayout.GALLERY)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -157,8 +161,8 @@ public class GameSystemSeeder {
|
||||
TemplateField.text("Competences"),
|
||||
TemplateField.text("Equipement"),
|
||||
TemplateField.text("Sorts"),
|
||||
TemplateField.text("Histoire"),
|
||||
TemplateField.image("Galerie", ImageLayout.GALLERY)
|
||||
TemplateField.text(FIELD_HISTOIRE),
|
||||
TemplateField.image(FIELD_GALERIE, ImageLayout.GALLERY)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.persistence.converter;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
/**
|
||||
* Convertit la fiche {@link CampaignPublication} en JSON stocké dans une colonne TEXT,
|
||||
* et inversement. Fiche vide → NULL en base. Champs inconnus ignorés (fiche écrite par
|
||||
* une version plus récente).
|
||||
*/
|
||||
@Converter
|
||||
public class CampaignPublicationJsonConverter implements AttributeConverter<CampaignPublication, String> {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(CampaignPublication attribute) {
|
||||
if (attribute == null || !attribute.hasContent()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.writeValueAsString(attribute);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur sérialisation CampaignPublication → JSON", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CampaignPublication convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readValue(dbData, CampaignPublication.class);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur désérialisation JSON → CampaignPublication", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -32,8 +33,11 @@ public class MapJsonConverter implements AttributeConverter<Map<String, Object>,
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Object> convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null) {
|
||||
return null;
|
||||
// Map vide (mutable) plutôt que null : les consommateurs itèrent/écrivent
|
||||
// sans avoir à se défendre contre le null (même contrat que les autres
|
||||
// converters de ce package).
|
||||
if (dbData == null || dbData.isBlank()) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(dbData, Map.class);
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.persistence.converter;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
/**
|
||||
* Convertit la fiche {@link NpcStory} (rôle dans l'histoire d'un PNJ) en JSON stocké dans une colonne TEXT,
|
||||
* et inversement. Fiche vide → NULL en base. Champs inconnus ignorés (fiche écrite par
|
||||
* une version plus récente).
|
||||
*/
|
||||
@Converter
|
||||
public class NpcStoryJsonConverter implements AttributeConverter<NpcStory, String> {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(NpcStory attribute) {
|
||||
if (attribute == null || !attribute.hasContent()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.writeValueAsString(attribute);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur sérialisation NpcStory → JSON", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public NpcStory convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readValue(dbData, NpcStory.class);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur désérialisation JSON → NpcStory", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+97
-65
@@ -60,71 +60,8 @@ public class TemplateFieldListJsonConverter
|
||||
}
|
||||
List<TemplateField> result = new ArrayList<>();
|
||||
for (JsonNode item : root) {
|
||||
if (item.isTextual()) {
|
||||
// Format legacy : chaine simple, on suppose TEXT par defaut.
|
||||
// L'id stable est retro-rempli avec le nom (les valeurs de Page
|
||||
// sont deja rangees par nom -> id == name, aucune migration).
|
||||
String name = item.asText();
|
||||
TemplateField legacy = TemplateField.text(name);
|
||||
legacy.setId(name);
|
||||
result.add(legacy);
|
||||
} else if (item.isObject()) {
|
||||
// Nouveau format : {id?, name, type, layout?, labels?, foundryPath?, pos?}
|
||||
String name = item.path("name").asText(null);
|
||||
String typeStr = item.path("type").asText("TEXT");
|
||||
FieldType type;
|
||||
try {
|
||||
type = FieldType.valueOf(typeStr);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
// Type inconnu (ajoute par une version future) : fallback TEXT.
|
||||
type = FieldType.TEXT;
|
||||
}
|
||||
ImageLayout layout = null;
|
||||
if (type == FieldType.IMAGE) {
|
||||
String layoutStr = item.path("layout").asText(null);
|
||||
if (layoutStr != null && !layoutStr.isBlank()) {
|
||||
try {
|
||||
layout = ImageLayout.valueOf(layoutStr);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
// Layout inconnu : on laisse null → rendu GALLERY par defaut cote UI.
|
||||
layout = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> labels = null;
|
||||
if (type == FieldType.KEY_VALUE_LIST || type == FieldType.TABLE) {
|
||||
JsonNode labelsNode = item.path("labels");
|
||||
if (labelsNode.isArray()) {
|
||||
labels = new ArrayList<>();
|
||||
for (JsonNode label : labelsNode) {
|
||||
if (label.isTextual()) labels.add(label.asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
// foundryPath : lu via hasNonNull pour eviter le piege NullNode
|
||||
// (asText() renverrait la chaine "null"). Historiquement omis a la
|
||||
// relecture -> il etait perdu au save+reload : corrige ici.
|
||||
String foundryPath = item.hasNonNull("foundryPath")
|
||||
? item.get("foundryPath").asText() : null;
|
||||
// id : explicite si present, sinon retro-rempli avec le nom.
|
||||
String id = item.hasNonNull("id") ? item.get("id").asText() : null;
|
||||
if (id == null || id.isBlank()) {
|
||||
id = name;
|
||||
}
|
||||
BlockPosition pos = readPos(item.path("pos"));
|
||||
if (name != null && !name.isBlank()) {
|
||||
result.add(TemplateField.builder()
|
||||
.id(id)
|
||||
.name(name)
|
||||
.type(type)
|
||||
.layout(layout)
|
||||
.labels(labels)
|
||||
.foundryPath(foundryPath)
|
||||
.pos(pos)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
// Autres types de noeuds (nombre, booleen...) : ignores silencieusement.
|
||||
TemplateField field = parseField(item);
|
||||
if (field != null) result.add(field);
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
@@ -133,6 +70,101 @@ public class TemplateFieldListJsonConverter
|
||||
}
|
||||
}
|
||||
|
||||
/** Un element du tableau JSON -> TemplateField, ou null si non convertible (ignore). */
|
||||
private static TemplateField parseField(JsonNode item) {
|
||||
if (item.isTextual()) {
|
||||
return parseLegacyField(item.asText());
|
||||
}
|
||||
if (item.isObject()) {
|
||||
return parseObjectField(item);
|
||||
}
|
||||
// Autres types de noeuds (nombre, booleen...) : ignores silencieusement.
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format legacy : chaine simple, on suppose TEXT par defaut. L'id stable est
|
||||
* retro-rempli avec le nom (les valeurs de Page sont deja rangees par nom ->
|
||||
* id == name, aucune migration).
|
||||
*/
|
||||
private static TemplateField parseLegacyField(String name) {
|
||||
TemplateField legacy = TemplateField.text(name);
|
||||
legacy.setId(name);
|
||||
return legacy;
|
||||
}
|
||||
|
||||
/** Nouveau format : {id?, name, type, layout?, labels?, foundryPath?, pos?}. Null si nom vide. */
|
||||
private static TemplateField parseObjectField(JsonNode item) {
|
||||
String name = item.path("name").asText(null);
|
||||
if (name == null || name.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
FieldType type = parseType(item.path("type").asText("TEXT"));
|
||||
// foundryPath : lu via hasNonNull pour eviter le piege NullNode
|
||||
// (asText() renverrait la chaine "null"). Historiquement omis a la
|
||||
// relecture -> il etait perdu au save+reload : corrige ici.
|
||||
String foundryPath = item.hasNonNull("foundryPath")
|
||||
? item.get("foundryPath").asText() : null;
|
||||
// id : explicite si present, sinon retro-rempli avec le nom.
|
||||
String id = item.hasNonNull("id") ? item.get("id").asText() : null;
|
||||
if (id == null || id.isBlank()) {
|
||||
id = name;
|
||||
}
|
||||
return TemplateField.builder()
|
||||
.id(id)
|
||||
.name(name)
|
||||
.type(type)
|
||||
.layout(parseLayout(item, type))
|
||||
.labels(parseLabels(item, type))
|
||||
.foundryPath(foundryPath)
|
||||
.pos(readPos(item.path("pos")))
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Type du champ ; fallback TEXT si inconnu (ajoute par une version future). */
|
||||
private static FieldType parseType(String typeStr) {
|
||||
try {
|
||||
return FieldType.valueOf(typeStr);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return FieldType.TEXT;
|
||||
}
|
||||
}
|
||||
|
||||
/** Layout d'un champ IMAGE ; null si absent/inconnu (-> rendu GALLERY par defaut cote UI). */
|
||||
private static ImageLayout parseLayout(JsonNode item, FieldType type) {
|
||||
if (type != FieldType.IMAGE) {
|
||||
return null;
|
||||
}
|
||||
String layoutStr = item.path("layout").asText(null);
|
||||
if (layoutStr == null || layoutStr.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return ImageLayout.valueOf(layoutStr);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Libelles d'un champ KEY_VALUE_LIST/TABLE ; null pour les autres types. */
|
||||
// S1168 : null est ici SEMANTIQUE ("champ sans libelles"), distinct d'une liste vide —
|
||||
// le JSON persiste ecrit "labels":null (compat ascendante) et le front distingue null/[].
|
||||
@SuppressWarnings("java:S1168")
|
||||
private static List<String> parseLabels(JsonNode item, FieldType type) {
|
||||
if (type != FieldType.KEY_VALUE_LIST && type != FieldType.TABLE) {
|
||||
return null;
|
||||
}
|
||||
JsonNode labelsNode = item.path("labels");
|
||||
if (!labelsNode.isArray()) {
|
||||
return null;
|
||||
}
|
||||
List<String> labels = new ArrayList<>();
|
||||
for (JsonNode label : labelsNode) {
|
||||
if (label.isTextual()) labels.add(label.asText());
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit le placement {@code pos: {x, y, w, h}} d'un bloc. Renvoie null si le
|
||||
* noeud n'est pas un objet ou si toutes les coordonnees sont absentes
|
||||
|
||||
+10
-3
@@ -9,6 +9,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -71,6 +72,12 @@ public class ArcJpaEntity {
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String resolution;
|
||||
|
||||
@Column(name = "hidden_truth", columnDefinition = "TEXT")
|
||||
private String hiddenTruth;
|
||||
|
||||
@Column(name = "hooks", columnDefinition = "TEXT")
|
||||
private String hooks;
|
||||
|
||||
/**
|
||||
* IDs des pages du Lore liées à cet arc, stockés en JSON dans une colonne TEXT.
|
||||
* Pas de FK cross-context : respect des Bounded Contexts.
|
||||
@@ -94,12 +101,12 @@ public class ArcJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+11
-3
@@ -1,11 +1,14 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.infrastructure.persistence.converter.CampaignPublicationJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la persistance des Campaigns en base de données PostgreSQL.
|
||||
@@ -62,14 +65,19 @@ public class CampaignJpaEntity {
|
||||
@Column(name = "graph_positions", columnDefinition = "TEXT")
|
||||
private String graphPositions;
|
||||
|
||||
/** Fiche « Publication » (JSON). NULL = jamais renseignée. */
|
||||
@Column(name = "publication", columnDefinition = "TEXT")
|
||||
@Convert(converter = CampaignPublicationJsonConverter.class)
|
||||
private CampaignPublication publication;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = createdAt;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -68,12 +69,12 @@ public class ChapterJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -10,6 +10,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -81,8 +82,8 @@ public class CharacterJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
if (values == null) values = new HashMap<>();
|
||||
if (imageValues == null) imageValues = new HashMap<>();
|
||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||
@@ -90,6 +91,6 @@ public class CharacterJpaEntity {
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -8,6 +8,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la persistance des Horloges (Clocks) en PostgreSQL.
|
||||
@@ -64,13 +65,13 @@ public class ClockJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -19,6 +19,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -77,13 +78,13 @@ public class ConversationJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -16,6 +16,7 @@ import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Persistance d'un message appartenant a une {@link ConversationJpaEntity}.
|
||||
@@ -54,6 +55,6 @@ public class ConversationMessageJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -10,6 +10,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -83,8 +84,8 @@ public class EnemyJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = createdAt;
|
||||
if (values == null) values = new HashMap<>();
|
||||
if (imageValues == null) imageValues = new HashMap<>();
|
||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||
@@ -92,6 +93,6 @@ public class EnemyJpaEntity {
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la persistance des Fronts en PostgreSQL.
|
||||
@@ -44,13 +45,13 @@ public class FrontJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -9,6 +9,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -69,8 +70,8 @@ public class GameSystemJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = createdAt;
|
||||
if (characterTemplate == null) characterTemplate = new ArrayList<>();
|
||||
if (npcTemplate == null) npcTemplate = new ArrayList<>();
|
||||
if (enemyTemplate == null) enemyTemplate = new ArrayList<>();
|
||||
@@ -78,6 +79,6 @@ public class GameSystemJpaEntity {
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Entite JPA pour les metadonnees d'images en PostgreSQL.
|
||||
@@ -43,7 +44,7 @@ public class ImageJpaEntity {
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (uploadedAt == null) {
|
||||
uploadedAt = LocalDateTime.now();
|
||||
uploadedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -60,12 +61,12 @@ public class ItemCatalogJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -6,6 +6,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la persistance des Lores en base de données PostgreSQL.
|
||||
@@ -43,12 +44,12 @@ public class LoreJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -6,6 +6,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la persistance des LoreNodes en base de données PostgreSQL.
|
||||
@@ -48,12 +49,12 @@ public class LoreNodeJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
@Entity
|
||||
@Table(name = "notebooks", indexes = {
|
||||
@@ -36,12 +37,12 @@ public class NotebookJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
@Entity
|
||||
@Table(name = "notebook_messages", indexes = {
|
||||
@@ -44,6 +45,6 @@ public class NotebookMessageJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) createdAt = LocalDateTime.now();
|
||||
if (createdAt == null) createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
@Entity
|
||||
@Table(name = "notebook_sources", indexes = {
|
||||
@@ -42,6 +43,6 @@ public class NotebookSourceJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) createdAt = LocalDateTime.now();
|
||||
if (createdAt == null) createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -66,6 +67,11 @@ public class NpcJpaEntity {
|
||||
@Column(name = "\"order\"", nullable = false)
|
||||
private int order;
|
||||
|
||||
/** Fiche « rôle dans l'histoire » (JSON). NULL = non renseignée. */
|
||||
@Column(name = "story", columnDefinition = "TEXT")
|
||||
@Convert(converter = com.loremind.infrastructure.persistence.converter.NpcStoryJsonConverter.class)
|
||||
private com.loremind.domain.campaigncontext.bestiary.NpcStory story;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@@ -74,8 +80,8 @@ public class NpcJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
if (values == null) values = new HashMap<>();
|
||||
if (imageValues == null) imageValues = new HashMap<>();
|
||||
if (keyValueValues == null) keyValueValues = new HashMap<>();
|
||||
@@ -83,6 +89,6 @@ public class NpcJpaEntity {
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -14,6 +14,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -94,12 +95,12 @@ public class PageJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* Entité JPA pour la table {@code playthroughs} — instances jouées d'une Campagne.
|
||||
@@ -43,12 +44,12 @@ public class PlaythroughJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -11,6 +11,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -90,12 +91,12 @@ public class QuestJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@ import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -62,12 +63,12 @@ public class RandomTableJpaEntity {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user