Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac7648f9fe | ||
|
|
d9a90f8412 | ||
|
|
2e9632de49 | ||
|
|
fbb1956e17 | ||
|
|
8c6b642975 | ||
|
|
d926545e3d | ||
|
|
b323c681f8 | ||
|
|
e7063b31e3 | ||
|
|
ab658f27b0 | ||
|
|
c2947cfef8 | ||
|
|
67ac4cc68f | ||
|
|
c2f162d823 | ||
|
|
ad3ea0e9e6 | ||
|
|
0c44e42a22 | ||
|
|
1c8b24c5dd | ||
|
|
177967af55 | ||
|
|
42c4b53ced | ||
|
|
3e9e828225 |
@@ -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/
|
||||
|
||||
@@ -6,7 +6,9 @@ name: Qualité & Sécurité
|
||||
# assainie, on pourra l'ajouter aux checks requis de la branch protection.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# 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]
|
||||
|
||||
@@ -27,11 +29,14 @@ jobs:
|
||||
- name: MegaLinter
|
||||
uses: oxsecurity/megalinter/flavors/cupcake@v9
|
||||
env:
|
||||
# push sur main → tout le dépôt ; PR → seulement les fichiers modifiés.
|
||||
VALIDATE_ALL_CODEBASE: ${{ github.event_name == 'push' }}
|
||||
# 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@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: megalinter-reports
|
||||
path: megalinter-reports/
|
||||
@@ -61,17 +66,39 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -35,3 +35,9 @@ 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.2-beta",
|
||||
version="1.3.0-beta",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
+14
-1
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>1.0.2-beta</version>
|
||||
<version>1.3.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>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
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)
|
||||
*/
|
||||
public record GuidedSkeleton(
|
||||
String arcId,
|
||||
String newArcName,
|
||||
ChapterSpec chapter,
|
||||
List<SceneSpec> scenes,
|
||||
boolean linkSequentially,
|
||||
String linkLabel
|
||||
) {
|
||||
|
||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||
}
|
||||
|
||||
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. */
|
||||
public record Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
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 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;
|
||||
|
||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
ArcService arcService,
|
||||
ChapterService chapterService,
|
||||
SceneService sceneService) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.arcService = arcService;
|
||||
this.chapterService = chapterService;
|
||||
this.sceneService = sceneService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
List<GuidedSkeleton.SceneSpec> specs = skeleton.scenes().stream()
|
||||
.filter(s -> s != null && !isBlank(s.name()))
|
||||
.toList();
|
||||
|
||||
String arcId = resolveArc(campaignId, skeleton);
|
||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||
|
||||
List<Scene> scenes = new ArrayList<>();
|
||||
int order = 0;
|
||||
for (GuidedSkeleton.SceneSpec spec : specs) {
|
||||
scenes.add(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()));
|
||||
}
|
||||
|
||||
if (skeleton.linkSequentially()) {
|
||||
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||
}
|
||||
|
||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList());
|
||||
}
|
||||
|
||||
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()))
|
||||
.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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
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.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.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.ArrayList;
|
||||
import java.util.Comparator;
|
||||
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 chemins menant à une révélation (en deçà : un seul chemin). */
|
||||
static final int REVELATION_MIN_INCOMING = 2;
|
||||
/** 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;
|
||||
|
||||
public WritingReviewService(CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
QuestRepository questRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.questRepository = questRepository;
|
||||
}
|
||||
|
||||
/** 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-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);
|
||||
}
|
||||
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);
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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;
|
||||
long incoming = chapterScenes.stream()
|
||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||
.flatMap(s -> s.getBranches().stream().map(SceneBranch::targetSceneId).distinct())
|
||||
.filter(scene.getId()::equals)
|
||||
.count();
|
||||
if (incoming < REVELATION_MIN_INCOMING) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("incoming", String.valueOf(incoming))));
|
||||
}
|
||||
}
|
||||
|
||||
/** 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())) {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers ----------------------------------------------------------------------------
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
) {
|
||||
}
|
||||
+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
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Entité JPA du réglage d'accès distant (migration V25). Singleton : une seule ligne,
|
||||
* {@code id = "current"}, comme la licence.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "remote_access_config")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RemoteAccessConfigJpaEntity {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean enabled;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int port;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Entité JPA d'un appareil appairé pour l'accès distant (migration V25). */
|
||||
@Entity
|
||||
@Table(name = "remote_devices")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RemoteDeviceJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String name;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, length = 64, unique = true)
|
||||
private String tokenHash;
|
||||
|
||||
@Column(name = "user_agent", length = 300)
|
||||
private String userAgent;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "last_seen_at")
|
||||
private Instant lastSeenAt;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteAccessConfigJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface RemoteAccessConfigJpaRepository extends JpaRepository<RemoteAccessConfigJpaEntity, String> {
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteDeviceJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface RemoteDeviceJpaRepository extends JpaRepository<RemoteDeviceJpaEntity, Long> {
|
||||
|
||||
Optional<RemoteDeviceJpaEntity> findByTokenHash(String tokenHash);
|
||||
|
||||
/** Mise à jour ciblée (pas de relecture de l'entité à chaque requête d'une tablette). */
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("update RemoteDeviceJpaEntity d set d.lastSeenAt = :seenAt where d.id = :id")
|
||||
void touch(@Param("id") Long id, @Param("seenAt") Instant seenAt);
|
||||
}
|
||||
+2
@@ -17,5 +17,7 @@ public interface SessionJpaRepository extends JpaRepository<SessionJpaEntity, Lo
|
||||
|
||||
Optional<SessionJpaEntity> findFirstByEndedAtIsNull();
|
||||
|
||||
List<SessionJpaEntity> findByEndedAtIsNullOrderByStartedAtDesc();
|
||||
|
||||
Optional<SessionJpaEntity> findFirstByPlaythroughIdAndEndedAtIsNull(Long playthroughId);
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteAccessConfigJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.RemoteAccessConfigJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class PostgresRemoteAccessConfigRepository implements RemoteAccessConfigRepository {
|
||||
|
||||
static final String CURRENT_ID = "current";
|
||||
|
||||
private final RemoteAccessConfigJpaRepository jpa;
|
||||
|
||||
public PostgresRemoteAccessConfigRepository(RemoteAccessConfigJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RemoteAccessConfig> find() {
|
||||
return jpa.findById(CURRENT_ID).map(e -> new RemoteAccessConfig(e.isEnabled(), e.getPort()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoteAccessConfig save(RemoteAccessConfig config) {
|
||||
jpa.save(RemoteAccessConfigJpaEntity.builder()
|
||||
.id(CURRENT_ID)
|
||||
.enabled(config.enabled())
|
||||
.port(config.port())
|
||||
.updatedAt(Instant.now())
|
||||
.build());
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteDeviceJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.RemoteDeviceJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class PostgresRemoteDeviceRepository implements RemoteDeviceRepository {
|
||||
|
||||
private final RemoteDeviceJpaRepository jpa;
|
||||
|
||||
public PostgresRemoteDeviceRepository(RemoteDeviceJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoteDevice save(RemoteDevice device) {
|
||||
RemoteDeviceJpaEntity entity = RemoteDeviceJpaEntity.builder()
|
||||
.id(device.getId() != null ? Long.parseLong(device.getId()) : null)
|
||||
.name(device.getName())
|
||||
.tokenHash(device.getTokenHash())
|
||||
.userAgent(device.getUserAgent())
|
||||
.createdAt(device.getCreatedAt() != null ? device.getCreatedAt() : Instant.now())
|
||||
.lastSeenAt(device.getLastSeenAt())
|
||||
.build();
|
||||
return toDomain(jpa.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RemoteDevice> findByTokenHash(String tokenHash) {
|
||||
return jpa.findByTokenHash(tokenHash).map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RemoteDevice> findAll() {
|
||||
return jpa.findAll().stream().map(this::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void touch(String id, Instant lastSeenAt) {
|
||||
jpa.touch(Long.parseLong(id), lastSeenAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteById(String id) {
|
||||
Long key = Long.parseLong(id);
|
||||
if (!jpa.existsById(key)) return false;
|
||||
jpa.deleteById(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
private RemoteDevice toDomain(RemoteDeviceJpaEntity e) {
|
||||
return RemoteDevice.builder()
|
||||
.id(String.valueOf(e.getId()))
|
||||
.name(e.getName())
|
||||
.tokenHash(e.getTokenHash())
|
||||
.userAgent(e.getUserAgent())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.lastSeenAt(e.getLastSeenAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+7
@@ -52,6 +52,13 @@ public class PostgresSessionRepository implements SessionRepository {
|
||||
return jpaRepository.findFirstByEndedAtIsNull().map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Session> findAllActive() {
|
||||
return jpaRepository.findByEndedAtIsNullOrderByStartedAtDesc().stream()
|
||||
.map(this::toDomain)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Session> findActiveByPlaythroughId(String playthroughId) {
|
||||
return jpaRepository.findFirstByPlaythroughIdAndEndedAtIsNull(Long.parseLong(playthroughId))
|
||||
|
||||
+31
-1
@@ -3,6 +3,9 @@ package com.loremind.infrastructure.transfer.foundry;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||
@@ -40,6 +43,7 @@ public class FoundryExportService {
|
||||
private final CampaignJpaRepository campaignRepo;
|
||||
private final ArcJpaRepository arcRepo;
|
||||
private final ChapterJpaRepository chapterRepo;
|
||||
private final QuestJpaRepository questRepo;
|
||||
private final SceneJpaRepository sceneRepo;
|
||||
private final NpcJpaRepository npcRepo;
|
||||
private final EnemyJpaRepository enemyRepo;
|
||||
@@ -55,6 +59,7 @@ public class FoundryExportService {
|
||||
public FoundryExportService(CampaignJpaRepository campaignRepo,
|
||||
ArcJpaRepository arcRepo,
|
||||
ChapterJpaRepository chapterRepo,
|
||||
QuestJpaRepository questRepo,
|
||||
SceneJpaRepository sceneRepo,
|
||||
NpcJpaRepository npcRepo,
|
||||
EnemyJpaRepository enemyRepo,
|
||||
@@ -69,6 +74,7 @@ public class FoundryExportService {
|
||||
this.campaignRepo = campaignRepo;
|
||||
this.arcRepo = arcRepo;
|
||||
this.chapterRepo = chapterRepo;
|
||||
this.questRepo = questRepo;
|
||||
this.sceneRepo = sceneRepo;
|
||||
this.npcRepo = npcRepo;
|
||||
this.enemyRepo = enemyRepo;
|
||||
@@ -154,7 +160,20 @@ public class FoundryExportService {
|
||||
List<FoundryBundle.Quest> quests = new ArrayList<>();
|
||||
List<FoundryBundle.Scene> scenes = new ArrayList<>();
|
||||
|
||||
Set<String> liveContainerIds = liveQuestContainerIds(campaign);
|
||||
for (ArcJpaEntity arc : sortByOrder(arcRepo.findByCampaignId(campaign.getId()), ArcJpaEntity::getOrder)) {
|
||||
List<ChapterJpaEntity> chapters = sortByOrder(chapterRepo.findByArcId(arc.getId()), ChapterJpaEntity::getOrder);
|
||||
// L'arc technique SYSTEM (« Quetes libres ») est masque dans l'appli : seuls
|
||||
// les conteneurs des quetes VIVANTES partent dans l'export. Un conteneur
|
||||
// orphelin (quete supprimee, chapitre garde par deleteQuest car il contenait
|
||||
// des scenes) est invisible cote LoreMind -> il ne doit pas reapparaitre
|
||||
// cote Foundry. Arc omis entierement s'il ne reste rien.
|
||||
if (arc.getType() == ArcType.SYSTEM) {
|
||||
chapters = chapters.stream()
|
||||
.filter(ch -> liveContainerIds.contains(str(ch.getId())))
|
||||
.toList();
|
||||
if (chapters.isEmpty()) continue;
|
||||
}
|
||||
// Sans journaux, arcs/quetes ne servent que d'ossature (dossiers des Scenes) :
|
||||
// leurs illustrations ne sont pas embarquees.
|
||||
arcs.add(new FoundryBundle.Arc(
|
||||
@@ -163,7 +182,7 @@ public class FoundryExportService {
|
||||
arc.getThemes(), arc.getStakes(), arc.getGmNotes(), arc.getRewards(), arc.getResolution(),
|
||||
opts.journals() ? assets.images(arc.getIllustrationImageIds()) : List.of()));
|
||||
|
||||
for (ChapterJpaEntity ch : sortByOrder(chapterRepo.findByArcId(arc.getId()), ChapterJpaEntity::getOrder)) {
|
||||
for (ChapterJpaEntity ch : chapters) {
|
||||
quests.add(new FoundryBundle.Quest(
|
||||
str(ch.getId()), str(arc.getId()), ch.getName(), ch.getDescription(), ch.getOrder(),
|
||||
ch.getIcon(), ch.getPlayerObjectives(), ch.getNarrativeStakes(), ch.getGmNotes(),
|
||||
@@ -177,6 +196,17 @@ public class FoundryExportService {
|
||||
return new ArcsQuestsScenes(arcs, quests, scenes);
|
||||
}
|
||||
|
||||
/** Ids des chapitres-conteneurs references par les quetes vivantes de la campagne. */
|
||||
private Set<String> liveQuestContainerIds(CampaignJpaEntity campaign) {
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (QuestJpaEntity q : questRepo.findByCampaignId(campaign.getId())) {
|
||||
for (QuestNodeRef n : q.getNodes() != null ? q.getNodes() : List.<QuestNodeRef>of()) {
|
||||
if (n.nodeType() == NodeType.CHAPTER) ids.add(n.nodeId());
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** PNJ : purement journal — hors perimetre sans les journaux. */
|
||||
private List<FoundryBundle.Persona> buildNpcs(CampaignJpaEntity campaign, ExportOptions opts,
|
||||
List<TemplateField> npcTemplate, AssetRegistry assets) {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Garde de l'accès distant (mode bureau). Ne concerne QUE les requêtes arrivées par le
|
||||
* connecteur réseau local (port dédié) : celles du connecteur habituel (127.0.0.1) passent
|
||||
* sans changement.
|
||||
* <ul>
|
||||
* <li>front statique (hors {@code /api/}) : libre — la tablette doit pouvoir afficher l'écran d'appairage ;</li>
|
||||
* <li>{@code /api/config}, {@code /api/version}, appairage : libres ;</li>
|
||||
* <li>administration (Paramètres, données, mises à jour, licence) : refusée, toujours, même appairé ;</li>
|
||||
* <li>tout le reste de l'API : cookie d'appareil valide, sinon 401 {@code remote_pairing_required}.</li>
|
||||
* </ul>
|
||||
* Pas un {@code @Component} : instancié par {@link SecurityConfig} pour ne pas être enregistré
|
||||
* deux fois (chaîne de sécurité + filtre servlet automatique).
|
||||
*/
|
||||
public class RemoteAccessFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String DEVICE_COOKIE = "lm_device";
|
||||
|
||||
private static final List<String> PUBLIC_PATHS = List.of(
|
||||
"/api/config", "/api/version", "/api/remote-access/pair", "/api/remote-access/session");
|
||||
private static final List<String> LOCAL_ONLY_PREFIXES = List.of(
|
||||
"/api/settings", "/api/admin", "/api/license");
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemoteAccessFilter(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
if (!isFromLan(request, remoteAccessService.lanPort())) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String path = request.getRequestURI();
|
||||
if (!path.startsWith("/api/") || PUBLIC_PATHS.contains(path)) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
if (LOCAL_ONLY_PREFIXES.stream().anyMatch(path::startsWith)) {
|
||||
reject(response, HttpServletResponse.SC_FORBIDDEN, "remote_forbidden");
|
||||
return;
|
||||
}
|
||||
if (remoteAccessService.authenticate(deviceToken(request)).isPresent()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
reject(response, HttpServletResponse.SC_UNAUTHORIZED, "remote_pairing_required");
|
||||
}
|
||||
|
||||
/** Arrivée par le connecteur réseau local ? (le port d'arrivée suffit : l'autre connecteur est sur 127.0.0.1). */
|
||||
public static boolean isFromLan(HttpServletRequest request, int lanPort) {
|
||||
return lanPort > 0 && request.getLocalPort() == lanPort;
|
||||
}
|
||||
|
||||
public static String deviceToken(HttpServletRequest request) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) return null;
|
||||
for (Cookie cookie : cookies) {
|
||||
if (DEVICE_COOKIE.equals(cookie.getName())) return cookie.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void reject(HttpServletResponse response, int status, String error) throws IOException {
|
||||
response.setStatus(status);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.getWriter().write("{\"error\":\"" + error + "\"}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -14,6 +16,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* Configuration Spring Security.
|
||||
@@ -24,6 +27,9 @@ import org.springframework.security.web.SecurityFilterChain;
|
||||
* l'UI elle-meme n'est pas authentifiee (trust model : reseau local ou
|
||||
* reverse-proxy front amont).
|
||||
* <p>
|
||||
* Mode bureau : l'acces depuis une tablette passe par un connecteur reseau dedie,
|
||||
* garde par {@link RemoteAccessFilter} (jeton d'appareil obtenu par code d'appairage).
|
||||
* <p>
|
||||
* Fail-closed : refuse de demarrer si admin.password n'est pas defini.
|
||||
*/
|
||||
@Configuration
|
||||
@@ -58,7 +64,15 @@ public class SecurityConfig {
|
||||
// S4502 : API stateless en HTTP Basic sans cookie — CSRF sans objet (voir javadoc de classe).
|
||||
@SuppressWarnings("java:S4502")
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
public SecurityFilterChain filterChain(HttpSecurity http,
|
||||
ObjectProvider<RemoteAccessService> remoteAccess) throws Exception {
|
||||
// Mode bureau : garde de l'accès distant (tablette sur le réseau local), placée AVANT
|
||||
// le HTTP Basic pour qu'un appareil du réseau ne puisse même pas tenter le mot de
|
||||
// passe admin. Absente en Docker (le service n'existe que sous le profil local).
|
||||
RemoteAccessService remoteAccessService = remoteAccess.getIfAvailable();
|
||||
if (remoteAccessService != null) {
|
||||
http.addFilterBefore(new RemoteAccessFilter(remoteAccessService), BasicAuthenticationFilter.class);
|
||||
}
|
||||
http
|
||||
// API stateless : pas de session, pas de cookie => CSRF sans objet.
|
||||
// Les credentials HTTP Basic sont envoyes a chaque requete, donc
|
||||
|
||||
+14
-2
@@ -13,15 +13,18 @@ import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.RandomTableRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ArcDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ChapterDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.QuestDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.RandomTableDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.SceneDTO;
|
||||
import com.loremind.infrastructure.web.dto.playcontext.PlaythroughDTO;
|
||||
import com.loremind.infrastructure.web.mapper.ArcMapper;
|
||||
import com.loremind.infrastructure.web.mapper.ChapterMapper;
|
||||
import com.loremind.infrastructure.web.mapper.NpcMapper;
|
||||
import com.loremind.infrastructure.web.mapper.PlaythroughMapper;
|
||||
import com.loremind.infrastructure.web.mapper.QuestMapper;
|
||||
import com.loremind.infrastructure.web.mapper.RandomTableMapper;
|
||||
import com.loremind.infrastructure.web.mapper.SceneMapper;
|
||||
@@ -37,7 +40,7 @@ import java.util.Map;
|
||||
|
||||
/**
|
||||
* Endpoint AGRÉGÉ de l'arbre de campagne : tout ce dont la sidebar a besoin en UNE
|
||||
* requête HTTP — arcs → chapitres → scènes, PNJ, tables, ennemis, quêtes et readiness.
|
||||
* requête HTTP — arcs → chapitres → scènes, PNJ, tables, ennemis, quêtes, parties et readiness.
|
||||
*
|
||||
* <p>Remplace la rafale d'appels du front (~1 + N arcs + M chapitres + 5 listes ≈ 15-20
|
||||
* requêtes À CHAQUE navigation) : la latence HTTP par appel dominait le temps de rendu
|
||||
@@ -56,6 +59,7 @@ public class CampaignTreeController {
|
||||
private final RandomTableRepository randomTableRepository;
|
||||
private final EnemyRepository enemyRepository;
|
||||
private final QuestRepository questRepository;
|
||||
private final PlaythroughRepository playthroughRepository;
|
||||
private final CampaignReadinessService readinessService;
|
||||
private final ArcMapper arcMapper;
|
||||
private final ChapterMapper chapterMapper;
|
||||
@@ -63,6 +67,7 @@ public class CampaignTreeController {
|
||||
private final NpcMapper npcMapper;
|
||||
private final RandomTableMapper randomTableMapper;
|
||||
private final QuestMapper questMapper;
|
||||
private final PlaythroughMapper playthroughMapper;
|
||||
|
||||
// S107 (trop de paramètres) : constructeur d'INJECTION pur, sans logique — l'endpoint
|
||||
// est un agrégat volontaire (une requête pour toute la sidebar), il consomme donc
|
||||
@@ -77,13 +82,15 @@ public class CampaignTreeController {
|
||||
RandomTableRepository randomTableRepository,
|
||||
EnemyRepository enemyRepository,
|
||||
QuestRepository questRepository,
|
||||
PlaythroughRepository playthroughRepository,
|
||||
CampaignReadinessService readinessService,
|
||||
ArcMapper arcMapper,
|
||||
ChapterMapper chapterMapper,
|
||||
SceneMapper sceneMapper,
|
||||
NpcMapper npcMapper,
|
||||
RandomTableMapper randomTableMapper,
|
||||
QuestMapper questMapper) {
|
||||
QuestMapper questMapper,
|
||||
PlaythroughMapper playthroughMapper) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
@@ -92,6 +99,7 @@ public class CampaignTreeController {
|
||||
this.randomTableRepository = randomTableRepository;
|
||||
this.enemyRepository = enemyRepository;
|
||||
this.questRepository = questRepository;
|
||||
this.playthroughRepository = playthroughRepository;
|
||||
this.readinessService = readinessService;
|
||||
this.arcMapper = arcMapper;
|
||||
this.chapterMapper = chapterMapper;
|
||||
@@ -99,6 +107,7 @@ public class CampaignTreeController {
|
||||
this.npcMapper = npcMapper;
|
||||
this.randomTableMapper = randomTableMapper;
|
||||
this.questMapper = questMapper;
|
||||
this.playthroughMapper = playthroughMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,6 +122,7 @@ public class CampaignTreeController {
|
||||
List<RandomTableDTO> randomTables,
|
||||
List<Enemy> enemies,
|
||||
List<QuestDTO> quests,
|
||||
List<PlaythroughDTO> playthroughs,
|
||||
CampaignReadinessAssessment readiness
|
||||
) {}
|
||||
|
||||
@@ -147,6 +157,8 @@ public class CampaignTreeController {
|
||||
enemyRepository.findByCampaignId(campaignId),
|
||||
questRepository.findByCampaignId(campaignId).stream()
|
||||
.map(questMapper::toDTO).toList(),
|
||||
playthroughRepository.findByCampaignId(campaignId).stream()
|
||||
.map(playthroughMapper::toDTO).toList(),
|
||||
readinessService.assess(campaignId)));
|
||||
}
|
||||
}
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.GuidedSkeleton;
|
||||
import com.loremind.application.campaigncontext.GuidedSkeletonService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller des méthodes guidées (Mentor d'écriture, phase M3) : persiste le
|
||||
* squelette (arc → chapitre → scènes) construit question par question par le MJ.
|
||||
*
|
||||
* <p>201 + ids créés ; 400 si le squelette est invalide ({@code GlobalExceptionHandler}) ;
|
||||
* 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/guided-skeleton")
|
||||
public class GuidedSkeletonController {
|
||||
|
||||
private final GuidedSkeletonService guidedSkeletonService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public GuidedSkeletonController(GuidedSkeletonService guidedSkeletonService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.guidedSkeletonService = guidedSkeletonService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<GuidedSkeleton.Result> create(@PathVariable String campaignId,
|
||||
@RequestBody GuidedSkeleton skeleton) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
// Squelette invalide : IllegalArgumentException → 400 via GlobalExceptionHandler.
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(guidedSkeletonService.create(campaignId, skeleton));
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,16 @@ public class QuestController {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/** Impact d'une suppression : scènes du conteneur (quête libre) qui partiront avec. */
|
||||
@GetMapping("/{questId}/deletion-impact")
|
||||
public ResponseEntity<QuestService.DeletionImpact> getDeletionImpact(@PathVariable String campaignId,
|
||||
@PathVariable String questId) {
|
||||
if (questService.getQuestById(questId).isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(questService.getDeletionImpact(questId));
|
||||
}
|
||||
|
||||
/** Réordonne les quêtes de la campagne : order = position. */
|
||||
@PutMapping("/reorder")
|
||||
public ResponseEntity<Void> reorder(@PathVariable String campaignId, @RequestBody ReorderRequest req) {
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.remoteaccess.NetworkReadiness;
|
||||
import com.loremind.application.remoteaccess.PairingCode;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessStatus;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Réglage de l'accès distant, côté PC (mode bureau). Sous {@code /api/settings} : réservé
|
||||
* à l'admin (HTTP Basic) ET à la machine elle-même ({@code RemoteAccessFilter} refuse ces
|
||||
* routes à tout appareil du réseau, même appairé). 404 en Docker (profil {@code local} absent).
|
||||
*/
|
||||
@RestController
|
||||
@Profile("local")
|
||||
@RequestMapping("/api/settings/remote-access")
|
||||
public class RemoteAccessAdminController {
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
private final HostNetworkAccess hostNetworkAccess;
|
||||
|
||||
public RemoteAccessAdminController(RemoteAccessService remoteAccessService, HostNetworkAccess hostNetworkAccess) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
this.hostNetworkAccess = hostNetworkAccess;
|
||||
}
|
||||
|
||||
public record ConfigureRequest(boolean enabled, int port) {}
|
||||
|
||||
/** Réponse du bouton « Autoriser dans le pare-feu » : ce qui s'est passé + le nouvel état. */
|
||||
public record FirewallFixResponse(HostNetworkAccess.FirewallFixOutcome outcome, NetworkReadiness readiness) {}
|
||||
|
||||
@GetMapping
|
||||
public RemoteAccessStatus status() {
|
||||
return remoteAccessService.status();
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public RemoteAccessStatus configure(@RequestBody ConfigureRequest request) {
|
||||
return remoteAccessService.configure(request.enabled(), request.port());
|
||||
}
|
||||
|
||||
@PostMapping("/pairing-code")
|
||||
public PairingCode newPairingCode() {
|
||||
return remoteAccessService.newPairingCode();
|
||||
}
|
||||
|
||||
/** Une tablette peut-elle joindre ce PC ? (type de réseau, règle du pare-feu) */
|
||||
@GetMapping("/network-check")
|
||||
public NetworkReadiness networkCheck() {
|
||||
return NetworkReadiness.evaluate(hostNetworkAccess.inspect(remoteAccessService.configuredPort()));
|
||||
}
|
||||
|
||||
/** Ajoute la règle du pare-feu ; attend la réponse de l'utilisateur à la confirmation Windows (UAC). */
|
||||
@PostMapping("/firewall-rule")
|
||||
public FirewallFixResponse allowThroughFirewall() {
|
||||
HostNetworkAccess.FirewallFixOutcome outcome = hostNetworkAccess.allowThroughFirewall();
|
||||
return new FirewallFixResponse(outcome, NetworkReadiness.evaluate(hostNetworkAccess.inspect(remoteAccessService.configuredPort())));
|
||||
}
|
||||
|
||||
/** Ouvre les réglages réseau de Windows (pour passer un Wi-Fi « Public » en « Privé »). */
|
||||
@PostMapping("/open-network-settings")
|
||||
public ResponseEntity<Void> openNetworkSettings() {
|
||||
hostNetworkAccess.openNetworkSettings();
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@DeleteMapping("/devices/{id}")
|
||||
public ResponseEntity<Void> revoke(@PathVariable String id) {
|
||||
return remoteAccessService.revoke(id) ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
/** Port occupé, accès non ouvert… : conflit d'état, message prêt à afficher. */
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public ResponseEntity<Map<String, String>> conflict(IllegalStateException e) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.remoteaccess.PairedDevice;
|
||||
import com.loremind.application.remoteaccess.PairingRejectedException;
|
||||
import com.loremind.application.remoteaccess.PairingResult;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.infrastructure.web.config.RemoteAccessFilter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Appairage d'une tablette (mode bureau) : seules routes d'API joignables depuis le réseau
|
||||
* sans jeton (avec {@code /api/config} et {@code /api/version}).
|
||||
* <p>
|
||||
* Le jeton est posé en cookie {@code HttpOnly} + {@code SameSite=Strict} : envoyé
|
||||
* automatiquement par le navigateur (y compris pour les {@code <img>}), illisible par le
|
||||
* JavaScript de la page, et jamais joint à une requête venue d'un autre site (anti-CSRF).
|
||||
*/
|
||||
@RestController
|
||||
@Profile("local")
|
||||
@RequestMapping("/api/remote-access")
|
||||
public class RemotePairingController {
|
||||
|
||||
static final Duration COOKIE_LIFETIME = Duration.ofDays(365);
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemotePairingController(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
public record PairRequest(String code, String deviceName) {}
|
||||
|
||||
/** Ce que le front a besoin de savoir pour décider d'afficher l'écran d'appairage. */
|
||||
public record SessionInfo(boolean remote, boolean paired, String deviceName) {}
|
||||
|
||||
@PostMapping("/pair")
|
||||
public ResponseEntity<PairedDevice> pair(@RequestBody PairRequest request,
|
||||
@RequestHeader(value = HttpHeaders.USER_AGENT, required = false) String userAgent) {
|
||||
PairingResult result = remoteAccessService.pair(request.code(), request.deviceName(), userAgent);
|
||||
ResponseCookie cookie = ResponseCookie.from(RemoteAccessFilter.DEVICE_COOKIE, result.token())
|
||||
.httpOnly(true)
|
||||
.sameSite("Strict")
|
||||
.path("/")
|
||||
.maxAge(COOKIE_LIFETIME)
|
||||
.build();
|
||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()).body(result.device());
|
||||
}
|
||||
|
||||
@GetMapping("/session")
|
||||
public SessionInfo session(HttpServletRequest request) {
|
||||
boolean remote = RemoteAccessFilter.isFromLan(request, remoteAccessService.lanPort());
|
||||
if (!remote) return new SessionInfo(false, true, null);
|
||||
Optional<RemoteDevice> device = remoteAccessService.authenticate(RemoteAccessFilter.deviceToken(request));
|
||||
return new SessionInfo(true, device.isPresent(), device.map(RemoteDevice::getName).orElse(null));
|
||||
}
|
||||
|
||||
@ExceptionHandler(PairingRejectedException.class)
|
||||
public ResponseEntity<Map<String, String>> rejected(PairingRejectedException e) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
+16
-4
@@ -56,11 +56,23 @@ public class SessionController {
|
||||
.orElse(ResponseEntity.noContent().build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Liste des sessions. {@code active=true} : uniquement celles en cours, toutes Parties
|
||||
* confondues, la plus récente d'abord (raccourci « Séance en cours » du menu, rafraîchi
|
||||
* à chaque navigation — évite de rapatrier tout l'historique).
|
||||
*/
|
||||
@GetMapping
|
||||
public ResponseEntity<List<SessionDTO>> getSessions(@RequestParam(value = "playthroughId", required = false) String playthroughId) {
|
||||
List<Session> sessions = (playthroughId == null || playthroughId.isBlank())
|
||||
? sessionService.getAll()
|
||||
: sessionService.getByPlaythroughId(playthroughId);
|
||||
public ResponseEntity<List<SessionDTO>> getSessions(
|
||||
@RequestParam(value = "playthroughId", required = false) String playthroughId,
|
||||
@RequestParam(value = "active", defaultValue = "false") boolean active) {
|
||||
List<Session> sessions;
|
||||
if (active) {
|
||||
sessions = sessionService.getAllActive();
|
||||
} else if (playthroughId == null || playthroughId.isBlank()) {
|
||||
sessions = sessionService.getAll();
|
||||
} else {
|
||||
sessions = sessionService.getByPlaythroughId(playthroughId);
|
||||
}
|
||||
List<SessionDTO> dtos = sessions.stream()
|
||||
.map(sessionMapper::toDTO)
|
||||
.toList();
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.WritingReviewReport;
|
||||
import com.loremind.application.campaigncontext.WritingReviewService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller de la relecture d'éditeur (Mentor d'écriture, phase M2) : conseils
|
||||
* d'auteur sur la qualité de l'écriture d'une campagne.
|
||||
*
|
||||
* <p>Read-model pur, toujours 200 quand la campagne existe (les remarques conseillent,
|
||||
* elles ne bloquent rien). 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/writing-review")
|
||||
public class WritingReviewController {
|
||||
|
||||
private final WritingReviewService writingReviewService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public WritingReviewController(WritingReviewService writingReviewService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.writingReviewService = writingReviewService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<WritingReviewReport> getWritingReview(@PathVariable String campaignId) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(writingReviewService.review(campaignId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package db.migration;
|
||||
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Nettoyage des CONTENEURS ORPHELINS des quêtes libres (arc technique SYSTEM).
|
||||
*
|
||||
* <p>Jusqu'à la 1.0.2, supprimer une quête libre GARDAIT son chapitre-conteneur
|
||||
* s'il contenait des scènes (garde anti-perte de contenu) — mais l'arc SYSTEM
|
||||
* étant masqué partout dans l'appli, ce contenu devenait INVISIBLE et
|
||||
* irrécupérable, tout en ressortant dans l'export Foundry (« quêtes fantômes »).
|
||||
* {@code QuestService.deleteQuest} cascade désormais ces conteneurs ; cette
|
||||
* migration répare l'existant SANS perte :</p>
|
||||
* <ul>
|
||||
* <li>conteneur orphelin AVEC scènes → une quête libre est RECRÉÉE dessus (même
|
||||
* nom que le chapitre) : le contenu redevient visible sous « Quêtes », et
|
||||
* l'utilisateur le garde ou le supprime via le flux normal (qui annonce
|
||||
* l'impact) ;</li>
|
||||
* <li>conteneur orphelin VIDE → supprimé (fantôme sans contenu).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>« Orphelin » = chapitre d'un arc SYSTEM dont l'id n'apparaît dans les
|
||||
* {@code nodes} d'AUCUNE quête de la campagne. Détection prudente par motif
|
||||
* {@code "nodeId":"<id>"} : une collision d'id avec un nœud SCENE fait considérer
|
||||
* le chapitre comme référencé → il est laissé en place (aucun risque de perte).</p>
|
||||
*
|
||||
* <p>Migration en Java (et non SQL) : la corrélation chapitre ↔ nodes JSON des
|
||||
* quêtes demande une itération par candidat, illisible en SQL portable H2/PG.</p>
|
||||
*/
|
||||
@SuppressWarnings("java:S101") // Nommage V24__... IMPOSE par la convention Flyway des migrations Java.
|
||||
public class V24__Reattach_orphan_free_quest_containers extends BaseJavaMigration {
|
||||
|
||||
private record Candidate(long chapterId, String name, long campaignId) {}
|
||||
|
||||
@Override
|
||||
public void migrate(Context context) throws Exception {
|
||||
Connection conn = context.getConnection();
|
||||
|
||||
List<Candidate> candidates = new ArrayList<>();
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT c.id, c.name, a.campaign_id FROM chapters c "
|
||||
+ "JOIN arcs a ON c.arc_id = a.id WHERE a.type = 'SYSTEM'");
|
||||
ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
candidates.add(new Candidate(rs.getLong(1), rs.getString(2), rs.getLong(3)));
|
||||
}
|
||||
}
|
||||
|
||||
for (Candidate ch : candidates) {
|
||||
if (isReferencedByAQuest(conn, ch)) continue; // conteneur d'une quête vivante
|
||||
if (countScenes(conn, ch.chapterId()) == 0) {
|
||||
deleteEmptyChapter(conn, ch.chapterId());
|
||||
} else {
|
||||
recreateFreeQuest(conn, ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isReferencedByAQuest(Connection conn, Candidate ch) throws Exception {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT COUNT(*) FROM quests WHERE campaign_id = ? AND nodes LIKE ?")) {
|
||||
ps.setLong(1, ch.campaignId());
|
||||
ps.setString(2, "%\"nodeId\":\"" + ch.chapterId() + "\"%");
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getLong(1) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int countScenes(Connection conn, long chapterId) throws Exception {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT COUNT(*) FROM scenes WHERE chapter_id = ?")) {
|
||||
ps.setLong(1, chapterId);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getInt(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteEmptyChapter(Connection conn, long chapterId) throws Exception {
|
||||
try (PreparedStatement ps = conn.prepareStatement("DELETE FROM chapters WHERE id = ?")) {
|
||||
ps.setLong(1, chapterId);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/** Recrée une quête LIBRE (arc_id NULL) pointant le conteneur, à la suite de l'ordre. */
|
||||
private void recreateFreeQuest(Connection conn, Candidate ch) throws Exception {
|
||||
int order;
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT COALESCE(MAX(\"order\"), -1) + 1 FROM quests WHERE campaign_id = ?")) {
|
||||
ps.setLong(1, ch.campaignId());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
order = rs.getInt(1);
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"INSERT INTO quests (campaign_id, \"order\", name, description, prerequisites, "
|
||||
+ "nodes, related_page_ids, illustration_image_ids, created_at, updated_at) "
|
||||
+ "VALUES (?, ?, ?, '', '[]', ?, '[]', '[]', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)")) {
|
||||
ps.setLong(1, ch.campaignId());
|
||||
ps.setInt(2, order);
|
||||
ps.setString(3, ch.name());
|
||||
ps.setString(4, "[{\"nodeType\":\"CHAPTER\",\"nodeId\":\"" + ch.chapterId() + "\",\"order\":0}]");
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
|
||||
-- remote_access_config : réglage singleton (id = 'current') — activé ou non, port réseau.
|
||||
-- remote_devices : appareils appairés par code ; seule l'EMPREINTE SHA-256 du jeton
|
||||
-- est stockée (le jeton lui-même ne vit que dans le cookie de l'appareil).
|
||||
-- Tables présentes partout (Docker compris) mais utilisées uniquement en mode bureau.
|
||||
-- Compatible Postgres et H2 (MODE=PostgreSQL).
|
||||
create table remote_access_config (
|
||||
id varchar(32) not null,
|
||||
enabled boolean not null,
|
||||
port integer not null,
|
||||
updated_at timestamp(6) with time zone not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table remote_devices (
|
||||
id bigint generated by default as identity,
|
||||
name varchar(100) not null,
|
||||
token_hash varchar(64) not null,
|
||||
user_agent varchar(300),
|
||||
created_at timestamp(6) with time zone not null,
|
||||
last_seen_at timestamp(6) with time zone,
|
||||
primary key (id)
|
||||
);
|
||||
create unique index ux_remote_device_token on remote_devices (token_hash);
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
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.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link GuidedSkeletonService} (Mentor d'écriture, phase M3) :
|
||||
* placement (nouvel arc / arc existant), champs reportés, chaînage des scènes, validations.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class GuidedSkeletonServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private ArcService arcService;
|
||||
@Mock private ChapterService chapterService;
|
||||
@Mock private SceneService sceneService;
|
||||
|
||||
@InjectMocks private GuidedSkeletonService service;
|
||||
|
||||
private final List<Scene> createdScenes = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void stubCreations() {
|
||||
AtomicInteger ids = new AtomicInteger();
|
||||
when(arcService.createArc(any(Arc.class))).thenAnswer(inv -> {
|
||||
Arc a = inv.getArgument(0);
|
||||
a.setId("new-arc");
|
||||
return a;
|
||||
});
|
||||
when(chapterService.createChapter(any(Chapter.class))).thenAnswer(inv -> {
|
||||
Chapter c = inv.getArgument(0);
|
||||
c.setId("new-chap");
|
||||
return c;
|
||||
});
|
||||
when(sceneService.createScene(any(Scene.class))).thenAnswer(inv -> {
|
||||
Scene s = inv.getArgument(0);
|
||||
s.setId("scene-" + ids.incrementAndGet());
|
||||
createdScenes.add(s);
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
private static GuidedSkeleton.SceneSpec room(String name, SceneType type) {
|
||||
return new GuidedSkeleton.SceneSpec(name, "Ce qui s'y passe", type, "La crypte",
|
||||
"Combattre ou négocier", "Le gardien protège son frère", null);
|
||||
}
|
||||
|
||||
private static GuidedSkeleton skeleton(String arcId, String newArcName, boolean link) {
|
||||
return new GuidedSkeleton(arcId, newArcName,
|
||||
new GuidedSkeleton.ChapterSpec("La crypte oubliée", "Une accroche", "Retrouver le reliquaire", "Le village sera maudit"),
|
||||
List.of(room("Salle 1", SceneType.ENCOUNTER), room("Salle 2", SceneType.LOCATION), room("Salle 3", SceneType.REVELATION)),
|
||||
link, "Vers la salle suivante");
|
||||
}
|
||||
|
||||
@Test
|
||||
void newArc_isLinear_andPlacedAfterVisibleArcs_beforeSystemArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build(),
|
||||
Arc.builder().id("a2").type(ArcType.HUB).order(1).build(),
|
||||
Arc.builder().id("sys").type(ArcType.SYSTEM).order(9999).build()));
|
||||
|
||||
GuidedSkeleton.Result result = service.create(CAMP, skeleton(null, "Les terres brûlées", false));
|
||||
|
||||
ArgumentCaptor<Arc> arc = ArgumentCaptor.forClass(Arc.class);
|
||||
verify(arcService).createArc(arc.capture());
|
||||
assertEquals(ArcType.LINEAR, arc.getValue().getType());
|
||||
assertEquals(2, arc.getValue().getOrder());
|
||||
assertEquals(CAMP, arc.getValue().getCampaignId());
|
||||
assertEquals("new-arc", result.arcId());
|
||||
assertEquals("new-chap", result.chapterId());
|
||||
assertEquals(List.of("scene-1", "scene-2", "scene-3"), result.sceneIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingArc_chapterAppendedAfterExistingChapters_withItsFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build()));
|
||||
when(chapterRepository.findByArcId("a1")).thenReturn(List.of(
|
||||
Chapter.builder().id("c1").arcId("a1").order(0).build(),
|
||||
Chapter.builder().id("c2").arcId("a1").order(3).build()));
|
||||
|
||||
service.create(CAMP, skeleton("a1", null, false));
|
||||
|
||||
verify(arcService, never()).createArc(any(Arc.class));
|
||||
ArgumentCaptor<Chapter> chapter = ArgumentCaptor.forClass(Chapter.class);
|
||||
verify(chapterService).createChapter(chapter.capture());
|
||||
assertEquals("a1", chapter.getValue().getArcId());
|
||||
assertEquals(4, chapter.getValue().getOrder());
|
||||
assertEquals("Retrouver le reliquaire", chapter.getValue().getPlayerObjectives());
|
||||
assertEquals("Le village sera maudit", chapter.getValue().getNarrativeStakes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scenes_keepOrderTypeAndFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", false));
|
||||
|
||||
assertEquals(3, createdScenes.size());
|
||||
Scene first = createdScenes.get(0);
|
||||
assertEquals(0, first.getOrder());
|
||||
assertEquals("new-chap", first.getChapterId());
|
||||
assertEquals(SceneType.ENCOUNTER, first.getType());
|
||||
assertEquals("La crypte", first.getLocation());
|
||||
assertEquals("Combattre ou négocier", first.getChoicesConsequences());
|
||||
assertEquals("Le gardien protège son frère", first.getGmSecretNotes());
|
||||
assertEquals(SceneType.REVELATION, createdScenes.get(2).getType());
|
||||
assertEquals(2, createdScenes.get(2).getOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkSequentially_chainsEachSceneToTheNext_lastHasNoExit() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", true));
|
||||
|
||||
verify(sceneRepository, times(2)).save(any(Scene.class));
|
||||
assertEquals("scene-2", createdScenes.get(0).getBranches().get(0).targetSceneId());
|
||||
assertEquals("Vers la salle suivante", createdScenes.get(0).getBranches().get(0).label());
|
||||
assertEquals("scene-3", createdScenes.get(1).getBranches().get(0).targetSceneId());
|
||||
assertTrue(createdScenes.get(2).getBranches() == null || createdScenes.get(2).getBranches().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unnamedScenes_areSkipped_andBlankFieldsStoredAsNull() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
GuidedSkeleton s = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", " ", null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("Salle", " ", null, "", null, null, null),
|
||||
new GuidedSkeleton.SceneSpec(" ", "ignorée", SceneType.EVENT, null, null, null, null)),
|
||||
false, null);
|
||||
|
||||
service.create(CAMP, s);
|
||||
|
||||
assertEquals(1, createdScenes.size());
|
||||
assertNull(createdScenes.get(0).getDescription());
|
||||
assertNull(createdScenes.get(0).getLocation());
|
||||
assertEquals(SceneType.GENERIC, createdScenes.get(0).getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_ambiguousPlacement() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("a1", "Arc", false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton(null, " ", false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_arcOfAnotherCampaign_orNonLinearArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("hub").type(ArcType.HUB).order(0).build()));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("ailleurs", null, false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("hub", null, false)));
|
||||
verify(chapterService, never()).createChapter(any(Chapter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_missingChapterName_orNoNamedScene() {
|
||||
GuidedSkeleton noChapterName = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec(" ", null, null, null), List.of(room("S", null)), false, null);
|
||||
GuidedSkeleton noScene = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", null, null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("", null, null, null, null, null, null)), false, null);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noChapterName));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noScene));
|
||||
}
|
||||
}
|
||||
@@ -230,13 +230,112 @@ class QuestServiceTest {
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-real").arcId("arc-lin").name("Réel").build()));
|
||||
when(arcRepository.findById("arc-lin"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-lin").type(ArcType.LINEAR).build()));
|
||||
when(sceneRepository.findByChapterId("chap-real")).thenReturn(List.of());
|
||||
// NB : pas de stub sceneRepository — un chapitre non-conteneur est écarté avant toute lecture des scènes.
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
verify(chapterRepository, never()).deleteById(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteQuest_freeQuest_cascadesScenesOfSystemContainer() {
|
||||
// Conteneur d'arc SYSTEM : INVISIBLE une fois la quête supprimée -> il part avec
|
||||
// ses scènes (sinon il pourrit en fantôme inaccessible qui ressort dans les exports).
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of());
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
when(sceneRepository.findByChapterId("chap-free")).thenReturn(List.of(
|
||||
Scene.builder().id("s-1").chapterId("chap-free").name("S1").build(),
|
||||
Scene.builder().id("s-2").chapterId("chap-free").name("S2").build()));
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
verify(sceneRepository).deleteById("s-1");
|
||||
verify(sceneRepository).deleteById("s-2");
|
||||
verify(chapterRepository).deleteById("chap-free");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_freeQuestWithScenes_countsThem() {
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(quest)); // filtrée par id
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
when(sceneRepository.findByChapterId("chap-free")).thenReturn(List.of(
|
||||
Scene.builder().id("s-1").chapterId("chap-free").name("S1").build(),
|
||||
Scene.builder().id("s-2").chapterId("chap-free").name("S2").build()));
|
||||
|
||||
assertEquals(2, service.getDeletionImpact("q-1").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_unknownQuest_returnsZero() {
|
||||
when(questRepository.findById("inconnue")).thenReturn(Optional.empty());
|
||||
|
||||
assertEquals(0, service.getDeletionImpact("inconnue").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_systemContainerReferencedByAnotherQuest_reportsZero() {
|
||||
// Conteneur PARTAGÉ (autre quête le référence) : il survivra -> impact 0.
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
Quest other = Quest.builder().id("q-2").campaignId("camp").name("Autre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(quest, other));
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
|
||||
assertEquals(0, service.getDeletionImpact("q-1").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteQuest_freeQuest_systemContainerReferencedElsewhere_keptWithScenes() {
|
||||
// Même partagé en arc SYSTEM, un conteneur encore référencé n'est JAMAIS cascadé.
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").name("Libre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
Quest other = Quest.builder().id("q-2").campaignId("camp").name("Autre")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-free", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(other));
|
||||
when(chapterRepository.findById("chap-free"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-free").arcId("arc-sys").name("Libre").build()));
|
||||
when(arcRepository.findById("arc-sys"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-sys").type(ArcType.SYSTEM).build()));
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
verify(chapterRepository, never()).deleteById(anyString());
|
||||
verify(sceneRepository, never()).deleteById(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionImpact_hubQuest_reportsZero() {
|
||||
// Jumeau de hub : GARDÉ à la suppression (il reste visible dans l'arc) -> impact 0.
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").arcId("arc-h").name("Q")
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, "chap-1", 0))).build();
|
||||
when(questRepository.findById("q-1")).thenReturn(Optional.of(quest));
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(quest));
|
||||
when(chapterRepository.findById("chap-1"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-1").arcId("arc-h").name("Q").build()));
|
||||
when(arcRepository.findById("arc-h"))
|
||||
.thenReturn(Optional.of(Arc.builder().id("arc-h").type(ArcType.HUB).build()));
|
||||
|
||||
assertEquals(0, service.getDeletionImpact("q-1").scenes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteQuest_keepsContainerReferencedByAnotherQuest() {
|
||||
Quest quest = Quest.builder().id("q-1").campaignId("camp").arcId("arc-h").name("Q")
|
||||
@@ -247,7 +346,7 @@ class QuestServiceTest {
|
||||
when(questRepository.findByCampaignId("camp")).thenReturn(List.of(other));
|
||||
when(chapterRepository.findById("chap-1"))
|
||||
.thenReturn(Optional.of(Chapter.builder().id("chap-1").arcId("arc-h").name("Q").build()));
|
||||
when(sceneRepository.findByChapterId("chap-1")).thenReturn(List.of());
|
||||
// NB : pas de stub sceneRepository — un conteneur encore référencé est écarté avant toute lecture.
|
||||
|
||||
service.deleteQuest("q-1");
|
||||
|
||||
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
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.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.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link WritingReviewService} (Mentor d'écriture, phase M2).
|
||||
* Chaque règle WRITE-xxx a son cas positif ET un cas qui ne doit PAS la déclencher
|
||||
* (le mentor doit rester sobre : un faux positif décourage le débutant).
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WritingReviewServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private CampaignRepository campaignRepository;
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private QuestRepository questRepository;
|
||||
|
||||
@InjectMocks private WritingReviewService service;
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
private static Arc arc(String id, ArcType type) {
|
||||
return Arc.builder().id(id).name(id).campaignId(CAMP).type(type).order(0).stakes("Le village brûle").build();
|
||||
}
|
||||
|
||||
private static Chapter chapter(String id, String arcId) {
|
||||
return Chapter.builder().id(id).name(id).arcId(arcId).order(0).narrativeStakes("Un allié en danger").build();
|
||||
}
|
||||
|
||||
/** Scène « propre » : typée, avec un choix décrit (ne déclenche aucune règle seule). */
|
||||
private static Scene.SceneBuilder scene(String id, int order) {
|
||||
return Scene.builder().id(id).name(id).chapterId("chap").order(order)
|
||||
.type(SceneType.NPC).choicesConsequences("Convaincre ou menacer");
|
||||
}
|
||||
|
||||
private void tree(Arc arc, Chapter chapter, List<Scene> scenes) {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(arc));
|
||||
when(chapterRepository.findByArcId(arc.getId())).thenReturn(List.of(chapter));
|
||||
when(sceneRepository.findByChapterId(chapter.getId())).thenReturn(scenes);
|
||||
}
|
||||
|
||||
private void tree(List<Scene> scenes) {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"), scenes);
|
||||
}
|
||||
|
||||
private Set<String> ruleIds() {
|
||||
return service.review(CAMP).remarks().stream().map(WritingRemark::ruleId).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private WritingRemark remark(String ruleId) {
|
||||
return service.review(CAMP).remarks().stream().filter(r -> r.ruleId().equals(ruleId))
|
||||
.findFirst().orElseThrow(() -> new AssertionError("Règle absente : " + ruleId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyCampaign_hasNoRemark() {
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wellWrittenChapter_hasNoRemark() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("s2", 1).type(SceneType.LOCATION).build()));
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
// --- WRITE-001 : couloir ---
|
||||
|
||||
@Test
|
||||
void corridor_threeScenesWithoutChoiceNorBranch() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).choicesConsequences(null).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-001-CORRIDOR");
|
||||
assertEquals(ReadinessEntityType.CHAPTER, r.entityType());
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void corridor_notRaised_whenOneSceneOffersAChoice() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-001-CORRIDOR"));
|
||||
}
|
||||
|
||||
// --- WRITE-002 : faux carrefour ---
|
||||
|
||||
@Test
|
||||
void fakeChoice_allBranchesLeadToSameScene() {
|
||||
Scene target = scene("s2", 1).name("La crypte").type(SceneType.LOCATION).build();
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s2"))).build(),
|
||||
target));
|
||||
|
||||
WritingRemark r = remark("WRITE-002-FAKE-CHOICE");
|
||||
assertEquals("s1", r.entityId());
|
||||
assertEquals("La crypte", r.params().get("target"));
|
||||
assertEquals("2", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fakeChoice_notRaised_whenBranchesDiverge() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s3"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-002-FAKE-CHOICE"));
|
||||
}
|
||||
|
||||
// --- WRITE-003 : révélation à chemin unique ---
|
||||
|
||||
@Test
|
||||
void singleClue_revelationReachableByOnePath() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
|
||||
assertEquals("1", remark("WRITE-003-SINGLE-CLUE").params().get("incoming"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_withTwoPaths_orInChapterWithoutLinks() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(SceneBranch.of("B", "rev"))).build(),
|
||||
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_inChapterWithoutAnyLink() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
// --- WRITE-004 : rythme monotone ---
|
||||
|
||||
@Test
|
||||
void monotonousPacing_threeFightsInARow() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).enemies("Deux gobelins").build(),
|
||||
scene("s3", 2).combatDifficulty("Difficile").build(),
|
||||
scene("s4", 3).type(SceneType.LOCATION).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-004-MONOTONOUS-PACING");
|
||||
assertEquals("COMBAT", r.params().get("kind"));
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void monotonousPacing_notRaised_whenVaried_orUntyped() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).type(SceneType.NPC).build(),
|
||||
scene("s3", 2).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s4", 3).type(SceneType.GENERIC).build(),
|
||||
scene("s5", 4).type(SceneType.GENERIC).build(),
|
||||
scene("s6", 5).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-004-MONOTONOUS-PACING"));
|
||||
}
|
||||
|
||||
// --- WRITE-005 : sans enjeu ---
|
||||
|
||||
@Test
|
||||
void noStakes_onChapterAndArc() {
|
||||
Arc a = Arc.builder().id("arc").name("Arc").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Chapter c = Chapter.builder().id("chap").name("Chap").arcId("arc").order(0).build();
|
||||
tree(a, c, List.of(scene("s1", 0).branches(List.of(SceneBranch.of("A", "s1"))).build()));
|
||||
|
||||
List<WritingRemark> remarks = service.review(CAMP).remarks().stream()
|
||||
.filter(r -> r.ruleId().equals("WRITE-005-NO-STAKES")).toList();
|
||||
assertEquals(Set.of(ReadinessEntityType.ARC, ReadinessEntityType.CHAPTER),
|
||||
remarks.stream().map(WritingRemark::entityType).collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_notRaised_onEmptyArc_norOnSystemArc() {
|
||||
Arc empty = Arc.builder().id("empty").name("Vide").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Arc system = Arc.builder().id("sys").name("Quêtes libres").campaignId(CAMP).type(ArcType.SYSTEM).order(9999).build();
|
||||
Chapter container = Chapter.builder().id("box").name("Q").arcId("sys").order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(empty, system));
|
||||
when(chapterRepository.findByArcId("empty")).thenReturn(List.of());
|
||||
when(chapterRepository.findByArcId("sys")).thenReturn(List.of(container));
|
||||
when(sceneRepository.findByChapterId("box")).thenReturn(List.of(scene("s1", 0).build()));
|
||||
|
||||
assertFalse(ruleIds().contains("WRITE-005-NO-STAKES"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_raisedOnHubArcCarriedByQuests() {
|
||||
Arc hub = Arc.builder().id("hub").name("Hub").campaignId(CAMP).type(ArcType.HUB).order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(hub));
|
||||
when(questRepository.findByCampaignId(CAMP))
|
||||
.thenReturn(List.of(Quest.builder().id("q").campaignId(CAMP).arcId("hub").build()));
|
||||
|
||||
assertEquals(ReadinessEntityType.ARC, remark("WRITE-005-NO-STAKES").entityType());
|
||||
}
|
||||
|
||||
// --- WRITE-006 / WRITE-007 : narration ---
|
||||
|
||||
@Test
|
||||
void longNarration_overThreshold() {
|
||||
String text = "a".repeat(WritingReviewService.LONG_NARRATION_CHARS + 1);
|
||||
tree(List.of(scene("s1", 0).playerNarration(text).build()));
|
||||
|
||||
assertEquals(String.valueOf(text.length()), remark("WRITE-006-LONG-NARRATION").params().get("chars"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_capturesThePhrase_inFrenchAndEnglish() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("La porte grince. Vous avez peur et reculez.").build()));
|
||||
assertEquals("Vous avez peur", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_english() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("The door creaks open. You enter the hall.").build()));
|
||||
assertEquals("You enter", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narration_notRaised_whenDescriptiveAndShort() {
|
||||
tree(List.of(scene("s1", 0)
|
||||
.playerNarration("La porte grince. Une odeur de cire flotte dans l'air. Que faites-vous ?").build()));
|
||||
Set<String> ids = ruleIds();
|
||||
assertFalse(ids.contains("WRITE-006-LONG-NARRATION"));
|
||||
assertFalse(ids.contains("WRITE-007-NARRATION-DECIDES"));
|
||||
}
|
||||
|
||||
// --- WRITE-008 : combat sans but ---
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null).build()));
|
||||
assertEquals("s1", remark("WRITE-008-COMBAT-NO-PURPOSE").entityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose_notRaised_whenGmNotesExplainMotives() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null)
|
||||
.gmSecretNotes("Ils veulent couler la barque").build()));
|
||||
assertFalse(ruleIds().contains("WRITE-008-COMBAT-NO-PURPOSE"));
|
||||
}
|
||||
|
||||
// --- WRITE-009 : fin unique ---
|
||||
|
||||
@Test
|
||||
void singleEnding_onLastSceneOfLinearArc() {
|
||||
tree(arc("arc", ArcType.LINEAR), chapter("chap", "arc"), List.of(
|
||||
scene("s1", 0).build(),
|
||||
scene("final", 1).type(SceneType.LOCATION).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-009-SINGLE-ENDING");
|
||||
assertEquals("final", r.entityId());
|
||||
assertEquals("arc", r.params().get("arc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleEnding_notRaised_onHubArc_orWhenFinaleHasChoices() {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"),
|
||||
List.of(scene("final", 0).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-009-SINGLE-ENDING"));
|
||||
}
|
||||
|
||||
// --- WRITE-010 : scènes non typées ---
|
||||
|
||||
@Test
|
||||
void untypedScenes_whenMostScenesAreGeneric() {
|
||||
List<Scene> scenes = new ArrayList<>(IntStream.range(0, 5)
|
||||
.mapToObj(i -> scene("s" + i, i).type(SceneType.GENERIC).build()).toList());
|
||||
tree(scenes);
|
||||
when(campaignRepository.findById(CAMP))
|
||||
.thenReturn(Optional.of(Campaign.builder().id(CAMP).name("Ma campagne").build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-010-UNTYPED-SCENES");
|
||||
assertEquals(ReadinessEntityType.CAMPAIGN, r.entityType());
|
||||
assertEquals("100", r.params().get("percent"));
|
||||
// Remarque de campagne en tête de liste.
|
||||
assertEquals("WRITE-010-UNTYPED-SCENES", service.review(CAMP).remarks().get(0).ruleId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void untypedScenes_notRaised_belowMinimumSceneCount() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-010-UNTYPED-SCENES"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot.FirewallRule;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot.Network;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Test du verdict « une tablette peut-elle joindre ce PC ? » à partir des faits lus sur Windows. */
|
||||
class NetworkReadinessTest {
|
||||
|
||||
private static final Network HOME_PRIVATE = new Network("Bbox-Maison", "Wi-Fi", "Private");
|
||||
private static final Network HOME_PUBLIC = new Network("Bbox-Maison", "Wi-Fi", "Public");
|
||||
private static final FirewallRule ALLOW_PRIVATE = new FirewallRule("Allow", "Private", "True");
|
||||
|
||||
private static NetworkReadiness eval(List<Network> networks, List<FirewallRule> rules) {
|
||||
return NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe", networks, rules, List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupported_whenNotWindows() {
|
||||
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.unsupported());
|
||||
assertFalse(r.supported());
|
||||
assertFalse(r.ready());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ready_onPrivateNetwork_withAllowRule() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of(ALLOW_PRIVATE));
|
||||
assertTrue(r.ready());
|
||||
assertTrue(r.firewallAllowed());
|
||||
assertTrue(r.publicNetworks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notReady_withoutAnyRule_evenOnPrivateNetwork() {
|
||||
// Cas réel du 2026-10-17 : Wi-Fi passé en privé, mais aucune règle → la tablette charge sans fin.
|
||||
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of());
|
||||
assertFalse(r.ready());
|
||||
assertFalse(r.firewallAllowed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notReady_onPublicNetwork_evenWithPrivateRule() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(ALLOW_PRIVATE));
|
||||
assertFalse(r.ready());
|
||||
assertEquals(List.of("Bbox-Maison"), r.publicNetworks());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicNetwork_isNotAnObstacle_whenPublicExplicitlyAllowed() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(new FirewallRule("Allow", "Private, Public", "True")));
|
||||
assertTrue(r.ready());
|
||||
assertTrue(r.publicNetworks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockRule_winsOverAllow() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PRIVATE),
|
||||
List.of(ALLOW_PRIVATE, new FirewallRule("Block", "Any", "True")));
|
||||
assertFalse(r.ready());
|
||||
assertTrue(r.firewallBlocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledRules_areIgnored_andAnyCoversPrivate() {
|
||||
assertFalse(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Private", "False"))).ready());
|
||||
assertTrue(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Any", "True"))).ready());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thirdPartyFirewall_isReported_withoutPretendingToKnowItsRules() {
|
||||
// Cas réel du 2026-10-17 : Windows prêt, mais Bitdefender filtre en plus avec ses propres règles.
|
||||
NetworkReadiness r = NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe",
|
||||
List.of(HOME_PRIVATE), List.of(ALLOW_PRIVATE), List.of("Bitdefender Pare-feu")));
|
||||
assertTrue(r.ready(), "Windows est prêt…");
|
||||
assertEquals(List.of("Bitdefender Pare-feu"), r.thirdPartyFirewalls(), "…mais le pare-feu tiers est signalé");
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicNetwork_withoutName_usesInterfaceAlias() {
|
||||
NetworkReadiness r = eval(List.of(new Network(null, "Wi-Fi", "Public")), List.of(ALLOW_PRIVATE));
|
||||
assertEquals(List.of("Wi-Fi"), r.publicNetworks());
|
||||
}
|
||||
|
||||
// --- Linux ---
|
||||
|
||||
@Test
|
||||
void linux_withoutFirewall_isReady() {
|
||||
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.linux("none", 8765, null));
|
||||
assertTrue(r.ready());
|
||||
assertEquals("linux", r.platform());
|
||||
assertNull(r.fixCommand());
|
||||
}
|
||||
|
||||
@Test
|
||||
void linux_ufw_portUnknown_proposesTheCommand() {
|
||||
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.linux("ufw", 8765, null));
|
||||
assertFalse(r.ready());
|
||||
assertNull(r.portOpen());
|
||||
assertEquals("sudo ufw allow 8765/tcp", r.fixCommand());
|
||||
}
|
||||
|
||||
@Test
|
||||
void linux_firewalld_closedThenOpen() {
|
||||
NetworkReadiness closed = NetworkReadiness.evaluate(NetworkSnapshot.linux("firewalld", 9000, false));
|
||||
assertFalse(closed.ready());
|
||||
assertEquals("sudo firewall-cmd --permanent --add-port=9000/tcp && sudo firewall-cmd --reload", closed.fixCommand());
|
||||
|
||||
NetworkReadiness open = NetworkReadiness.evaluate(NetworkSnapshot.linux("firewalld", 9000, true));
|
||||
assertTrue(open.ready());
|
||||
assertNull(open.fixCommand());
|
||||
}
|
||||
}
|
||||
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
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.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test unitaire de {@link RemoteAccessService} avec des doublures en mémoire (pas de Mockito :
|
||||
* l'état des appareils et du connecteur doit vraiment évoluer d'un appel à l'autre).
|
||||
*/
|
||||
class RemoteAccessServiceTest {
|
||||
|
||||
private static final int LOCAL_PORT = 8080;
|
||||
|
||||
private MutableClock clock;
|
||||
private FakeLan lan;
|
||||
private InMemoryDevices devices;
|
||||
private InMemoryConfig config;
|
||||
private RemoteAccessService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clock = new MutableClock(Instant.parse("2026-10-17T10:00:00Z"));
|
||||
lan = new FakeLan();
|
||||
devices = new InMemoryDevices();
|
||||
config = new InMemoryConfig();
|
||||
service = new RemoteAccessService(config, devices, lan, LOCAL_PORT, clock);
|
||||
}
|
||||
|
||||
private String freshCode() {
|
||||
service.configure(true, 8765);
|
||||
return service.newPairingCode().code();
|
||||
}
|
||||
|
||||
// --- Réglage ---
|
||||
|
||||
@Test
|
||||
void disabledByDefault_noConnector() {
|
||||
RemoteAccessStatus status = service.status();
|
||||
assertFalse(status.enabled());
|
||||
assertFalse(status.running());
|
||||
assertEquals(RemoteAccessConfig.DEFAULT_PORT, status.port());
|
||||
assertTrue(status.urls().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enable_opensConnector_persists_andListsUrls() {
|
||||
RemoteAccessStatus status = service.configure(true, 8765);
|
||||
|
||||
assertEquals(8765, lan.port);
|
||||
assertTrue(status.running());
|
||||
assertEquals(List.of("http://192.168.1.20:8765"), status.urls());
|
||||
assertEquals(new RemoteAccessConfig(true, 8765), config.saved);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enable_onBusyPort_staysDisabled() {
|
||||
lan.busy = true;
|
||||
assertThrows(IllegalStateException.class, () -> service.configure(true, 8765));
|
||||
assertNull(config.saved);
|
||||
assertFalse(service.status().enabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_portOutOfRange_orSameAsLocalPort() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.configure(true, 80));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.configure(true, LOCAL_PORT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void disable_closesConnector_andInvalidatesPendingCode() {
|
||||
String code = freshCode();
|
||||
service.configure(false, 8765);
|
||||
|
||||
assertEquals(-1, lan.port);
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void applySavedConfig_reopensOnBoot_withoutCrashingOnBusyPort() {
|
||||
config.saved = new RemoteAccessConfig(true, 8765);
|
||||
lan.busy = true;
|
||||
|
||||
service.applySavedConfig();
|
||||
|
||||
assertEquals(-1, lan.port);
|
||||
assertNotNull(service.status().lastError());
|
||||
}
|
||||
|
||||
// --- Appairage ---
|
||||
|
||||
@Test
|
||||
void pairingCode_requiresOpenConnector() {
|
||||
assertThrows(IllegalStateException.class, () -> service.newPairingCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pairingCode_isSixDigits() {
|
||||
assertTrue(freshCode().matches("\\d{6}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_withRightCode_issuesToken_storesOnlyItsHash_andConsumesTheCode() {
|
||||
String code = freshCode();
|
||||
|
||||
PairingResult result = service.pair(code, " Tablette de Léa ", "Mozilla/5.0 (iPad)");
|
||||
|
||||
assertEquals("Tablette de Léa", result.device().name());
|
||||
RemoteDevice stored = devices.items.get(0);
|
||||
assertNotEquals(result.token(), stored.getTokenHash());
|
||||
assertEquals(RemoteAccessService.sha256(result.token()), stored.getTokenHash());
|
||||
assertTrue(service.authenticate(result.token()).isPresent());
|
||||
// Code à usage unique.
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Autre", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_rejectsExpiredCode() {
|
||||
String code = freshCode();
|
||||
clock.advance(RemoteAccessService.CODE_TTL.plusSeconds(1));
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
assertTrue(devices.items.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_invalidatesCodeAfterTooManyWrongAttempts() {
|
||||
String code = freshCode();
|
||||
String wrong = code.equals("000000") ? "111111" : "000000";
|
||||
for (int i = 0; i < RemoteAccessService.CODE_MAX_ATTEMPTS; i++) {
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(wrong, "Tablette", null));
|
||||
}
|
||||
// Même le bon code ne passe plus : il faut en afficher un nouveau.
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_globalThrottle_blocksBurstAcrossCodes() {
|
||||
for (int i = 0; i < RemoteAccessService.GLOBAL_MAX_FAILURES_PER_MINUTE; i++) {
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair("123456", "x", null));
|
||||
}
|
||||
String code = freshCode();
|
||||
PairingRejectedException blocked =
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
assertTrue(blocked.getMessage().contains("minute"));
|
||||
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
assertDoesNotThrow(() -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceName_defaultsAndIsTruncated() {
|
||||
PairingResult unnamed = service.pair(freshCode(), " ", null);
|
||||
assertEquals("Appareil", unnamed.device().name());
|
||||
|
||||
PairingResult longName = service.pair(service.newPairingCode().code(), "x".repeat(300), null);
|
||||
assertEquals(RemoteAccessService.DEVICE_NAME_MAX, longName.device().name().length());
|
||||
}
|
||||
|
||||
// --- Authentification & révocation ---
|
||||
|
||||
@Test
|
||||
void authenticate_unknownOrBlankToken_isEmpty() {
|
||||
assertTrue(service.authenticate(null).isEmpty());
|
||||
assertTrue(service.authenticate("").isEmpty());
|
||||
assertTrue(service.authenticate("inconnu").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void authenticate_touchesLastSeen_atMostOncePerMinute() {
|
||||
String token = service.pair(freshCode(), "Tablette", null).token();
|
||||
devices.touches = 0;
|
||||
|
||||
service.authenticate(token);
|
||||
assertEquals(0, devices.touches);
|
||||
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
service.authenticate(token);
|
||||
assertEquals(1, devices.touches);
|
||||
}
|
||||
|
||||
@Test
|
||||
void revoke_cutsAccess() {
|
||||
PairingResult result = service.pair(freshCode(), "Tablette", null);
|
||||
|
||||
assertTrue(service.revoke(result.device().id()));
|
||||
assertTrue(service.authenticate(result.token()).isEmpty());
|
||||
assertFalse(service.revoke(result.device().id()));
|
||||
}
|
||||
|
||||
// --- Doublures ---
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant now;
|
||||
|
||||
MutableClock(Instant now) { this.now = now; }
|
||||
|
||||
void advance(Duration d) { now = now.plus(d); }
|
||||
|
||||
@Override public Instant instant() { return now; }
|
||||
@Override public java.time.ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(java.time.ZoneId zone) { return this; }
|
||||
}
|
||||
|
||||
private static final class FakeLan implements LanConnector {
|
||||
int port = -1;
|
||||
boolean busy;
|
||||
|
||||
@Override public void start(int p) {
|
||||
if (busy) throw new IllegalStateException("Le port " + p + " est déjà utilisé par une autre application.");
|
||||
port = p;
|
||||
}
|
||||
@Override public void stop() { port = -1; }
|
||||
@Override public int runningPort() { return port; }
|
||||
@Override public List<String> lanAddresses() { return List.of("192.168.1.20"); }
|
||||
}
|
||||
|
||||
private static final class InMemoryConfig implements RemoteAccessConfigRepository {
|
||||
RemoteAccessConfig saved;
|
||||
|
||||
@Override public Optional<RemoteAccessConfig> find() { return Optional.ofNullable(saved); }
|
||||
@Override public RemoteAccessConfig save(RemoteAccessConfig c) { saved = c; return c; }
|
||||
}
|
||||
|
||||
private static final class InMemoryDevices implements RemoteDeviceRepository {
|
||||
final List<RemoteDevice> items = new ArrayList<>();
|
||||
int touches;
|
||||
private int nextId = 1;
|
||||
|
||||
@Override public RemoteDevice save(RemoteDevice d) {
|
||||
d.setId(String.valueOf(nextId++));
|
||||
items.add(d);
|
||||
return d;
|
||||
}
|
||||
@Override public Optional<RemoteDevice> findByTokenHash(String h) {
|
||||
return items.stream().filter(d -> d.getTokenHash().equals(h)).findFirst();
|
||||
}
|
||||
@Override public List<RemoteDevice> findAll() { return List.copyOf(items); }
|
||||
@Override public void touch(String id, Instant at) {
|
||||
touches++;
|
||||
items.stream().filter(d -> d.getId().equals(id)).forEach(d -> d.setLastSeenAt(at));
|
||||
}
|
||||
@Override public boolean deleteById(String id) { return items.removeIf(d -> d.getId().equals(id)); }
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test de {@link LinuxHostNetworkAccess} : lecture de ufw.conf, interprétation de
|
||||
* {@code firewall-cmd --query-port}, et cas ufw actif sans droits root (port inconnu).
|
||||
*/
|
||||
class LinuxHostNetworkAccessTest {
|
||||
|
||||
@Test
|
||||
void ufwEnabled_readsTheConfigFile() {
|
||||
assertTrue(LinuxHostNetworkAccess.ufwEnabled("# commentaire\nENABLED=yes\nLOGLEVEL=low"));
|
||||
assertTrue(LinuxHostNetworkAccess.ufwEnabled("ENABLED=\"yes\""));
|
||||
assertFalse(LinuxHostNetworkAccess.ufwEnabled("ENABLED=no"));
|
||||
assertFalse(LinuxHostNetworkAccess.ufwEnabled("#ENABLED=yes"));
|
||||
assertFalse(LinuxHostNetworkAccess.ufwEnabled(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void firewalldQuery_yesNoOrUnknown() {
|
||||
assertEquals(Boolean.TRUE, LinuxHostNetworkAccess.interpretQuery(0, "yes\n"));
|
||||
assertEquals(Boolean.FALSE, LinuxHostNetworkAccess.interpretQuery(1, "no\n"));
|
||||
// Refus D-Bus / commande absente : on ne prétend rien.
|
||||
assertNull(LinuxHostNetworkAccess.interpretQuery(-1, ""));
|
||||
assertNull(LinuxHostNetworkAccess.interpretQuery(11, "Authorization failed."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeUfw_meansPortUnknownWithoutRoot(@TempDir Path dir) throws Exception {
|
||||
Path conf = dir.resolve("ufw.conf");
|
||||
Files.writeString(conf, "ENABLED=yes\n");
|
||||
|
||||
NetworkSnapshot s = new LinuxHostNetworkAccess(conf).inspect(8765);
|
||||
|
||||
assertTrue(s.supported());
|
||||
assertEquals("linux", s.platform());
|
||||
assertEquals("ufw", s.linuxFirewall());
|
||||
assertEquals(8765, s.port());
|
||||
assertNull(s.portOpen());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noOneClickFixOnLinux() {
|
||||
assertEquals(HostNetworkAccess.FirewallFixOutcome.UNSUPPORTED,
|
||||
new LinuxHostNetworkAccess(Path.of("absent")).allowThroughFirewall());
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
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 com.loremind.infrastructure.web.config.RemoteAccessFilter;
|
||||
import com.loremind.infrastructure.web.controller.RemotePairingController;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test d'intégration de l'accès distant sur un VRAI Tomcat : ouverture à chaud du second
|
||||
* connecteur, garde du filtre, appairage par code avec pose du cookie, puis fermeture.
|
||||
* Contexte Spring minimal (ni base, ni sécurité) : seules les briques de l'accès distant.
|
||||
*/
|
||||
@SpringBootTest(classes = TomcatLanConnectorIntegrationTest.App.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = "spring.main.banner-mode=off")
|
||||
class TomcatLanConnectorIntegrationTest {
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration(exclude = {
|
||||
DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, FlywayAutoConfiguration.class,
|
||||
SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})
|
||||
@Import(App.Ping.class)
|
||||
static class App {
|
||||
|
||||
@RestController
|
||||
static class Ping {
|
||||
@GetMapping("/api/ping")
|
||||
String ping() { return "pong"; }
|
||||
|
||||
@GetMapping("/api/settings/secret")
|
||||
String secret() { return "admin"; }
|
||||
}
|
||||
|
||||
@Bean
|
||||
TomcatLanConnector lanConnector(ApplicationContext context) {
|
||||
return new TomcatLanConnector(context);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RemoteAccessService remoteAccessService(LanConnector lan) {
|
||||
return new RemoteAccessService(new InMemoryConfig(), new InMemoryDevices(), lan, 1);
|
||||
}
|
||||
|
||||
/** En @Bean : un @Import ignorerait la classe, annotée @Profile("local"). */
|
||||
@Bean
|
||||
RemotePairingController remotePairingController(RemoteAccessService service) {
|
||||
return new RemotePairingController(service);
|
||||
}
|
||||
|
||||
@Bean
|
||||
FilterRegistrationBean<RemoteAccessFilter> remoteAccessFilter(RemoteAccessService service) {
|
||||
return new FilterRegistrationBean<>(new RemoteAccessFilter(service));
|
||||
}
|
||||
}
|
||||
|
||||
@LocalServerPort private int localPort;
|
||||
@Autowired private RemoteAccessService service;
|
||||
@Autowired private TomcatLanConnector lan;
|
||||
|
||||
private final HttpClient http = HttpClient.newHttpClient();
|
||||
|
||||
@AfterEach
|
||||
void closeLan() {
|
||||
lan.stop();
|
||||
}
|
||||
|
||||
private HttpResponse<String> get(int port, String path, String cookie) throws Exception {
|
||||
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path)).GET();
|
||||
if (cookie != null) req.header("Cookie", cookie);
|
||||
return http.send(req.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private HttpResponse<String> post(int port, String path, String json) throws Exception {
|
||||
return http.send(HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static int freePort() throws IOException {
|
||||
try (ServerSocket s = new ServerSocket(0)) {
|
||||
return s.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void lanConnector_guardsApi_pairsWithCode_andClosesCleanly() throws Exception {
|
||||
// Connecteur habituel : inchangé, aucun jeton demandé.
|
||||
assertEquals(200, get(localPort, "/api/ping", null).statusCode());
|
||||
|
||||
int lanPort = freePort();
|
||||
assertTrue(service.configure(true, lanPort).running());
|
||||
|
||||
// Depuis le réseau : appairage exigé, administration interdite.
|
||||
HttpResponse<String> unpaired = get(lanPort, "/api/ping", null);
|
||||
assertEquals(401, unpaired.statusCode());
|
||||
assertTrue(unpaired.body().contains("remote_pairing_required"));
|
||||
assertEquals(403, get(lanPort, "/api/settings/secret", null).statusCode());
|
||||
|
||||
// Mauvais code puis bon code : le bon pose un cookie HttpOnly + SameSite=Strict.
|
||||
assertEquals(403, post(lanPort, "/api/remote-access/pair", "{\"code\":\"abcdef\",\"deviceName\":\"x\"}").statusCode());
|
||||
String code = service.newPairingCode().code();
|
||||
HttpResponse<String> paired = post(lanPort, "/api/remote-access/pair",
|
||||
"{\"code\":\"" + code + "\",\"deviceName\":\"Tablette de test\"}");
|
||||
assertEquals(200, paired.statusCode());
|
||||
String setCookie = paired.headers().firstValue("Set-Cookie").orElseThrow();
|
||||
assertTrue(setCookie.startsWith(RemoteAccessFilter.DEVICE_COOKIE + "="));
|
||||
assertTrue(setCookie.contains("HttpOnly"));
|
||||
assertTrue(setCookie.contains("SameSite=Strict"));
|
||||
String cookie = setCookie.split(";", 2)[0];
|
||||
|
||||
HttpResponse<String> authorized = get(lanPort, "/api/ping", cookie);
|
||||
assertEquals(200, authorized.statusCode());
|
||||
assertEquals("pong", authorized.body());
|
||||
assertEquals(403, get(lanPort, "/api/settings/secret", cookie).statusCode());
|
||||
assertTrue(get(lanPort, "/api/remote-access/session", cookie).body().contains("\"paired\":true"));
|
||||
|
||||
// Désactivation : le port réseau se ferme, le connecteur local continue.
|
||||
service.configure(false, lanPort);
|
||||
assertThrows(ConnectException.class, () -> get(lanPort, "/api/ping", cookie));
|
||||
assertEquals(200, get(localPort, "/api/ping", null).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void busyPort_isReportedClearly() throws Exception {
|
||||
try (ServerSocket occupied = new ServerSocket(0)) {
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> service.configure(true, occupied.getLocalPort()));
|
||||
assertTrue(e.getMessage().contains("déjà utilisé"));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Doublures de persistance ---
|
||||
|
||||
static final class InMemoryConfig implements RemoteAccessConfigRepository {
|
||||
private RemoteAccessConfig saved;
|
||||
|
||||
@Override public Optional<RemoteAccessConfig> find() { return Optional.ofNullable(saved); }
|
||||
@Override public RemoteAccessConfig save(RemoteAccessConfig c) { saved = c; return c; }
|
||||
}
|
||||
|
||||
static final class InMemoryDevices implements RemoteDeviceRepository {
|
||||
private final List<RemoteDevice> items = new ArrayList<>();
|
||||
|
||||
@Override public synchronized RemoteDevice save(RemoteDevice d) {
|
||||
d.setId(String.valueOf(items.size() + 1));
|
||||
items.add(d);
|
||||
return d;
|
||||
}
|
||||
@Override public synchronized Optional<RemoteDevice> findByTokenHash(String h) {
|
||||
return items.stream().filter(d -> d.getTokenHash().equals(h)).findFirst();
|
||||
}
|
||||
@Override public synchronized List<RemoteDevice> findAll() { return List.copyOf(items); }
|
||||
@Override public void touch(String id, Instant at) { /* sans objet ici */ }
|
||||
@Override public synchronized boolean deleteById(String id) { return items.removeIf(d -> d.getId().equals(id)); }
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledOnOs;
|
||||
import org.junit.jupiter.api.condition.OS;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test de {@link WindowsHostNetworkAccess} : lecture du JSON de PowerShell (objet seul ou
|
||||
* tableau), contenu des scripts, et — sur Windows seulement — un vrai appel en lecture seule.
|
||||
*/
|
||||
class WindowsHostNetworkAccessTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void parse_handlesSingleObjectsAndArrays() throws Exception {
|
||||
// ConvertTo-Json écrit un objet (pas un tableau) quand il n'y a qu'un élément.
|
||||
String json = "{\"networks\":{\"name\":\"Bbox\",\"alias\":\"Wi-Fi\",\"category\":\"Private\"},"
|
||||
+ "\"rules\":[{\"action\":\"Allow\",\"profile\":\"Private\",\"enabled\":\"True\"},"
|
||||
+ "{\"action\":\"Block\",\"profile\":\"Public\",\"enabled\":\"True\"}]}";
|
||||
|
||||
NetworkSnapshot s = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", json);
|
||||
|
||||
assertTrue(s.supported());
|
||||
assertEquals(1, s.networks().size());
|
||||
assertEquals("Private", s.networks().get(0).category());
|
||||
assertEquals(2, s.rules().size());
|
||||
assertEquals("Block", s.rules().get(1).action());
|
||||
assertTrue(s.thirdPartyFirewalls().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_readsThirdPartyFirewalls_asSingleValueOrArray() throws Exception {
|
||||
NetworkSnapshot one = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe",
|
||||
"{\"networks\":[],\"rules\":[],\"thirdPartyFirewalls\":\"Bitdefender Pare-feu\"}");
|
||||
assertEquals(java.util.List.of("Bitdefender Pare-feu"), one.thirdPartyFirewalls());
|
||||
|
||||
NetworkSnapshot two = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe",
|
||||
"{\"networks\":[],\"rules\":[],\"thirdPartyFirewalls\":[\"Norton\",\"\"]}");
|
||||
assertEquals(java.util.List.of("Norton"), two.thirdPartyFirewalls());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_handlesEmptyLists_andEmptyOutput() throws Exception {
|
||||
NetworkSnapshot empty = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", "{\"networks\":[],\"rules\":[]}");
|
||||
assertTrue(empty.networks().isEmpty());
|
||||
assertTrue(empty.rules().isEmpty());
|
||||
|
||||
NetworkSnapshot blank = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", " ");
|
||||
assertTrue(blank.networks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scripts_quoteThePath_andOnlyOpenPrivateNetworks() {
|
||||
String path = "C:\\Users\\l'MJ\\DM Loremind.exe";
|
||||
String allow = WindowsHostNetworkAccess.allowScript(path);
|
||||
|
||||
assertTrue(allow.contains("'C:\\Users\\l''MJ\\DM Loremind.exe'"), "apostrophe doublée dans la chaîne PowerShell");
|
||||
assertTrue(allow.contains("-Profile Private"));
|
||||
assertFalse(allow.contains("Public"), "la règle ne doit jamais ouvrir les réseaux publics");
|
||||
assertTrue(allow.contains("Remove-NetFirewallRule"), "les blocages de CE programme sont retirés");
|
||||
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("ConvertTo-Json"));
|
||||
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("SecurityCenter2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encode_isUtf16LeBase64_asExpectedByEncodedCommand() {
|
||||
String encoded = WindowsHostNetworkAccess.encode("é");
|
||||
assertEquals("é", new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_16LE));
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledOnOs(OS.WINDOWS)
|
||||
void inspect_readsTheRealSystem_onWindows() {
|
||||
NetworkSnapshot s = new WindowsHostNetworkAccess(mapper).inspect(8765);
|
||||
assertTrue(s.supported(), "PowerShell doit répondre en lecture seule sur Windows");
|
||||
assertNotNull(s.program());
|
||||
assertNotNull(s.thirdPartyFirewalls());
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -71,6 +73,15 @@ class FlywayMigrationTest {
|
||||
"values ('C', 0, now(), now())");
|
||||
st.executeUpdate("insert into arcs (name, campaign_id, \"order\", type, created_at, updated_at) " +
|
||||
"select 'Quêtes libres', id, 9999, 'SYSTEM', now(), now() from campaigns");
|
||||
|
||||
// V25 : accès distant — réglage singleton + appareils, empreinte de jeton unique.
|
||||
st.executeUpdate("insert into remote_access_config (id, enabled, port, updated_at) " +
|
||||
"values ('current', true, 8765, now())");
|
||||
st.executeUpdate("insert into remote_devices (name, token_hash, created_at) values ('Tablette', 'abc', now())");
|
||||
assertThrows(SQLException.class,
|
||||
() -> st.executeUpdate("insert into remote_devices (name, token_hash, created_at) " +
|
||||
"values ('Doublon', 'abc', now())"),
|
||||
"remote_devices.token_hash doit être unique (V25)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,4 +130,77 @@ class FlywayMigrationTest {
|
||||
assertEquals("[]", rs.getString(2));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* V24 : les conteneurs ORPHELINS de l'arc SYSTEM (quête libre supprimée avant que
|
||||
* la suppression ne cascade) sont réparés — rattachés à une quête recréée s'ils
|
||||
* ont des scènes (contenu redevenu visible), supprimés s'ils sont vides. Le
|
||||
* conteneur d'une quête vivante n'est pas touché.
|
||||
*/
|
||||
@Test
|
||||
void v24_reattachesOrphanSystemContainers_andDropsEmptyOnes() throws SQLException {
|
||||
String url = "jdbc:h2:mem:flyway_v24_test;MODE=PostgreSQL;NON_KEYWORDS=VALUE;DB_CLOSE_DELAY=-1";
|
||||
|
||||
// 1) Schéma arrêté AVANT V24…
|
||||
Flyway.configure()
|
||||
.dataSource(url, "sa", "")
|
||||
.locations("classpath:db/migration")
|
||||
.target(MigrationVersion.fromVersion("23"))
|
||||
.load()
|
||||
.migrate();
|
||||
|
||||
// 2) …peuplé : un arc SYSTEM avec un orphelin PLEIN (1 scène), un orphelin
|
||||
// VIDE, et le conteneur d'une quête VIVANTE.
|
||||
try (Connection conn = DriverManager.getConnection(url, "sa", "");
|
||||
Statement st = conn.createStatement()) {
|
||||
st.executeUpdate("insert into campaigns (id, name, arcs_count, created_at, updated_at) "
|
||||
+ "values (1, 'C', 0, now(), now())");
|
||||
st.executeUpdate("insert into arcs (id, name, campaign_id, \"order\", type, created_at, updated_at) "
|
||||
+ "values (9, 'Quêtes libres', 1, 9999, 'SYSTEM', now(), now())");
|
||||
st.executeUpdate("insert into chapters (id, name, arc_id, \"order\", created_at, updated_at) "
|
||||
+ "values (41, 'Orphelin plein', 9, 0, now(), now())");
|
||||
st.executeUpdate("insert into chapters (id, name, arc_id, \"order\", created_at, updated_at) "
|
||||
+ "values (42, 'Orphelin vide', 9, 1, now(), now())");
|
||||
st.executeUpdate("insert into chapters (id, name, arc_id, \"order\", created_at, updated_at) "
|
||||
+ "values (43, 'Vivant', 9, 2, now(), now())");
|
||||
st.executeUpdate("insert into scenes (id, name, chapter_id, \"order\", created_at, updated_at) "
|
||||
+ "values (1, 'S', 41, 0, now(), now())");
|
||||
st.executeUpdate("insert into quests (campaign_id, \"order\", name, nodes, created_at, updated_at) "
|
||||
+ "values (1, 0, 'Vivant', '[{\"nodeType\":\"CHAPTER\",\"nodeId\":\"43\",\"order\":0}]', now(), now())");
|
||||
}
|
||||
|
||||
// 3) Fin de la chaîne : V24 répare.
|
||||
Flyway.configure()
|
||||
.dataSource(url, "sa", "")
|
||||
.locations("classpath:db/migration")
|
||||
.load()
|
||||
.migrate();
|
||||
|
||||
try (Connection conn = DriverManager.getConnection(url, "sa", "");
|
||||
Statement st = conn.createStatement()) {
|
||||
|
||||
// L'orphelin PLEIN est rattaché : quête LIBRE (arc_id NULL) recréée dessus.
|
||||
try (ResultSet rs = st.executeQuery(
|
||||
"select arc_id, nodes from quests where name = 'Orphelin plein'")) {
|
||||
assertTrue(rs.next(), "une quête aurait dû être recréée sur le conteneur orphelin");
|
||||
assertNull(rs.getObject(1));
|
||||
assertEquals("[{\"nodeType\":\"CHAPTER\",\"nodeId\":\"41\",\"order\":0}]", rs.getString(2));
|
||||
}
|
||||
|
||||
// L'orphelin VIDE a disparu ; l'orphelin plein et le conteneur vivant restent.
|
||||
try (ResultSet rs = st.executeQuery("select id from chapters where arc_id = 9 order by id")) {
|
||||
assertTrue(rs.next());
|
||||
assertEquals(41, rs.getInt(1));
|
||||
assertTrue(rs.next());
|
||||
assertEquals(43, rs.getInt(1));
|
||||
assertFalse(rs.next(), "l'orphelin vide (42) aurait dû être supprimé");
|
||||
}
|
||||
|
||||
// Pas de doublon : la quête vivante n'a pas été re-rattachée.
|
||||
try (ResultSet rs = st.executeQuery("select count(*) from quests")) {
|
||||
rs.next();
|
||||
assertEquals(2, rs.getInt(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+60
@@ -1,5 +1,8 @@
|
||||
package com.loremind.infrastructure.transfer.foundry;
|
||||
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||
import com.loremind.domain.shared.template.TemplateField;
|
||||
import com.loremind.infrastructure.persistence.entity.*;
|
||||
@@ -30,6 +33,7 @@ class FoundryExportServiceTest {
|
||||
@Autowired private CampaignJpaRepository campaignRepo;
|
||||
@Autowired private ArcJpaRepository arcRepo;
|
||||
@Autowired private ChapterJpaRepository chapterRepo;
|
||||
@Autowired private QuestJpaRepository questRepo;
|
||||
@Autowired private SceneJpaRepository sceneRepo;
|
||||
@Autowired private NpcJpaRepository npcRepo;
|
||||
@Autowired private GameSystemJpaRepository gameSystemRepo;
|
||||
@@ -251,4 +255,60 @@ class FoundryExportServiceTest {
|
||||
assertThrows(java.util.NoSuchElementException.class,
|
||||
() -> service.buildBundle("999999999", "2026-06-25T00:00:00Z"));
|
||||
}
|
||||
|
||||
/**
|
||||
* L'arc technique SYSTEM heberge les conteneurs des quetes libres. Un conteneur
|
||||
* ORPHELIN (quete supprimee, chapitre garde par deleteQuest car il contenait des
|
||||
* scenes) est invisible dans l'appli : il ne doit pas partir dans le bundle.
|
||||
*/
|
||||
@Test
|
||||
void buildBundle_systemArc_exportsOnlyLiveQuestContainers() {
|
||||
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder()
|
||||
.name("Quetes libres").description("d").arcsCount(1).build());
|
||||
ArcJpaEntity system = arcRepo.save(ArcJpaEntity.builder()
|
||||
.campaignId(camp.getId()).name("Quêtes libres").order(9999)
|
||||
.type(ArcType.SYSTEM).build());
|
||||
ChapterJpaEntity live = chapterRepo.save(ChapterJpaEntity.builder()
|
||||
.arcId(system.getId()).name("Quete vivante").order(0).build());
|
||||
ChapterJpaEntity orphan = chapterRepo.save(ChapterJpaEntity.builder()
|
||||
.arcId(system.getId()).name("test de quete").order(1).build());
|
||||
sceneRepo.save(SceneJpaEntity.builder()
|
||||
.chapterId(live.getId()).name("Scene vivante").order(0).build());
|
||||
sceneRepo.save(SceneJpaEntity.builder()
|
||||
.chapterId(orphan.getId()).name("Scene fantome").order(0).build());
|
||||
questRepo.save(QuestJpaEntity.builder()
|
||||
.campaignId(camp.getId()).name("Quete vivante").order(0)
|
||||
.nodes(List.of(new QuestNodeRef(NodeType.CHAPTER, String.valueOf(live.getId()), 0)))
|
||||
.build());
|
||||
|
||||
FoundryBundle.Data data = service.buildBundle(
|
||||
String.valueOf(camp.getId()), "2026-07-09T00:00:00Z").data();
|
||||
|
||||
assertEquals(1, data.arcs().size());
|
||||
assertEquals(1, data.quests().size());
|
||||
assertEquals("Quete vivante", data.quests().get(0).name());
|
||||
assertEquals(1, data.scenes().size());
|
||||
assertEquals("Scene vivante", data.scenes().get(0).name());
|
||||
}
|
||||
|
||||
/** Sans quete vivante, l'arc SYSTEM disparait entierement du bundle. */
|
||||
@Test
|
||||
void buildBundle_systemArcWithoutLiveQuest_isDroppedEntirely() {
|
||||
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder()
|
||||
.name("Fantomes").description("d").arcsCount(1).build());
|
||||
ArcJpaEntity system = arcRepo.save(ArcJpaEntity.builder()
|
||||
.campaignId(camp.getId()).name("Quêtes libres").order(9999)
|
||||
.type(ArcType.SYSTEM).build());
|
||||
ChapterJpaEntity orphan = chapterRepo.save(ChapterJpaEntity.builder()
|
||||
.arcId(system.getId()).name("test").order(0).build());
|
||||
sceneRepo.save(SceneJpaEntity.builder()
|
||||
.chapterId(orphan.getId()).name("test").order(0).build());
|
||||
|
||||
FoundryBundle.Data data = service.buildBundle(
|
||||
String.valueOf(camp.getId()), "2026-07-09T00:00:00Z").data();
|
||||
|
||||
assertTrue(data.arcs().isEmpty());
|
||||
assertTrue(data.quests().isEmpty());
|
||||
assertTrue(data.scenes().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire de {@link RemoteAccessFilter} : ce qui passe et ce qui est refusé selon
|
||||
* le connecteur d'arrivée (local / réseau), le chemin et le cookie d'appareil.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class RemoteAccessFilterTest {
|
||||
|
||||
private static final int LOCAL_PORT = 8080;
|
||||
private static final int LAN_PORT = 8765;
|
||||
|
||||
@Mock private RemoteAccessService service;
|
||||
private RemoteAccessFilter filter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
filter = new RemoteAccessFilter(service);
|
||||
when(service.lanPort()).thenReturn(LAN_PORT);
|
||||
when(service.authenticate("bon-jeton")).thenReturn(Optional.of(RemoteDevice.builder().id("1").name("Tablette").build()));
|
||||
when(service.authenticate(null)).thenReturn(Optional.empty());
|
||||
when(service.authenticate("mauvais")).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
private record Outcome(boolean passed, int status, String body) {}
|
||||
|
||||
private Outcome run(int localPort, String path, String token) throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", path);
|
||||
request.setLocalPort(localPort);
|
||||
if (token != null) request.setCookies(new Cookie(RemoteAccessFilter.DEVICE_COOKIE, token));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
filter.doFilter(request, response, chain);
|
||||
return new Outcome(chain.getRequest() != null, response.getStatus(), response.getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void localConnector_isUntouched_evenForSettings() throws Exception {
|
||||
assertTrue(run(LOCAL_PORT, "/api/campaigns", null).passed());
|
||||
assertTrue(run(LOCAL_PORT, "/api/settings", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lanClosed_meansEverythingIsLocal() throws Exception {
|
||||
when(service.lanPort()).thenReturn(-1);
|
||||
assertTrue(run(LOCAL_PORT, "/api/campaigns", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_staticFrontAndPublicApi_passWithoutToken() throws Exception {
|
||||
assertTrue(run(LAN_PORT, "/", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/pair", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/main-ABC123.js", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/config", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/remote-access/pair", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/remote-access/session", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_api_requiresValidDeviceToken() throws Exception {
|
||||
Outcome none = run(LAN_PORT, "/api/campaigns", null);
|
||||
assertFalse(none.passed());
|
||||
assertEquals(401, none.status());
|
||||
assertTrue(none.body().contains("remote_pairing_required"));
|
||||
|
||||
assertEquals(401, run(LAN_PORT, "/api/images/42", "mauvais").status());
|
||||
assertTrue(run(LAN_PORT, "/api/campaigns", "bon-jeton").passed());
|
||||
assertTrue(run(LAN_PORT, "/api/images/42", "bon-jeton").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_adminRoutes_areAlwaysForbidden_evenWhenPaired() throws Exception {
|
||||
for (String path : new String[]{"/api/settings", "/api/settings/remote-access", "/api/admin/data/export", "/api/license"}) {
|
||||
Outcome outcome = run(LAN_PORT, path, "bon-jeton");
|
||||
assertFalse(outcome.passed(), path);
|
||||
assertEquals(403, outcome.status(), path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -11,6 +11,8 @@ import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -39,6 +41,7 @@ class CampaignTreeControllerTest {
|
||||
@Autowired private ChapterRepository chapterRepository;
|
||||
@Autowired private SceneRepository sceneRepository;
|
||||
@Autowired private QuestRepository questRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
|
||||
private String campaignId;
|
||||
private String arcId;
|
||||
@@ -52,6 +55,7 @@ class CampaignTreeControllerTest {
|
||||
chapterId = chapterRepository.save(Chapter.builder().arcId(arcId).name("Chap").order(0).build()).getId();
|
||||
sceneRepository.save(Scene.builder().chapterId(chapterId).name("Scène").order(0).build());
|
||||
questRepository.save(Quest.builder().campaignId(campaignId).arcId(arcId).name("Quête").order(0).build());
|
||||
playthroughRepository.save(Playthrough.builder().campaignId(campaignId).name("Partie 1").build());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -65,6 +69,8 @@ class CampaignTreeControllerTest {
|
||||
.andExpect(jsonPath("$.scenesByChapter." + chapterId + "[0].name").value("Scène"))
|
||||
.andExpect(jsonPath("$.quests", hasSize(1)))
|
||||
.andExpect(jsonPath("$.quests[0].arcId").value(arcId))
|
||||
.andExpect(jsonPath("$.playthroughs", hasSize(1)))
|
||||
.andExpect(jsonPath("$.playthroughs[0].name").value("Partie 1"))
|
||||
.andExpect(jsonPath("$.readiness.campaignId").value(campaignId))
|
||||
.andExpect(jsonPath("$.readiness.gaps").isArray());
|
||||
}
|
||||
|
||||
+20
@@ -20,6 +20,11 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.hamcrest.Matchers.everyItem;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
|
||||
@@ -98,6 +103,21 @@ class SessionControllerTest {
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSessions_activeOnly_excludesEnded() throws Exception {
|
||||
Session running = saveSession();
|
||||
Session ended = sessionRepository.save(Session.builder()
|
||||
.name("ended").playthroughId(playthroughId)
|
||||
.startedAt(FIXED_TIME.minusHours(2))
|
||||
.endedAt(FIXED_TIME.minusHours(1))
|
||||
.build());
|
||||
mockMvc.perform(get("/api/sessions").param("active", "true"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[*].active", everyItem(is(true))))
|
||||
.andExpect(jsonPath("$[*].id", hasItem(running.getId())))
|
||||
.andExpect(jsonPath("$[*].id", not(hasItem(ended.getId()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getActive_global_returnsActive() throws Exception {
|
||||
saveSession();
|
||||
|
||||
+25
-2
@@ -18,7 +18,9 @@
|
||||
Le code source de ce script est public et auditable a l'adresse indiquee dans .LINK.
|
||||
|
||||
.PARAMETER InstallDir
|
||||
Dossier d'installation. Defaut : %LOCALAPPDATA%\DM Loremind
|
||||
Dossier d'installation. Defaut : %LOCALAPPDATA%\DM Loremind Docker
|
||||
(PAS "%LOCALAPPDATA%\DM Loremind" : ce dossier est celui de l'application
|
||||
bureau .msi — les deux produits ne doivent jamais partager un dossier).
|
||||
|
||||
.PARAMETER ComposeUrl
|
||||
URL du fichier docker-compose.yml a recuperer. Defaut : version officielle du depot.
|
||||
@@ -48,7 +50,7 @@
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$InstallDir = "$env:LOCALAPPDATA\DM Loremind",
|
||||
[string]$InstallDir = "$env:LOCALAPPDATA\DM Loremind Docker",
|
||||
[string]$ComposeUrl = "https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/docker-compose.yml",
|
||||
[int]$WebPort = 8081,
|
||||
[switch]$NonInteractive
|
||||
@@ -204,6 +206,27 @@ if (Test-Docker) {
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Dossier d'installation + docker-compose.yml
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compat : les stacks historiques vivaient dans "%LOCALAPPDATA%\DM Loremind",
|
||||
# desormais reserve a l'application bureau (.msi jpackage, meme nom produit —
|
||||
# une maj du .msi pouvait ecraser compose/.env). Si un stack y est deja
|
||||
# installe (compose present, pas d'exe bureau), on le reutilise plutot que
|
||||
# d'en creer un second qui entrerait en conflit (memes noms de conteneurs).
|
||||
$legacyDir = "$env:LOCALAPPDATA\DM Loremind"
|
||||
if ($InstallDir -eq "$env:LOCALAPPDATA\DM Loremind Docker" -and
|
||||
(Test-Path (Join-Path $legacyDir 'docker-compose.yml')) -and
|
||||
-not (Test-Path (Join-Path $legacyDir 'DM Loremind.exe'))) {
|
||||
Write-Warn2 "Stack Docker existant detecte dans $legacyDir - reutilise (pas de duplication)."
|
||||
$InstallDir = $legacyDir
|
||||
}
|
||||
|
||||
# Garde-fou : jamais d'installation du stack Docker dans le dossier de
|
||||
# l'application bureau (le .msi et le stack s'ecraseraient mutuellement).
|
||||
if (Test-Path (Join-Path $InstallDir 'DM Loremind.exe')) {
|
||||
Write-Err "Le dossier $InstallDir contient l'application bureau DM Loremind (.msi)."
|
||||
Write-Err "La version Docker doit vivre ailleurs : relancez avec -InstallDir <autre dossier>."
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Step "Preparation du dossier $InstallDir"
|
||||
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
|
||||
Set-Location $InstallDir
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ruleset xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
name="LoreMind"
|
||||
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
||||
|
||||
<description>
|
||||
Ruleset PMD LoreMind — détecté automatiquement par MegaLinter (JAVA_PMD).
|
||||
Philosophie : bugs et pièges réels uniquement. Les catégories de STYLE
|
||||
(codestyle/design/documentation) sont exclues : le défaut MegaLinter y
|
||||
générait ~11 000 violations hors sujet (conventions incompatibles avec
|
||||
l'idiome Lombok/slf4j/Spring du projet : champ `log`, DI constructeur…).
|
||||
</description>
|
||||
|
||||
<!-- Bugs probables : null, equals/hashCode, ressources, casts douteux… -->
|
||||
<rule ref="category/java/errorprone.xml">
|
||||
<!-- Chaque littéral dupliqué = une violation : du bruit, pas un bug. -->
|
||||
<exclude name="AvoidDuplicateLiterals"/>
|
||||
<exclude name="AvoidLiteralsInIfCondition"/>
|
||||
<!-- Entités JPA/DTO : pas de sérialisation Java native ici. -->
|
||||
<exclude name="MissingSerialVersionUID"/>
|
||||
<!-- `this.name = name` en DI/setters : idiome standard. -->
|
||||
<exclude name="AvoidFieldNameMatchingMethodName"/>
|
||||
<exclude name="AvoidFieldNameMatchingTypeName"/>
|
||||
<!-- `while ((x = read()) != null)` : idiome de lecture standard. -->
|
||||
<exclude name="AssignmentInOperand"/>
|
||||
<!-- catch(Exception) best-effort : choix assumé du projet (imports,
|
||||
exports, best-effort serveur) — pas un gate. -->
|
||||
<exclude name="AvoidCatchingGenericException"/>
|
||||
<!-- TODO backlog : réactiver et passer les toLowerCase/UpperCase en
|
||||
Locale.ROOT (27 sites) — bug potentiel (locale turque) mais
|
||||
changement de comportement à valider posément. -->
|
||||
<exclude name="UseLocaleWithCaseConversions"/>
|
||||
</rule>
|
||||
|
||||
<!-- Concurrence -->
|
||||
<rule ref="category/java/multithreading.xml">
|
||||
<!-- Règle d'époque J2EE : les threads sont légitimes (sidecar, SSE…). -->
|
||||
<exclude name="DoNotUseThreads"/>
|
||||
<!-- Flaguerait CHAQUE HashMap, y compris locales à une méthode (×135). -->
|
||||
<exclude name="UseConcurrentHashMap"/>
|
||||
</rule>
|
||||
|
||||
<!-- Performance (sans les micro-optimisations StringBuilder : le rendu
|
||||
PDF/HTML fait des milliers d'appends, aucun n'est un point chaud). -->
|
||||
<rule ref="category/java/performance.xml">
|
||||
<exclude name="AvoidInstantiatingObjectsInLoops"/>
|
||||
<exclude name="AppendCharacterWithChar"/>
|
||||
<exclude name="ConsecutiveLiteralAppends"/>
|
||||
<exclude name="ConsecutiveAppendsShouldReuse"/>
|
||||
<exclude name="InsufficientStringBufferDeclaration"/>
|
||||
</rule>
|
||||
|
||||
<!-- Sécurité -->
|
||||
<rule ref="category/java/security.xml"/>
|
||||
|
||||
<!-- Bonnes pratiques (sous-ensemble non-style) -->
|
||||
<rule ref="category/java/bestpractices.xml">
|
||||
<!-- slf4j paramétré ({} + args) rend le guard inutile. -->
|
||||
<exclude name="GuardLogStatement"/>
|
||||
<!-- Les ports hexagonaux à méthode unique ne sont pas des lambdas. -->
|
||||
<exclude name="ImplicitFunctionalInterface"/>
|
||||
<!-- Déclarer List vs ArrayList : style, pas un bug. -->
|
||||
<exclude name="LooseCoupling"/>
|
||||
<!-- StringBuilder en champ : pattern builder assumé (export PDF). -->
|
||||
<exclude name="AvoidStringBufferField"/>
|
||||
<!-- Style de tests : à l'appréciation du projet, pas un gate. -->
|
||||
<exclude name="UnitTestAssertionsShouldIncludeMessage"/>
|
||||
<exclude name="UnitTestContainsTooManyAsserts"/>
|
||||
<exclude name="UnitTestShouldIncludeAssert"/>
|
||||
</rule>
|
||||
|
||||
</ruleset>
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
FROM node:20-bookworm-slim AS build
|
||||
WORKDIR /build
|
||||
RUN npm install -g npm@latest
|
||||
# PAS de mise à jour de npm ici : « npm@latest » est une cible mouvante qui finit
|
||||
# par exiger un Node plus récent que l'image (npm 12 -> Node >= 22) et casse le
|
||||
# build. Le npm livré avec l'image suffit (npm ci supporte lockfileVersion 3).
|
||||
COPY package*.json ./
|
||||
RUN npm ci --include=dev --ignore-scripts --no-audit --no-fund --no-progress
|
||||
COPY . .
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
"zone.js"
|
||||
],
|
||||
"tsConfig": "tsconfig.json",
|
||||
"allowedCommonJsDependencies": [
|
||||
"qrcode"
|
||||
],
|
||||
"assets": [
|
||||
"src/favicon.ico",
|
||||
"src/assets"
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Page, expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Ajoute un bloc Texte au builder de template (grille de blocs) et le renomme.
|
||||
*
|
||||
* Le builder n'a plus de champ « + Ajouter un champ » : un clic sur un type de
|
||||
* la palette ajoute en bas de la grille un bloc au nom par défaut (« Texte »,
|
||||
* « Texte 2 »…), qu'on renomme dans son en-tête. Le nom est validé au blur.
|
||||
*/
|
||||
export async function addTextBlock(page: Page, name: string): Promise<void> {
|
||||
const blocks = page.locator('.grid-block');
|
||||
const before = await blocks.count();
|
||||
|
||||
await page.locator('.palette-item', { hasText: /^\s*Texte\s*$/ }).click();
|
||||
await expect(blocks).toHaveCount(before + 1);
|
||||
|
||||
const nameInput = blocks.last().locator('.block-name-input');
|
||||
await nameInput.fill(name);
|
||||
await nameInput.blur();
|
||||
await expect(page.locator(`.grid-block[data-block-name="${name}"]`)).toBeVisible();
|
||||
}
|
||||
@@ -113,7 +113,10 @@ test.describe('Scene edit', () => {
|
||||
|
||||
const branchItem = branchesSection.locator('.branch-item').first();
|
||||
await branchItem.getByPlaceholder(/Ex: Si les joueurs attaquent/i).fill('Si les PJ fuient');
|
||||
await branchItem.locator('select').selectOption({ label: sibling.name });
|
||||
// Une branche a 2 selects (scène cible + type de lien) : on vise celui qui liste la scène.
|
||||
await branchItem
|
||||
.locator('select', { has: page.locator('option', { hasText: sibling.name }) })
|
||||
.selectOption({ label: sibling.name });
|
||||
await branchItem.getByPlaceholder(/Jet de Persuasion/i).fill('Sur échec initiative');
|
||||
|
||||
await page.getByRole('button', { name: /^Sauvegarder$/i }).click();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { seedLoreWithFolder, deleteLore, getTemplatesForLore, type SeededLore } from '../../fixtures/api';
|
||||
import { addTextBlock } from '../../fixtures/template-builder';
|
||||
|
||||
test.describe('Template creation', () => {
|
||||
let seeded: SeededLore;
|
||||
@@ -50,14 +51,8 @@ test.describe('Template creation', () => {
|
||||
await page.getByLabel(/Nom du template/i).fill(templateName);
|
||||
await page.getByLabel(/Dossier par défaut/i).selectOption({ label: seeded.rootFolderName });
|
||||
|
||||
const addFieldInput = page.getByPlaceholder('+ Ajouter un champ');
|
||||
await addFieldInput.fill('Pouvoir');
|
||||
await addFieldInput.press('Enter');
|
||||
await expect(page.locator('.grid-block[data-block-name="Pouvoir"]')).toBeVisible();
|
||||
|
||||
await addFieldInput.fill('Origine');
|
||||
await addFieldInput.press('Enter');
|
||||
await expect(page.locator('.grid-block[data-block-name="Origine"]')).toBeVisible();
|
||||
await addTextBlock(page, 'Pouvoir');
|
||||
await addTextBlock(page, 'Origine');
|
||||
|
||||
const origineBlock = page.locator('.grid-block[data-block-name="Origine"]');
|
||||
await origineBlock.getByRole('button', { name: 'Supprimer' }).click();
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type SeededLore,
|
||||
type SeededTemplate,
|
||||
} from '../../fixtures/api';
|
||||
import { addTextBlock } from '../../fixtures/template-builder';
|
||||
|
||||
test.describe('Template edit', () => {
|
||||
let seeded: SeededLore;
|
||||
@@ -55,10 +56,9 @@ test.describe('Template edit', () => {
|
||||
test('adds a new field, removes an existing one, and persists the order', async ({ page, request }) => {
|
||||
await page.goto(`/lore/${seeded.id}/templates/${template.id}`);
|
||||
|
||||
const addInput = page.getByPlaceholder('+ Ajouter un champ');
|
||||
await addInput.fill('Stats');
|
||||
await addInput.press('Enter');
|
||||
await expect(page.locator('.grid-block[data-block-name="Stats"]')).toBeVisible();
|
||||
// Attendre les champs existants (chargés en asynchrone) avant d'en ajouter un.
|
||||
await expect(page.locator('.grid-block[data-block-name="Description"]')).toBeVisible();
|
||||
await addTextBlock(page, 'Stats');
|
||||
|
||||
const descriptionBlock = page.locator('.grid-block[data-block-name="Description"]');
|
||||
await descriptionBlock.getByRole('button', { name: 'Supprimer' }).click();
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { test, expect, type APIRequestContext, type Page } from '@playwright/test';
|
||||
import {
|
||||
seedCampaign,
|
||||
seedArc,
|
||||
seedChapter,
|
||||
seedScene,
|
||||
deleteCampaign,
|
||||
type SeededCampaign,
|
||||
type SeededArc,
|
||||
type SeededChapter,
|
||||
type SeededScene,
|
||||
} from '../../fixtures/api';
|
||||
|
||||
/**
|
||||
* Shell responsive au viewport téléphone (projet Playwright « mobile », 375 px).
|
||||
*
|
||||
* Sous 1024 px, le menu principal et l'arborescence deviennent des tiroirs
|
||||
* off-canvas ouverts depuis une barre haute. On vérifie :
|
||||
* - qu'aucun écran clé ne défile horizontalement — ni le document, ni
|
||||
* `main.main-content` (le conteneur qui défile réellement : un débordement
|
||||
* y produirait une barre horizontale sans toucher au document) ;
|
||||
* - que la navigation reste accessible au doigt (ouverture, navigation,
|
||||
* fermeture au changement de route / Échap / clic extérieur).
|
||||
*/
|
||||
|
||||
async function expectNoHorizontalScroll(page: Page): Promise<void> {
|
||||
const m = await page.evaluate(() => {
|
||||
const main = document.querySelector('main.main-content');
|
||||
return {
|
||||
doc: document.documentElement.scrollWidth,
|
||||
vw: window.innerWidth,
|
||||
mainScroll: main?.scrollWidth ?? 0,
|
||||
mainClient: main?.clientWidth ?? 0,
|
||||
};
|
||||
});
|
||||
expect(m.doc, 'scroll horizontal du document').toBeLessThanOrEqual(m.vw);
|
||||
expect(m.mainScroll, 'scroll horizontal de main.main-content').toBeLessThanOrEqual(m.mainClient);
|
||||
}
|
||||
|
||||
async function seedPlaythroughWithSession(
|
||||
request: APIRequestContext,
|
||||
campaignId: string,
|
||||
): Promise<{ playthroughId: string; sessionId: string }> {
|
||||
const ptRes = await request.post('/api/playthroughs', {
|
||||
data: { campaignId, name: `E2E Partie ${Date.now()}`, description: 'Seeded by Playwright' },
|
||||
});
|
||||
expect(ptRes.ok(), `POST /api/playthroughs -> ${ptRes.status()}`).toBeTruthy();
|
||||
const pt = await ptRes.json();
|
||||
|
||||
const clockRes = await request.post(`/api/playthroughs/${pt.id}/clocks`, {
|
||||
data: { name: 'Le rituel du nécromancien', description: '', segments: 6 },
|
||||
});
|
||||
expect(clockRes.ok(), `POST clocks -> ${clockRes.status()}`).toBeTruthy();
|
||||
|
||||
const sRes = await request.post('/api/sessions', { data: { playthroughId: pt.id } });
|
||||
expect(sRes.ok(), `POST /api/sessions -> ${sRes.status()}`).toBeTruthy();
|
||||
const session = await sRes.json();
|
||||
|
||||
const eRes = await request.post(`/api/sessions/${session.id}/entries`, {
|
||||
data: { type: 'NOTE', content: 'Les PJ arrivent à Brumecombe sous la pluie.', occurredAt: null },
|
||||
});
|
||||
expect(eRes.ok(), `POST entries -> ${eRes.status()}`).toBeTruthy();
|
||||
|
||||
return { playthroughId: pt.id, sessionId: session.id };
|
||||
}
|
||||
|
||||
test.describe('Shell mobile (375 px)', () => {
|
||||
test('liste des campagnes : pas de scroll horizontal, menu en tiroir', async ({ page }) => {
|
||||
await page.goto('/campaigns');
|
||||
await expect(page.getByRole('heading', { name: /Vos Campagnes/i })).toBeVisible();
|
||||
await expectNoHorizontalScroll(page);
|
||||
|
||||
// Le menu principal est hors écran tant que le tiroir est fermé.
|
||||
const menu = page.locator('app-sidebar');
|
||||
await expect(menu).toBeHidden();
|
||||
|
||||
// Le libellé du burger alterne Ouvrir / Fermer : on le cible par aria-controls.
|
||||
const burger = page.locator('button[aria-controls="app-main-nav"]');
|
||||
await expect(burger).toHaveAccessibleName('Ouvrir le menu');
|
||||
await burger.tap();
|
||||
await expect(menu).toBeVisible();
|
||||
await expect(burger).toHaveAttribute('aria-expanded', 'true');
|
||||
await expect(burger).toHaveAccessibleName('Fermer le menu');
|
||||
|
||||
// Échap referme et rend le focus au bouton burger.
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(burger).toBeFocused();
|
||||
|
||||
// Clic hors du tiroir (voile) : referme aussi.
|
||||
await burger.tap();
|
||||
await expect(menu).toBeVisible();
|
||||
await page.mouse.click(360, 400);
|
||||
await expect(menu).toBeHidden();
|
||||
|
||||
// Navigation depuis le tiroir : la page change et le tiroir se ferme.
|
||||
await burger.tap();
|
||||
await menu.getByRole('button', { name: 'Lore', exact: true }).tap();
|
||||
await expect(page).toHaveURL(/\/lore$/);
|
||||
await expect(page.getByRole('heading', { name: /Vos Univers/i })).toBeVisible();
|
||||
await expect(menu).toBeHidden();
|
||||
await expectNoHorizontalScroll(page);
|
||||
});
|
||||
|
||||
test.describe('avec une campagne', () => {
|
||||
let campaign: SeededCampaign;
|
||||
let arc: SeededArc;
|
||||
let chapter: SeededChapter;
|
||||
let scene: SeededScene;
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
// Nom long volontaire : c'est lui qui faisait déborder l'en-tête du hub.
|
||||
campaign = await seedCampaign(request, {
|
||||
name: `E2E La Chute de la Maison Valcourt — campagne longue ${Date.now()}`,
|
||||
});
|
||||
arc = await seedArc(request, { campaignId: campaign.id });
|
||||
chapter = await seedChapter(request, { arcId: arc.id });
|
||||
scene = await seedScene(request, { chapterId: chapter.id, name: 'La taverne du Corbeau Borgne' });
|
||||
});
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
if (campaign?.id) await deleteCampaign(request, campaign.id);
|
||||
});
|
||||
|
||||
test('hub campagne → scène via l’arborescence en tiroir', async ({ page }) => {
|
||||
await page.goto(`/campaigns/${campaign.id}`);
|
||||
await expect(page.getByRole('heading', { level: 1, name: campaign.name })).toBeVisible();
|
||||
await expectNoHorizontalScroll(page);
|
||||
|
||||
// L'arborescence s'ouvre depuis la barre haute (bouton titré par la campagne).
|
||||
const tree = page.locator('app-secondary-sidebar');
|
||||
await expect(tree).toBeHidden();
|
||||
await page.getByRole('button', { name: "Ouvrir l'arborescence" }).tap();
|
||||
await expect(tree).toBeVisible();
|
||||
|
||||
// Navigation par niveaux : toucher une ligne qui a des enfants « entre » dedans
|
||||
// (sans quitter le volet), jusqu'à la scène. Mode plat ou arc/chapitre selon le seed.
|
||||
const sceneRow = tree.locator('.drill-row', { hasText: scene.name });
|
||||
for (const label of ['Scènes', arc.name, chapter.name]) {
|
||||
if (await sceneRow.isVisible()) break;
|
||||
const row = tree.locator('.drill-row', { hasText: label }).first();
|
||||
if (await row.count()) {
|
||||
await row.tap();
|
||||
await expect(tree.locator('.drill-back')).toBeVisible();
|
||||
await expect(tree).toBeVisible();
|
||||
}
|
||||
}
|
||||
await sceneRow.tap();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/scenes/${scene.id}$`));
|
||||
await expect(page.getByRole('heading', { level: 1, name: scene.name })).toBeVisible();
|
||||
await expect(tree).toBeHidden();
|
||||
await expectNoHorizontalScroll(page);
|
||||
|
||||
// En rouvrant le volet, on retrouve le niveau de la scène, surlignée ; « retour » remonte.
|
||||
await page.getByRole('button', { name: "Ouvrir l'arborescence" }).tap();
|
||||
await expect(tree.locator('.drill-row.active', { hasText: scene.name })).toBeVisible();
|
||||
await tree.locator('.drill-back').tap();
|
||||
await expect(tree.locator('.drill-row.active', { hasText: scene.name })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('écran de séance : journal et horloges lisibles sans scroll horizontal', async ({ page, request }) => {
|
||||
const { sessionId } = await seedPlaythroughWithSession(request, campaign.id);
|
||||
|
||||
await page.goto(`/sessions/${sessionId}`);
|
||||
await expect(page.getByText('Les PJ arrivent à Brumecombe sous la pluie.')).toBeVisible();
|
||||
await expect(page.getByText('Le rituel du nécromancien')).toBeVisible();
|
||||
await expectNoHorizontalScroll(page);
|
||||
|
||||
// Le menu reste accessible depuis la séance.
|
||||
await page.getByRole('button', { name: 'Ouvrir le menu' }).tap();
|
||||
await expect(page.locator('app-sidebar')).toBeVisible();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -42,6 +42,23 @@ module.exports = defineConfig([
|
||||
// Math.random() est légitime ici : tables aléatoires / jets de dés = le
|
||||
// domaine métier. Aucun usage cryptographique côté front.
|
||||
"sonarjs/pseudo-random": "off",
|
||||
// 9 fonctions historiques dépassent le seuil de 15 (jusqu'à 39 sur les
|
||||
// graphes campagne/chapitre). Les refactorer "pour le lint" sans filet de
|
||||
// tests serait plus risqué qu'utile → warn (visible, non bloquant).
|
||||
// Backlog : campaign-graph (×3), chapter-graph (×2), campaign-import,
|
||||
// settings, persona-view, sse.util. Repasser en "error" une fois résorbé.
|
||||
"sonarjs/cognitive-complexity": "warn",
|
||||
// Convention TS standard : un préfixe `_` marque un paramètre/variable
|
||||
// volontairement inutilisé (ex. paramètres conservés pour ne pas casser
|
||||
// les appelants — cf. campaign-tree.helper.ts).
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
caughtErrorsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
Generated
+1104
-884
File diff suppressed because it is too large
Load Diff
+12
-10
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "loremind-web",
|
||||
"version": "1.0.2-beta",
|
||||
"version": "1.3.0-beta",
|
||||
"description": "LoreMind Frontend - Angular",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
@@ -20,20 +20,21 @@
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^21.2.16",
|
||||
"@angular/animations": "^21.2.17",
|
||||
"@angular/cdk": "^21.2.14",
|
||||
"@angular/common": "^21.2.16",
|
||||
"@angular/compiler": "^21.2.16",
|
||||
"@angular/core": "^21.2.16",
|
||||
"@angular/forms": "^21.2.16",
|
||||
"@angular/platform-browser": "^21.2.16",
|
||||
"@angular/platform-browser-dynamic": "^21.2.16",
|
||||
"@angular/router": "^21.2.16",
|
||||
"@angular/common": "^21.2.17",
|
||||
"@angular/compiler": "^21.2.17",
|
||||
"@angular/core": "^21.2.17",
|
||||
"@angular/forms": "^21.2.17",
|
||||
"@angular/platform-browser": "^21.2.17",
|
||||
"@angular/platform-browser-dynamic": "^21.2.17",
|
||||
"@angular/router": "^21.2.17",
|
||||
"@ngx-translate/core": "^18.0.0",
|
||||
"@ngx-translate/http-loader": "^18.0.0",
|
||||
"dompurify": "^3.4.1",
|
||||
"lucide-angular": "^1.0.0",
|
||||
"marked": "^18.0.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
"zone.js": "~0.15.1"
|
||||
@@ -41,11 +42,12 @@
|
||||
"devDependencies": {
|
||||
"@angular-devkit/build-angular": "^21.2.14",
|
||||
"@angular/cli": "^21.2.14",
|
||||
"@angular/compiler-cli": "^21.2.16",
|
||||
"@angular/compiler-cli": "^21.2.17",
|
||||
"@emnapi/core": "^1.11.0",
|
||||
"@emnapi/runtime": "^1.11.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitest/coverage-v8": "^4.1.9",
|
||||
"angular-eslint": "21.4.0",
|
||||
"eslint": "^10.3.0",
|
||||
|
||||
@@ -30,7 +30,21 @@ export default defineConfig({
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
testIgnore: /responsive\//,
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
// Téléphone (375 px, tactile) : shell en tiroirs, absence de scroll horizontal.
|
||||
// Chromium « Desktop Chrome » redimensionné plutôt qu'un preset d'appareil :
|
||||
// même navigateur que la CI (seul chromium y est installé), largeur exacte.
|
||||
{
|
||||
name: 'mobile',
|
||||
testMatch: /responsive\/.*\.spec\.ts/,
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
viewport: { width: 375, height: 812 },
|
||||
isMobile: true,
|
||||
hasTouch: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,10 +1,52 @@
|
||||
<app-update-banner></app-update-banner>
|
||||
|
||||
<div class="app-container">
|
||||
<app-sidebar></app-sidebar>
|
||||
<!-- Barre haute (< 1024 px) : ouvre les tiroirs menu / arborescence. Masquée en CSS sur desktop. -->
|
||||
<header class="mobile-topbar">
|
||||
<button #mainToggle type="button" class="topbar-btn"
|
||||
aria-controls="app-main-nav"
|
||||
[attr.aria-expanded]="openDrawer() === 'main'"
|
||||
[attr.aria-label]="(openDrawer() === 'main' ? 'mobileShell.closeMenu' : 'mobileShell.openMenu') | translate"
|
||||
(click)="toggleDrawer('main')">
|
||||
<lucide-icon [img]="openDrawer() === 'main' ? X : Menu" [size]="20"></lucide-icon>
|
||||
</button>
|
||||
@if (sidebarConfig$ | async; as config) {
|
||||
<button #treeToggle type="button" class="topbar-btn topbar-tree"
|
||||
aria-controls="app-tree-nav"
|
||||
[attr.aria-expanded]="openDrawer() === 'tree'"
|
||||
[attr.aria-label]="(openDrawer() === 'tree' ? 'mobileShell.closeTree' : 'mobileShell.openTree') | translate"
|
||||
(click)="toggleDrawer('tree')">
|
||||
<lucide-icon [img]="PanelLeft" [size]="18"></lucide-icon>
|
||||
<span class="topbar-title">{{ config.title }}</span>
|
||||
</button>
|
||||
} @else {
|
||||
<span class="topbar-brand">
|
||||
<img src="assets/logo.png" alt="" />
|
||||
<span>DM Loremind</span>
|
||||
</span>
|
||||
}
|
||||
<!-- Séance en cours : un tap y ramène (visible seulement si une séance tourne). -->
|
||||
<app-active-session-shortcut compact class="topbar-session"></app-active-session-shortcut>
|
||||
<button type="button" class="topbar-btn topbar-search"
|
||||
[attr.aria-label]="'mobileShell.search' | translate"
|
||||
(click)="openSearch()">
|
||||
<lucide-icon [img]="Search" [size]="18"></lucide-icon>
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<app-sidebar id="app-main-nav"
|
||||
[class.drawer-open]="openDrawer() === 'main'"
|
||||
[attr.role]="isCompact() ? 'dialog' : null"
|
||||
[attr.aria-modal]="isCompact() && openDrawer() === 'main' ? 'true' : null"
|
||||
[attr.aria-label]="'mobileShell.mainNav' | translate"></app-sidebar>
|
||||
|
||||
@if (sidebarConfig$ | async; as config) {
|
||||
<app-secondary-sidebar
|
||||
<app-secondary-sidebar id="app-tree-nav"
|
||||
[class.drawer-open]="openDrawer() === 'tree'"
|
||||
[attr.role]="isCompact() ? 'dialog' : null"
|
||||
[attr.aria-modal]="isCompact() && openDrawer() === 'tree' ? 'true' : null"
|
||||
[attr.aria-label]="'mobileShell.treeNav' | translate"
|
||||
[drawerMode]="isCompact()"
|
||||
[title]="config.title"
|
||||
[titleRoute]="config.titleRoute || null"
|
||||
[items]="config.items"
|
||||
@@ -16,10 +58,15 @@
|
||||
</app-secondary-sidebar>
|
||||
}
|
||||
|
||||
<main class="main-content">
|
||||
@if (openDrawer()) {
|
||||
<div class="drawer-backdrop" aria-hidden="true" (click)="closeDrawer()"></div>
|
||||
}
|
||||
|
||||
<main #mainContent class="main-content" tabindex="-1">
|
||||
<router-outlet></router-outlet>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<app-global-search></app-global-search>
|
||||
<app-confirm-dialog-host></app-confirm-dialog-host>
|
||||
<app-writing-coach-panel></app-writing-coach-panel>
|
||||
|
||||
@@ -1,14 +1,144 @@
|
||||
// Points de rupture du shell (cf. styles/_responsive.scss) :
|
||||
// - >= 1024 px : colonnes fixes (menu + arborescence + contenu) ;
|
||||
// - < 1024 px : barre haute + menu et arborescence en tiroirs off-canvas ;
|
||||
// - < 768 px : une seule colonne, marges réduites.
|
||||
$compact: 1023.98px;
|
||||
$phone: 767.98px;
|
||||
$topbar-height: 52px;
|
||||
|
||||
.app-container {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
// min-width: 0 — sans ça un contenu large (tableau, graphe) élargit la colonne
|
||||
// flex au lieu de défiler dedans, et toute la page déborde horizontalement.
|
||||
min-width: 0;
|
||||
// padding-top: 0 — sinon le contenu defile dans la zone de padding
|
||||
// au-dessus du `.page-header` sticky (top: 0 pin sur l'edge interne du
|
||||
// padding-box). Chaque page-wrapper definit deja son propre padding-top
|
||||
// qui devient l'unique source d'espacement haut.
|
||||
padding: 0 2rem 2rem;
|
||||
overflow-y: auto;
|
||||
|
||||
// Focus programmatique après navigation depuis un tiroir : pas d'anneau visible.
|
||||
&:focus { outline: none; }
|
||||
}
|
||||
|
||||
.mobile-topbar,
|
||||
.drawer-backdrop { display: none; }
|
||||
|
||||
@media (max-width: $compact) {
|
||||
.app-container { flex-direction: column; }
|
||||
|
||||
.mobile-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
flex: 0 0 auto;
|
||||
height: $topbar-height;
|
||||
padding: 0 0.5rem;
|
||||
background: #0f0f1a;
|
||||
border-bottom: 1px solid #1e1e3a;
|
||||
position: relative;
|
||||
z-index: 120;
|
||||
}
|
||||
|
||||
.topbar-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 44px;
|
||||
height: 44px;
|
||||
padding: 0 0.6rem;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
color: #d1d5db;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover, &[aria-expanded='true'] { background: #1f2937; color: white; }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: -2px; }
|
||||
}
|
||||
|
||||
// Le bouton arborescence porte le titre de la section (campagne, lore) et prend
|
||||
// toute la place disponible : c'est la cible la plus utilisée au doigt.
|
||||
.topbar-tree {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
justify-content: flex-start;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.topbar-title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.topbar-brand {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
padding-left: 0.25rem;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
|
||||
img { width: 1.5rem; height: 1.5rem; border-radius: 5px; }
|
||||
}
|
||||
|
||||
// Les deux sidebars deviennent des tiroirs : hors flux, cachés à gauche.
|
||||
// visibility: hidden (retardée le temps de l'animation) les sort aussi de
|
||||
// l'ordre de tabulation quand ils sont fermés.
|
||||
app-sidebar,
|
||||
app-secondary-sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 150;
|
||||
max-width: 88vw;
|
||||
transform: translateX(-100%);
|
||||
visibility: hidden;
|
||||
transition: transform 0.25s ease, visibility 0s linear 0.25s;
|
||||
box-shadow: 4px 0 24px rgba(0, 0, 0, 0.5);
|
||||
|
||||
&.drawer-open {
|
||||
transform: none;
|
||||
visibility: visible;
|
||||
transition: transform 0.25s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.drawer-backdrop {
|
||||
display: block;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 149;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
padding: 0 1.25rem 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: $phone) {
|
||||
.main-content { padding: 0 0.75rem 1.25rem; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
app-sidebar,
|
||||
app-secondary-sidebar,
|
||||
app-sidebar.drawer-open,
|
||||
app-secondary-sidebar.drawer-open { transition: none; }
|
||||
}
|
||||
|
||||
@@ -1,24 +1,43 @@
|
||||
import { Component, HostListener } from '@angular/core';
|
||||
import { Component, ElementRef, HostListener, effect, inject, signal, viewChild } from '@angular/core';
|
||||
import { AsyncPipe } from '@angular/common';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { BreakpointObserver } from '@angular/cdk/layout';
|
||||
import { NavigationEnd, NavigationSkipped, Router, RouterOutlet } from '@angular/router';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
import { LucideAngularModule, Menu, PanelLeft, Search, X } from 'lucide-angular';
|
||||
import { filter, map } from 'rxjs';
|
||||
import { SidebarComponent } from './sidebar/sidebar.component';
|
||||
import { SecondarySidebarComponent } from './shared/secondary-sidebar/secondary-sidebar.component';
|
||||
import { GlobalSearchComponent } from './shared/global-search/global-search.component';
|
||||
import { UpdateBannerComponent } from './shared/update-banner/update-banner.component';
|
||||
import { ConfirmDialogHostComponent } from './shared/confirm-dialog/confirm-dialog-host.component';
|
||||
import { WritingCoachPanelComponent } from './shared/writing-coach/writing-coach-panel.component';
|
||||
import { ActiveSessionShortcutComponent } from './sessions/active-session-shortcut/active-session-shortcut.component';
|
||||
import { LayoutService } from './services/layout.service';
|
||||
import { GlobalSearchService } from './services/global-search.service';
|
||||
import { VersionCheckerService } from './services/version-checker.service';
|
||||
|
||||
/** Sous cette largeur, les deux sidebars deviennent des tiroirs off-canvas (tablette, téléphone). */
|
||||
const COMPACT_QUERY = '(max-width: 1023.98px)';
|
||||
|
||||
/** Tiroir ouvert en mode compact : menu principal, arborescence secondaire, ou aucun. */
|
||||
type ShellDrawer = 'main' | 'tree' | null;
|
||||
|
||||
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [
|
||||
RouterOutlet,
|
||||
LucideAngularModule,
|
||||
TranslatePipe,
|
||||
SidebarComponent,
|
||||
SecondarySidebarComponent,
|
||||
GlobalSearchComponent,
|
||||
UpdateBannerComponent,
|
||||
ConfirmDialogHostComponent,
|
||||
WritingCoachPanelComponent,
|
||||
ActiveSessionShortcutComponent,
|
||||
AsyncPipe
|
||||
],
|
||||
templateUrl: './app.component.html',
|
||||
@@ -27,6 +46,29 @@ import { VersionCheckerService } from './services/version-checker.service';
|
||||
export class AppComponent {
|
||||
readonly sidebarConfig$ = this.layoutService.secondarySidebar$;
|
||||
|
||||
readonly Menu = Menu;
|
||||
readonly PanelLeft = PanelLeft;
|
||||
readonly Search = Search;
|
||||
readonly X = X;
|
||||
|
||||
private readonly breakpoints = inject(BreakpointObserver);
|
||||
private readonly router = inject(Router);
|
||||
|
||||
/** True sous 1024 px : barre haute + tiroirs au lieu des colonnes fixes. */
|
||||
readonly isCompact = toSignal(
|
||||
this.breakpoints.observe(COMPACT_QUERY).pipe(map(state => state.matches)),
|
||||
{ initialValue: this.breakpoints.isMatched(COMPACT_QUERY) }
|
||||
);
|
||||
|
||||
/** Tiroir ouvert (mode compact uniquement). */
|
||||
readonly openDrawer = signal<ShellDrawer>(null);
|
||||
|
||||
private readonly mainDrawerRef = viewChild(SidebarComponent, { read: ElementRef });
|
||||
private readonly treeDrawerRef = viewChild(SecondarySidebarComponent, { read: ElementRef });
|
||||
private readonly mainToggleRef = viewChild<ElementRef<HTMLButtonElement>>('mainToggle');
|
||||
private readonly treeToggleRef = viewChild<ElementRef<HTMLButtonElement>>('treeToggle');
|
||||
private readonly mainContentRef = viewChild<ElementRef<HTMLElement>>('mainContent');
|
||||
|
||||
constructor(
|
||||
private layoutService: LayoutService,
|
||||
private globalSearch: GlobalSearchService,
|
||||
@@ -36,6 +78,48 @@ export class AppComponent {
|
||||
// Si une nouvelle version est deployee pendant la session, l'UpdateBanner
|
||||
// s'affichera automatiquement.
|
||||
versionChecker.start();
|
||||
|
||||
// Retour en largeur desktop : les tiroirs n'ont plus de sens, on les referme.
|
||||
effect(() => {
|
||||
if (!this.isCompact()) this.openDrawer.set(null);
|
||||
});
|
||||
|
||||
// Une navigation (y compris vers l'URL courante, NavigationSkipped) referme le
|
||||
// tiroir : on choisit une page, on veut la voir. Le focus part sur le contenu.
|
||||
this.router.events.pipe(
|
||||
filter(e => e instanceof NavigationEnd || e instanceof NavigationSkipped),
|
||||
takeUntilDestroyed(),
|
||||
).subscribe(() => {
|
||||
if (!this.openDrawer()) return;
|
||||
this.openDrawer.set(null);
|
||||
this.mainContentRef()?.nativeElement.focus({ preventScroll: true });
|
||||
});
|
||||
|
||||
// La recherche globale passe au-dessus : inutile de laisser le tiroir ouvert dessous.
|
||||
this.globalSearch.open$.pipe(filter(Boolean), takeUntilDestroyed()).subscribe(() => this.openDrawer.set(null));
|
||||
}
|
||||
|
||||
toggleDrawer(drawer: Exclude<ShellDrawer, null>): void {
|
||||
if (this.openDrawer() === drawer) {
|
||||
this.closeDrawer();
|
||||
return;
|
||||
}
|
||||
this.openDrawer.set(drawer);
|
||||
// Focus sur le premier élément du tiroir une fois rendu visible.
|
||||
setTimeout(() => this.focusables(this.drawerElement())[0]?.focus());
|
||||
}
|
||||
|
||||
/** Ferme le tiroir et rend le focus au bouton de la barre haute qui l'a ouvert. */
|
||||
closeDrawer(): void {
|
||||
const drawer = this.openDrawer();
|
||||
if (!drawer) return;
|
||||
this.openDrawer.set(null);
|
||||
const toggle = drawer === 'main' ? this.mainToggleRef() : this.treeToggleRef();
|
||||
toggle?.nativeElement.focus();
|
||||
}
|
||||
|
||||
openSearch(): void {
|
||||
this.globalSearch.open();
|
||||
}
|
||||
|
||||
@HostListener('document:keydown', ['$event'])
|
||||
@@ -44,6 +128,45 @@ export class AppComponent {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
|
||||
event.preventDefault();
|
||||
this.globalSearch.toggle();
|
||||
return;
|
||||
}
|
||||
if (!this.openDrawer()) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.closeDrawer();
|
||||
} else if (event.key === 'Tab') {
|
||||
this.trapFocus(event);
|
||||
}
|
||||
}
|
||||
|
||||
/** Garde le focus clavier dans le tiroir ouvert (comportement de modale). */
|
||||
private trapFocus(event: KeyboardEvent): void {
|
||||
const drawer = this.drawerElement();
|
||||
const items = this.focusables(drawer);
|
||||
if (!drawer || !items.length) return;
|
||||
const first = items[0];
|
||||
const last = items[items.length - 1];
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
const inside = !!active && drawer.contains(active);
|
||||
if (event.shiftKey && (active === first || !inside)) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && (active === last || !inside)) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
private drawerElement(): HTMLElement | null {
|
||||
const drawer = this.openDrawer();
|
||||
if (drawer === 'main') return this.mainDrawerRef()?.nativeElement ?? null;
|
||||
if (drawer === 'tree') return this.treeDrawerRef()?.nativeElement ?? null;
|
||||
return null;
|
||||
}
|
||||
|
||||
private focusables(root: HTMLElement | null): HTMLElement[] {
|
||||
if (!root) return [];
|
||||
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE))
|
||||
.filter(el => el.offsetParent !== null || el.getClientRects().length > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ export const routes: Routes = [
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId/edit', loadComponent: () => import('./campaigns/random-table/random-table-edit/random-table-edit.component').then(m => m.RandomTableEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId', loadComponent: () => import('./campaigns/random-table/random-table-view/random-table-view.component').then(m => m.RandomTableViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/create', loadComponent: () => import('./campaigns/arc/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
|
||||
{ path: 'campaigns/:campaignId/guided/:method', loadComponent: () => import('./campaigns/guided/guided-wizard/guided-wizard.component').then(m => m.GuidedWizardComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId', loadComponent: () => import('./campaigns/arc/arc-view/arc-view.component').then(m => m.ArcViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId/edit', loadComponent: () => import('./campaigns/arc/arc-edit/arc-edit.component').then(m => m.ArcEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/create', loadComponent: () => import('./campaigns/chapter/chapter-create/chapter-create.component').then(m => m.ChapterCreateComponent) },
|
||||
@@ -60,6 +61,8 @@ export const routes: Routes = [
|
||||
{ path: 'game-systems/:id/edit', loadComponent: () => import('./game-systems/game-system-edit/game-system-edit.component').then(m => m.GameSystemEditComponent) },
|
||||
// Routes masquees en mode demo : ajouter canActivate: [hiddenInDemoGuard]
|
||||
// (a prevoir aussi sur la future route d'export VTT).
|
||||
// Accès distant (mode bureau) : appairage d'une tablette par code.
|
||||
{ path: 'pair', loadComponent: () => import('./remote-access/remote-pair/remote-pair.component').then(m => m.RemotePairComponent) },
|
||||
{ path: 'settings', canActivate: [hiddenInDemoGuard], loadComponent: () => import('./settings/settings.component').then(m => m.SettingsComponent) },
|
||||
{ path: '', redirectTo: '/lore', pathMatch: 'full' }
|
||||
];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
@@ -25,7 +25,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
templateUrl: './arc-create.component.html',
|
||||
styleUrls: ['./arc-create.component.scss']
|
||||
})
|
||||
export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
export class ArcCreateComponent implements OnInit {
|
||||
readonly BookOpen = BookOpen;
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
|
||||
@@ -88,11 +88,4 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,9 @@
|
||||
<!-- Tout est optionnel sauf le titre : identité visible, le reste replié. -->
|
||||
<p class="optional-hint">{{ 'arcEdit.optionalHint' | translate }}</p>
|
||||
|
||||
<!-- Mentor d'écriture (M2) : conseils de relecture qui concernent cette entité. -->
|
||||
<app-writing-review-hints [campaignId]="campaignId" entityType="ARC" [entityId]="arcId"></app-writing-review-hints>
|
||||
|
||||
<!-- Co-création (Pilier A) : le co-MJ propose, validation champ par champ → remplit le formulaire. -->
|
||||
<app-entity-assist-panel
|
||||
[entityType]="'arc'" [entityId]="arcId" [campaignId]="campaignId"
|
||||
@@ -47,7 +50,10 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-description">{{ 'arcEdit.synopsisLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-description">{{ 'arcEdit.synopsisLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.synopsis"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-description"
|
||||
formControlName="description"
|
||||
@@ -89,10 +95,13 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Thèmes et enjeux -->
|
||||
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [filled]="themesStakesFilled">
|
||||
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [initiallyOpen]="focusSection === 'stakes'" [filled]="themesStakesFilled">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="arc-edit-themes">{{ 'arcEdit.themesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-themes">{{ 'arcEdit.themesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.themes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-themes"
|
||||
formControlName="themes"
|
||||
@@ -101,7 +110,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="arc-edit-stakes">{{ 'arcEdit.stakesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-stakes">{{ 'arcEdit.stakesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.stakes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-stakes"
|
||||
formControlName="stakes"
|
||||
@@ -129,7 +141,10 @@
|
||||
<!-- Récompenses et dénouement -->
|
||||
<app-expandable-section [title]="'arcEdit.rewardsResolutionSectionTitle' | translate" icon="🎁" [filled]="rewardsResolutionFilled">
|
||||
<div class="field">
|
||||
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.rewards"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-rewards"
|
||||
formControlName="rewards"
|
||||
@@ -138,7 +153,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.resolution"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-resolution"
|
||||
formControlName="resolution"
|
||||
@@ -183,5 +201,5 @@
|
||||
[isOpen]="chatOpen"
|
||||
[welcomeMessage]="'arcEdit.chatWelcome' | translate"
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
(closed)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
@@ -26,6 +26,8 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
|
||||
import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { WritingReviewHintsComponent } from '../../../shared/writing-review/writing-review-hints.component';
|
||||
|
||||
/**
|
||||
* Écran de détail/modification d'un Arc.
|
||||
@@ -38,11 +40,11 @@ import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-edit',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
|
||||
templateUrl: './arc-edit.component.html',
|
||||
styleUrls: ['./arc-edit.component.scss']
|
||||
})
|
||||
export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
export class ArcEditComponent implements OnInit {
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Sparkles = Sparkles;
|
||||
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
|
||||
@@ -74,6 +76,9 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
arcId = '';
|
||||
arc: Arc | null = null;
|
||||
|
||||
/** `?focus=stakes` (lien « Voir » de la relecture d'éditeur) → section dépliée d'office. */
|
||||
focusSection: string | null = null;
|
||||
|
||||
/** Pages disponibles pour le picker (vide si la campagne n'a pas de loreId). */
|
||||
availablePages: Page[] = [];
|
||||
/** ID du Lore associé à la campagne (null si campagne sans univers). */
|
||||
@@ -135,6 +140,7 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
if (newArcId !== this.arcId || newCampaignId !== this.campaignId) {
|
||||
this.campaignId = newCampaignId;
|
||||
this.arcId = newArcId;
|
||||
this.focusSection = this.route.snapshot.queryParamMap.get('focus');
|
||||
this.loadAll();
|
||||
}
|
||||
});
|
||||
@@ -221,11 +227,4 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
||||
cancel(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'arcs', this.arcId]);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant
|
||||
// suivant (autre sous-route ou le composant detail parent) qui appellera
|
||||
// show(). Eviter d'appeler hide() ici previent le clignotement / la
|
||||
// disparition de la sidebar lors des navigations internes a la section.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, OnInit, OnDestroy, DestroyRef } from '@angular/core';
|
||||
import { Component, OnInit, DestroyRef } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
@@ -35,7 +35,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
templateUrl: './arc-view.component.html',
|
||||
styleUrls: ['./arc-view.component.scss']
|
||||
})
|
||||
export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
export class ArcViewComponent implements OnInit {
|
||||
readonly Pencil = Pencil;
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Plus = Plus;
|
||||
@@ -162,8 +162,4 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
||||
error: () => console.error('Impossible de récupérer les dépendances de l\'arc')
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
// Volontairement vide : la sidebar reste prise en charge par le composant suivant.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
private readonly DRAG_THRESHOLD = 4;
|
||||
|
||||
// Adjacence (ids de nœuds) — sert à recalculer les arêtes après un drag.
|
||||
private adjacency: Array<{ key: string; kind: NodeKind; a: string; b: string }> = [];
|
||||
private adjacency: { key: string; kind: NodeKind; a: string; b: string }[] = [];
|
||||
|
||||
// Disposition personnalisée : positions sauvegardées sur la campagne, sauvegarde
|
||||
// différée après un drag (évite un PUT par pixel déplacé).
|
||||
@@ -174,7 +174,10 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
if (this.draggingId) return; // pas de changement de focus en plein drag
|
||||
this.hoveredId = node.id;
|
||||
this.hoverNeighbors = new Set(
|
||||
this.adjacency.flatMap(e => e.a === node.id ? [e.b] : e.b === node.id ? [e.a] : []));
|
||||
this.adjacency.flatMap(e => {
|
||||
if (e.a === node.id) return [e.b];
|
||||
return e.b === node.id ? [e.a] : [];
|
||||
}));
|
||||
}
|
||||
|
||||
onNodeLeave(): void {
|
||||
@@ -230,7 +233,7 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
for (const [arcId, chapters] of Object.entries(treeData.chaptersByArc)) {
|
||||
for (const ch of chapters) arcOfChapter.set(ch.id!, arcId);
|
||||
}
|
||||
const linkedScenes: Array<{ scene: Scene; chapterId: string }> = [];
|
||||
const linkedScenes: { scene: Scene; chapterId: string }[] = [];
|
||||
if (!this.hiddenKinds.has('scene')) {
|
||||
for (const [chapterId, scenes] of Object.entries(treeData.scenesByChapter)) {
|
||||
if (!arcOfChapter.has(chapterId)) continue;
|
||||
@@ -268,7 +271,7 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
|
||||
// Arêtes. Les liens page↔page sont dé-dupliqués par paire non-orientée
|
||||
// (A→B et B→A = un seul trait) ; les liens entité→page portent le type de l'entité.
|
||||
const adjacency: Array<{ key: string; kind: NodeKind; a: string; b: string }> = [];
|
||||
const adjacency: { key: string; kind: NodeKind; a: string; b: string }[] = [];
|
||||
const seenPairs = new Set<string>();
|
||||
for (const p of pages) {
|
||||
for (const targetId of p.relatedPageIds ?? []) {
|
||||
@@ -530,14 +533,16 @@ export class CampaignGraphComponent implements OnInit, OnDestroy {
|
||||
if (Math.abs(dx) >= needX || Math.abs(dy) >= needY) continue;
|
||||
const overlapX = needX - Math.abs(dx);
|
||||
const overlapY = needY - Math.abs(dy);
|
||||
// Départage déterministe quand les centres coïncident (dx/dy = 0).
|
||||
const tieBreak = i % 2 === 0 ? 1 : -1;
|
||||
if (overlapX / needX < overlapY / needY) {
|
||||
const shift = overlapX / 2 + 0.5;
|
||||
const sign = dx !== 0 ? Math.sign(dx) : (i % 2 === 0 ? 1 : -1);
|
||||
const sign = dx !== 0 ? Math.sign(dx) : tieBreak;
|
||||
a.x -= sign * shift;
|
||||
b.x += sign * shift;
|
||||
} else {
|
||||
const shift = overlapY / 2 + 0.5;
|
||||
const sign = dy !== 0 ? Math.sign(dy) : (i % 2 === 0 ? 1 : -1);
|
||||
const sign = dy !== 0 ? Math.sign(dy) : tieBreak;
|
||||
a.y -= sign * shift;
|
||||
b.y += sign * shift;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,29 @@ describe('buildCampaignTree', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('place un nœud « Parties » en tête (avant la narration), une entrée par partie', () => {
|
||||
const tree = buildCampaignTree('c1', data({
|
||||
arcs: [{ id: 'a1', name: 'Arc', type: 'LINEAR' }] as never,
|
||||
chaptersByArc: { a1: [{ id: 'ch1', name: 'C1' }, { id: 'ch2', name: 'C2' }] } as never,
|
||||
playthroughs: [
|
||||
{ id: 'p1', campaignId: 'c1', name: 'Table du mardi' },
|
||||
{ id: 'p2', campaignId: 'c1', name: 'Table du jeudi' },
|
||||
],
|
||||
}), t);
|
||||
expect(tree[0].id).toBe('playthroughs-root');
|
||||
expect(tree[0].sectionHeaderBefore).toBe('campaignTree.sectionPlay');
|
||||
expect(tree[0].meta).toBe('2');
|
||||
expect(tree[0].children!.map((c) => c.route)).toEqual([
|
||||
'/campaigns/c1/playthroughs/p1', '/campaigns/c1/playthroughs/p2',
|
||||
]);
|
||||
expect(tree[1].id).toBe('arc-a1');
|
||||
});
|
||||
|
||||
it('pas de nœud « Parties » sans partie', () => {
|
||||
const tree = buildCampaignTree('c1', data({ playthroughs: [] }), t);
|
||||
expect(tree.some((n) => n.id === 'playthroughs-root')).toBe(false);
|
||||
});
|
||||
|
||||
it('trie les arcs par ordre manuel (champ order, réagencé au glisser-déposer)', () => {
|
||||
const arcs = [
|
||||
{ id: 'a', name: 'Final', order: 2 },
|
||||
|
||||
@@ -7,7 +7,7 @@ import { RandomTableService } from '../services/random-table.service';
|
||||
import { EnemyService } from '../services/enemy.service';
|
||||
import { TreeItem, TreeCreateAction, SecondarySidebarConfig, GlobalItem, ReorderKind } from '../services/layout.service';
|
||||
import { groupByFolder, byOrder } from '../shared/folder-grouping.util';
|
||||
import { Arc, Chapter, Scene, Campaign, Quest } from '../services/campaign.model';
|
||||
import { Arc, Chapter, Scene, Campaign, Quest, Playthrough } from '../services/campaign.model';
|
||||
import { Npc } from '../services/npc.model';
|
||||
import { RandomTable } from '../services/random-table.model';
|
||||
import { Enemy } from '../services/enemy.model';
|
||||
@@ -34,6 +34,8 @@ export interface CampaignTreeData {
|
||||
quests?: Quest[];
|
||||
/** Bilan de readiness complet — évite un fetch séparé pour le panneau du hub. */
|
||||
readiness?: CampaignReadinessAssessment | null;
|
||||
/** Parties (Playthroughs) — nœud « Parties » en tête d'arbre (accès direct aux séances). Optionnel. */
|
||||
playthroughs?: Playthrough[];
|
||||
}
|
||||
|
||||
export function loadCampaignTreeData(
|
||||
@@ -56,13 +58,14 @@ export function loadCampaignTreeData(
|
||||
randomTables: tree.randomTables ?? [],
|
||||
enemies: tree.enemies ?? [],
|
||||
quests: tree.quests ?? [],
|
||||
playthroughs: tree.playthroughs ?? [],
|
||||
gaps: tree.readiness?.gaps ?? [],
|
||||
readiness: tree.readiness ?? null
|
||||
} as CampaignTreeData)),
|
||||
// Dégradation gracieuse : sidebar vide plutôt qu'écran cassé si le back est indisponible.
|
||||
catchError(() => of({
|
||||
arcs: [], chaptersByArc: {}, scenesByChapter: {},
|
||||
npcs: [], randomTables: [], enemies: [], quests: [], gaps: [], readiness: null
|
||||
npcs: [], randomTables: [], enemies: [], quests: [], playthroughs: [], gaps: [], readiness: null
|
||||
} as CampaignTreeData))
|
||||
);
|
||||
}
|
||||
@@ -82,7 +85,10 @@ export function buildCampaignTree(
|
||||
// Clé TYPE|ID obligatoire : chaque table a sa propre séquence IDENTITY (une quête
|
||||
// id 6 et une scène id 6 coexistent) — sans le type, un manque de quête allumerait
|
||||
// à tort la pastille d'une scène/PNJ portant le même numéro.
|
||||
const sevRank = (s: ReadinessSeverity): number => (s === 'BLOCKING' ? 2 : s === 'RECOMMENDED' ? 1 : 0);
|
||||
const sevRank = (s: ReadinessSeverity): number => {
|
||||
if (s === 'BLOCKING') return 2;
|
||||
return s === 'RECOMMENDED' ? 1 : 0;
|
||||
};
|
||||
const gapsByKey = new Map<string, ReadinessGap[]>();
|
||||
for (const g of readinessGaps) {
|
||||
const key = `${g.entityType}|${g.entityId}`;
|
||||
@@ -456,7 +462,31 @@ export function buildCampaignTree(
|
||||
}]
|
||||
};
|
||||
|
||||
return [...narrationNodes, questsNode, npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode];
|
||||
// Parties (Playthroughs) : EN TÊTE d'arbre, avant la narration — c'est par une Partie
|
||||
// qu'on lance/reprend une séance ; enfouies en bas du hub, on finissait par les manquer.
|
||||
const playthroughItems: TreeItem[] = (data.playthroughs ?? [])
|
||||
.filter(p => !!p.id)
|
||||
.map(p => ({
|
||||
id: `playthrough-${p.id}`,
|
||||
label: p.name,
|
||||
iconKey: 'c-dice',
|
||||
route: `/campaigns/${campaignId}/playthroughs/${p.id}`
|
||||
}));
|
||||
const playthroughsNode: TreeItem | null = playthroughItems.length ? {
|
||||
id: 'playthroughs-root',
|
||||
label: translate.instant('campaignTree.playthroughs'),
|
||||
iconKey: 'c-dice',
|
||||
children: playthroughItems,
|
||||
meta: String(playthroughItems.length),
|
||||
// Libellé → hub (bloc « Jouer » + liste des Parties) ; chevron → une Partie par nœud.
|
||||
route: `/campaigns/${campaignId}`,
|
||||
sectionHeaderBefore: translate.instant('campaignTree.sectionPlay')
|
||||
} : null;
|
||||
|
||||
return [
|
||||
...(playthroughsNode ? [playthroughsNode] : []),
|
||||
...narrationNodes, questsNode, npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
[placeholder]="'campaignCreate.gameSystemNamePlaceholder' | translate"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
|
||||
/>
|
||||
<div class="inline-create-actions">
|
||||
<button type="button" class="btn-inline-primary"
|
||||
|
||||
@@ -29,7 +29,7 @@ export interface CampaignCreatePayload {
|
||||
styleUrls: ['./campaign-create.component.scss']
|
||||
})
|
||||
export class CampaignCreateComponent implements OnInit {
|
||||
@Output() close = new EventEmitter<void>();
|
||||
@Output() closed = new EventEmitter<void>();
|
||||
@Output() created = new EventEmitter<CampaignCreatePayload>();
|
||||
|
||||
readonly BookCopy = BookCopy;
|
||||
@@ -131,6 +131,6 @@ export class CampaignCreateComponent implements OnInit {
|
||||
}
|
||||
|
||||
onCancel(): void {
|
||||
this.close.emit();
|
||||
this.closed.emit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,9 +59,19 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<!-- ============ Jouer : reprendre / démarrer une séance (accès direct) ============ -->
|
||||
@if (!editing && campaign.id) {
|
||||
<app-campaign-play-block
|
||||
[playthroughs]="playthroughs"
|
||||
[creatingPlaythrough]="newPlaythroughInFlight"
|
||||
(createPlaythrough)="createPlaythrough()">
|
||||
</app-campaign-play-block>
|
||||
}
|
||||
<!-- ============ Guidage co-MJ : « Prochaines étapes » (Pilier B) ============ -->
|
||||
@if (!editing && campaign.id) {
|
||||
<app-readiness-panel [campaignId]="campaign.id" [assessment]="readiness"></app-readiness-panel>
|
||||
<!-- Mentor d'écriture (M2) : conseils d'auteur sur la qualité, à côté de la complétude. -->
|
||||
<app-writing-review-panel [campaignId]="campaign.id"></app-writing-review-panel>
|
||||
}
|
||||
<!-- ============ Header : mode édition inline ============ -->
|
||||
@if (editing) {
|
||||
@@ -106,7 +116,7 @@
|
||||
[placeholder]="'campaignDetail.gameSystemNamePlaceholder' | translate"
|
||||
(keydown.enter)="$event.preventDefault(); submitCreateGameSystem()"
|
||||
(keydown.escape)="cancelCreateGameSystem()"
|
||||
autofocus
|
||||
|
||||
/>
|
||||
<div class="inline-create-actions">
|
||||
<button type="button" class="btn-inline-primary"
|
||||
@@ -206,6 +216,11 @@
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
{{ 'campaignDetail.newArc' | translate }}
|
||||
</button>
|
||||
<!-- Mentor d'écriture (M3) : écrire une aventure question par question. -->
|
||||
<a class="btn-add btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ 'guided.entry' | translate }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
@if (arcs.length > 0 && !showQuickAddScene) {
|
||||
@@ -235,6 +250,10 @@
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
{{ 'campaignDetail.quickSceneFirst' | translate }}
|
||||
</button>
|
||||
<a class="btn-add-first btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ 'guided.entryFirst' | translate }}
|
||||
</a>
|
||||
<button type="button" class="empty-alt-action" (click)="createArc()">
|
||||
{{ 'campaignDetail.organizeInArcs' | translate }}
|
||||
</button>
|
||||
|
||||
@@ -173,16 +173,28 @@
|
||||
border-bottom: 1px solid #1f2937;
|
||||
margin-bottom: 1.5rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1.5rem;
|
||||
gap: 1rem 1.5rem;
|
||||
|
||||
.header-texts { flex: 1; min-width: 0; }
|
||||
// Le bloc titre réclame ~280 px ; s'il ne les a pas à côté des actions
|
||||
// (tablette, desktop étroit), les actions passent dessous et s'y répartissent.
|
||||
.header-texts { flex: 1 1 280px; min-width: 0; }
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
// Téléphone : l'en-tête (titre + 5 actions) mangerait la moitié de l'écran
|
||||
// s'il restait collé en haut pendant le défilement.
|
||||
@media (max-width: 767.98px) {
|
||||
position: static;
|
||||
|
||||
h1 { overflow-wrap: anywhere; }
|
||||
}
|
||||
|
||||
// Variante mode édition : champs empilés verticalement.
|
||||
@@ -295,8 +307,10 @@
|
||||
|
||||
.section-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap; // écran étroit : les actions passent sous le titre au lieu de déborder
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
h2 { color: #d1d5db; font-size: 1rem; font-weight: 600; }
|
||||
@@ -304,6 +318,7 @@
|
||||
|
||||
.section-header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
@@ -486,6 +501,18 @@
|
||||
&:hover { background: #5b52e0; }
|
||||
}
|
||||
|
||||
// Entrée « Méthode guidée » (Mentor d'écriture, M3) : un lien stylé en bouton,
|
||||
// accent ambré du mentor pour le distinguer des créations « à la main ».
|
||||
.btn-guided {
|
||||
text-decoration: none;
|
||||
background: rgba(251, 191, 36, 0.12);
|
||||
color: #fde68a;
|
||||
border: 1px solid rgba(251, 191, 36, 0.35);
|
||||
|
||||
&:hover { background: rgba(251, 191, 36, 0.2); }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
|
||||
}
|
||||
|
||||
// Action secondaire de l'état vide (« ou créer un arc ») — bouton texte discret.
|
||||
.empty-alt-action {
|
||||
background: none;
|
||||
|
||||
@@ -32,11 +32,13 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
import { FolderGroup, groupByFolder, byOrder } from '../../../shared/folder-grouping.util';
|
||||
import { CampaignReadinessAssessment } from '../../../services/readiness.model';
|
||||
import { ReadinessPanelComponent } from '../../../shared/readiness-panel/readiness-panel.component';
|
||||
import { WritingReviewPanelComponent } from '../../../shared/writing-review/writing-review-panel.component';
|
||||
import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play-block.component';
|
||||
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-detail',
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, FoundryExportDialogComponent],
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, CampaignPlayBlockComponent, FoundryExportDialogComponent],
|
||||
templateUrl: './campaign-detail.component.html',
|
||||
styleUrls: ['./campaign-detail.component.scss']
|
||||
})
|
||||
@@ -94,14 +96,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
editPlaythroughName = '';
|
||||
/** Sessions de jeu (passées et en cours) liées à cette campagne. */
|
||||
sessions: Session[] = [];
|
||||
/**
|
||||
* Session active globale (toutes campagnes confondues).
|
||||
* Sert à désactiver le bouton "Lancer" si une session tourne déjà ailleurs.
|
||||
* Null si aucune session active dans l'app.
|
||||
*/
|
||||
activeSessionGlobal: Session | null = null;
|
||||
/** Indicateur de lancement en cours pour éviter les double-clics. */
|
||||
startingSession = false;
|
||||
|
||||
/** Parties (Playthroughs) de cette campagne. */
|
||||
playthroughs: Playthrough[] = [];
|
||||
@@ -214,6 +208,18 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
||||
this.showLayout(allCampaigns, treeData);
|
||||
this.pageTitleService.set(campaign.name);
|
||||
this.openEditFromQueryParam();
|
||||
}
|
||||
|
||||
/**
|
||||
* `?edit=system` (lien « Choisir le système » de l'onglet Règles en séance) : ouvre
|
||||
* directement l'édition inline, puis retire le paramètre pour qu'un rechargement
|
||||
* ne la rouvre pas.
|
||||
*/
|
||||
private openEditFromQueryParam(): void {
|
||||
if (!this.route.snapshot.queryParamMap.has('edit')) return;
|
||||
this.startEdit();
|
||||
this.router.navigate([], { relativeTo: this.route, queryParams: { edit: null }, queryParamsHandling: 'merge', replaceUrl: true });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -52,6 +52,19 @@ interface NpcNode { name: string; description: string; selected: boolean; existi
|
||||
* Flux : upload → progression streamée → arbre éditable (revue) → création.
|
||||
* Rien n'est créé tant que l'utilisateur n'a pas validé « Créer dans la campagne ».
|
||||
*/
|
||||
|
||||
/** Nettoie les pièces (rooms) d'une scène pour le payload de création. */
|
||||
function cleanRooms(rooms: { name: string; description: string; enemies: string; loot: string }[]) {
|
||||
return rooms
|
||||
.filter(r => r.name.trim())
|
||||
.map(r => ({
|
||||
name: r.name.trim(),
|
||||
description: r.description.trim(),
|
||||
enemies: r.enemies.trim(),
|
||||
loot: r.loot.trim()
|
||||
}));
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-import',
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe, FileDropDirective],
|
||||
@@ -401,14 +414,7 @@ export class CampaignImportComponent implements OnInit {
|
||||
playerNarration: s.playerNarration.trim(),
|
||||
gmNotes: s.gmNotes.trim(),
|
||||
existingId: s.existingId ?? null,
|
||||
rooms: s.rooms
|
||||
.filter(r => r.name.trim())
|
||||
.map(r => ({
|
||||
name: r.name.trim(),
|
||||
description: r.description.trim(),
|
||||
enemies: r.enemies.trim(),
|
||||
loot: r.loot.trim()
|
||||
}))
|
||||
rooms: cleanRooms(s.rooms)
|
||||
}))
|
||||
}))
|
||||
})),
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<section class="play-block" [class.play-block--live]="target.kind === 'resume'" [attr.aria-label]="'playAccess.block.title' | translate">
|
||||
<div class="play-head">
|
||||
<lucide-icon [img]="Play" [size]="16" class="play-head-icon"></lucide-icon>
|
||||
<h2 class="play-title">{{ 'playAccess.block.title' | translate }}</h2>
|
||||
</div>
|
||||
|
||||
@if (target.kind === 'resume') {
|
||||
<ul class="play-rows">
|
||||
@for (r of target.sessions; track r.session.id) {
|
||||
<li class="play-row">
|
||||
<span class="live-dot" aria-hidden="true"></span>
|
||||
<div class="play-row-texts">
|
||||
<span class="play-row-label">{{ 'playAccess.block.running' | translate }}</span>
|
||||
<span class="play-row-sub">{{ r.session.name }} · {{ r.playthrough.name }}</span>
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" (click)="resume(r.session)">
|
||||
<lucide-icon [img]="Play" [size]="15"></lucide-icon>
|
||||
{{ 'playAccess.block.resume' | translate }}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
} @else if (target.kind === 'start') {
|
||||
<div class="play-row">
|
||||
<div class="play-row-texts">
|
||||
@if (target.playthroughs.length > 1) {
|
||||
<label class="play-row-label" for="play-block-playthrough">{{ 'playAccess.block.playthroughLabel' | translate }}</label>
|
||||
<select id="play-block-playthrough" class="play-select" [(ngModel)]="selectedPlaythroughId">
|
||||
@for (p of target.playthroughs; track p.id) {
|
||||
<option [value]="p.id">{{ p.name }}</option>
|
||||
}
|
||||
</select>
|
||||
} @else {
|
||||
<span class="play-row-label">{{ 'playAccess.block.nextSession' | translate }}</span>
|
||||
<span class="play-row-sub">{{ target.playthroughs[0].name }}</span>
|
||||
}
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" [disabled]="starting" (click)="start()">
|
||||
<lucide-icon [img]="Play" [size]="15"></lucide-icon>
|
||||
{{ (starting ? 'playAccess.block.starting' : 'playAccess.block.start') | translate }}
|
||||
</button>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="play-row">
|
||||
<div class="play-row-texts">
|
||||
<span class="play-row-sub">{{ 'playAccess.block.noPlaythrough' | translate }}</span>
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" [disabled]="creatingPlaythrough" (click)="createPlaythrough.emit()">
|
||||
<lucide-icon [img]="Plus" [size]="15"></lucide-icon>
|
||||
{{ 'playAccess.block.createPlaythrough' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
:host { display: block; }
|
||||
|
||||
.play-block {
|
||||
margin: 0 0 1.25rem;
|
||||
padding: 0.8rem 0.9rem;
|
||||
background: #0d1117;
|
||||
border: 1px solid #2d2a5a;
|
||||
border-radius: 10px;
|
||||
|
||||
&--live { border-color: rgba(16, 185, 129, 0.55); background: rgba(16, 185, 129, 0.05); }
|
||||
}
|
||||
|
||||
.play-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
margin-bottom: 0.55rem;
|
||||
}
|
||||
|
||||
.play-head-icon { color: #a5a0ff; }
|
||||
.play-block--live .play-head-icon { color: #34d399; }
|
||||
|
||||
.play-title {
|
||||
margin: 0;
|
||||
font-size: 0.92rem;
|
||||
font-weight: 600;
|
||||
color: #e5e7eb;
|
||||
}
|
||||
|
||||
.play-rows {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.play-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.play-row-texts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
flex: 1 1 12rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.play-row-label {
|
||||
font-size: 0.75rem;
|
||||
color: #9ca3af;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.play-row-sub {
|
||||
font-size: 0.9rem;
|
||||
color: #e5e7eb;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.play-select {
|
||||
width: 100%;
|
||||
max-width: 22rem;
|
||||
min-height: 44px;
|
||||
padding: 0.45rem 0.6rem;
|
||||
background: #111827;
|
||||
color: #e5e7eb;
|
||||
border: 1px solid #374151;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.play-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.45rem;
|
||||
min-height: 44px;
|
||||
padding: 0.55rem 1.1rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.play-block--live .play-btn {
|
||||
background: #059669;
|
||||
&:hover:not(:disabled) { background: #047857; }
|
||||
}
|
||||
|
||||
.live-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #10b981;
|
||||
animation: live-pulse 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes live-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.6); }
|
||||
70% { box-shadow: 0 0 0 7px rgba(16, 185, 129, 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.live-dot { animation: none; }
|
||||
}
|
||||
|
||||
// Téléphone : bouton pleine largeur sous le texte.
|
||||
@media (max-width: 480px) {
|
||||
.play-btn { flex: 1 1 100%; }
|
||||
.play-select { max-width: none; }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user