Compare commits
21
Commits
v1.0.3
...
v1.5.0-beta
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cccf2b85db | ||
|
|
6ae9238fee | ||
|
|
0ef1380265 | ||
|
|
9a7e93b162 | ||
|
|
106754fd77 | ||
|
|
0c0581e894 | ||
|
|
dae0508c93 | ||
|
|
cbd59a5bd9 | ||
|
|
d759bc8131 | ||
|
|
ac7648f9fe | ||
|
|
d9a90f8412 | ||
|
|
2e9632de49 | ||
|
|
fbb1956e17 | ||
|
|
8c6b642975 | ||
|
|
d926545e3d | ||
|
|
b323c681f8 | ||
|
|
e7063b31e3 | ||
|
|
ab658f27b0 | ||
|
|
c2947cfef8 | ||
|
|
67ac4cc68f | ||
|
|
c2f162d823 |
+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.3",
|
||||
version="1.5.0-beta",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>1.0.3</version>
|
||||
<version>1.5.0-beta</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class CampaignContentSearchService {
|
||||
private final CampaignContentSearchRepository repository;
|
||||
|
||||
public CampaignContentSearchService(CampaignContentSearchRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public List<CampaignContentHit> search(String query) {
|
||||
String value = query == null ? "" : query.strip();
|
||||
return value.length() < 2 ? List.of() : repository.searchByName(value);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
||||
import com.loremind.application.playcontext.PlaythroughService;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
@@ -108,6 +109,23 @@ public class CampaignService {
|
||||
campaignRepository.save(campaign);
|
||||
}
|
||||
|
||||
/** Fiche « Publication » de la campagne (vide si jamais renseignée). */
|
||||
public CampaignPublication getPublication(String id) {
|
||||
Campaign campaign = campaignRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||
return campaign.getPublication() != null ? campaign.getPublication() : CampaignPublication.empty();
|
||||
}
|
||||
|
||||
/** Remplace la fiche « Publication » (nettoyée : blancs → vide, longueurs bornées). */
|
||||
public CampaignPublication updatePublication(String id, CampaignPublication publication) {
|
||||
Campaign campaign = campaignRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||
CampaignPublication clean = publication != null ? publication.normalized() : CampaignPublication.empty();
|
||||
campaign.setPublication(clean.hasContent() ? clean : null);
|
||||
campaignRepository.save(campaign);
|
||||
return clean;
|
||||
}
|
||||
|
||||
private String normalizeId(String id) {
|
||||
return (id == null || id.isBlank()) ? null : id;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Squelette d'aventure produit par une méthode guidée (Mentor d'écriture, phase M3 —
|
||||
* voir docs/conception-mentor-ecriture.md) : un chapitre et ses scènes, rédigés par le MJ
|
||||
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
||||
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
||||
*
|
||||
* <p>Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre
|
||||
* est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite).
|
||||
* Exactement l'un des deux.</p>
|
||||
*
|
||||
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
|
||||
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
||||
* @param chapter le chapitre (nom obligatoire)
|
||||
* @param scenes les scènes, dans l'ordre (au moins une avec un nom)
|
||||
* @param linkSequentially relier chaque scène à la suivante par une sortie
|
||||
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
|
||||
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
|
||||
* une enquête en nœuds relie ses pistes en réseau, pas en chaîne
|
||||
* @param clock horloge à créer dans chaque partie de la campagne (plan du méchant), ou {@code null}
|
||||
*/
|
||||
public record GuidedSkeleton(
|
||||
String arcId,
|
||||
String newArcName,
|
||||
ChapterSpec chapter,
|
||||
List<SceneSpec> scenes,
|
||||
boolean linkSequentially,
|
||||
String linkLabel,
|
||||
List<LinkSpec> links,
|
||||
ClockSpec clock
|
||||
) {
|
||||
|
||||
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
|
||||
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||
boolean linkSequentially, String linkLabel) {
|
||||
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null);
|
||||
}
|
||||
|
||||
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
|
||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes,
|
||||
String gmNotes) {
|
||||
public ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||
this(name, description, playerObjectives, narrativeStakes, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lien d'une scène vers une autre, par position dans {@code scenes}.
|
||||
*
|
||||
* @param from index de la scène de départ
|
||||
* @param to index de la scène d'arrivée
|
||||
* @param label libellé du lien (langue du MJ)
|
||||
* @param kind nature du lien (sortie, piste, indice) ; {@code null} = sortie
|
||||
*/
|
||||
public record LinkSpec(int from, int to, String label, LinkType kind) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Horloge de progression à créer dans chaque partie (Playthrough) de la campagne.
|
||||
*
|
||||
* @param name nom de l'horloge
|
||||
* @param description ce qui arrive quand elle est pleine
|
||||
* @param segments nombre de segments (une étape du plan = un segment)
|
||||
*/
|
||||
public record ClockSpec(String name, String description, int segments) {
|
||||
}
|
||||
|
||||
public record SceneSpec(
|
||||
String name, String description, SceneType type, String location,
|
||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ce qui a été créé, pour que le front ouvre directement le chapitre.
|
||||
*
|
||||
* @param clocks nombre d'horloges créées (une par partie de la campagne)
|
||||
*/
|
||||
public record Result(String arcId, String chapterId, List<String> sceneIds, int clocks) {
|
||||
public Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||
this(arcId, chapterId, sceneIds, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.application.playcontext.ClockService;
|
||||
import com.loremind.domain.playcontext.ClockTrigger;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Persiste d'un bloc le squelette d'une méthode guidée (Mentor d'écriture, phase M3) :
|
||||
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
||||
*
|
||||
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
|
||||
* arc et le nouveau chapitre se placent à la suite). Transactionnel : tout ou rien.</p>
|
||||
*/
|
||||
@Service
|
||||
public class GuidedSkeletonService {
|
||||
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final ArcService arcService;
|
||||
private final ChapterService chapterService;
|
||||
private final SceneService sceneService;
|
||||
private final PlaythroughRepository playthroughRepository;
|
||||
private final ClockService clockService;
|
||||
|
||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
ArcService arcService,
|
||||
ChapterService chapterService,
|
||||
SceneService sceneService,
|
||||
PlaythroughRepository playthroughRepository,
|
||||
ClockService clockService) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.arcService = arcService;
|
||||
this.chapterService = chapterService;
|
||||
this.sceneService = sceneService;
|
||||
this.playthroughRepository = playthroughRepository;
|
||||
this.clockService = clockService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
||||
* arc d'une autre campagne ou non linéaire)
|
||||
*/
|
||||
@Transactional
|
||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||
validate(skeleton);
|
||||
String arcId = resolveArc(campaignId, skeleton);
|
||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||
|
||||
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
|
||||
List<Scene> scenes = new ArrayList<>();
|
||||
List<Scene> byIndex = new ArrayList<>();
|
||||
int order = 0;
|
||||
for (GuidedSkeleton.SceneSpec spec : skeleton.scenes()) {
|
||||
if (spec == null || isBlank(spec.name())) {
|
||||
byIndex.add(null);
|
||||
continue;
|
||||
}
|
||||
Scene created = sceneService.createScene(Scene.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
|
||||
.location(blankToNull(spec.location()))
|
||||
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
||||
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
||||
.enemies(blankToNull(spec.enemies()))
|
||||
.chapterId(chapter.getId())
|
||||
.order(order++)
|
||||
.build());
|
||||
scenes.add(created);
|
||||
byIndex.add(created);
|
||||
}
|
||||
|
||||
if (skeleton.linkSequentially()) {
|
||||
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||
}
|
||||
if (skeleton.links() != null && !skeleton.links().isEmpty()) {
|
||||
linkExplicitly(byIndex, skeleton.links());
|
||||
}
|
||||
int clocks = createClocks(campaignId, skeleton.clock());
|
||||
|
||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList(), clocks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liens explicites (réseau d'une enquête) : ajoutés aux sorties existantes. Un lien vers
|
||||
* ou depuis une scène ignorée (sans nom), hors limites ou en boucle sur soi est écarté.
|
||||
*/
|
||||
private void linkExplicitly(List<Scene> byIndex, List<GuidedSkeleton.LinkSpec> links) {
|
||||
java.util.Map<String, Scene> touched = new java.util.LinkedHashMap<>();
|
||||
for (GuidedSkeleton.LinkSpec link : links) {
|
||||
if (link == null || link.from() == link.to()) continue;
|
||||
Scene from = at(byIndex, link.from());
|
||||
Scene to = at(byIndex, link.to());
|
||||
if (from == null || to == null) continue;
|
||||
List<SceneBranch> branches = from.getBranches() == null ? new ArrayList<>() : new ArrayList<>(from.getBranches());
|
||||
String label = isBlank(link.label()) ? to.getName() : link.label().trim();
|
||||
branches.add(new SceneBranch(label, to.getId(), null,
|
||||
Objects.requireNonNullElse(link.kind(), LinkType.EXIT)));
|
||||
from.setBranches(branches);
|
||||
touched.put(from.getId(), from);
|
||||
}
|
||||
touched.values().forEach(sceneRepository::save);
|
||||
}
|
||||
|
||||
private static Scene at(List<Scene> byIndex, int index) {
|
||||
return index >= 0 && index < byIndex.size() ? byIndex.get(index) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Horloge du plan (méthode « Plan du méchant ») : créée dans chaque partie de la campagne,
|
||||
* car une horloge est de l'état de partie. Aucune partie : rien n'est créé (le MJ la
|
||||
* créera quand il lancera une partie).
|
||||
*/
|
||||
private int createClocks(String campaignId, GuidedSkeleton.ClockSpec clock) {
|
||||
if (clock == null || isBlank(clock.name())) return 0;
|
||||
int count = 0;
|
||||
for (Playthrough p : playthroughRepository.findByCampaignId(campaignId)) {
|
||||
clockService.create(p.getId(), clock.name().trim(), blankToNull(clock.description()),
|
||||
clock.segments(), ClockTrigger.NONE, null, null);
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void validate(GuidedSkeleton skeleton) {
|
||||
if (skeleton == null) {
|
||||
throw new IllegalArgumentException("Squelette manquant.");
|
||||
}
|
||||
boolean hasArc = !isBlank(skeleton.arcId());
|
||||
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
||||
if (hasArc == hasNewArc) {
|
||||
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
||||
}
|
||||
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
||||
throw new IllegalArgumentException("Le chapitre doit avoir un nom.");
|
||||
}
|
||||
if (skeleton.scenes() == null || skeleton.scenes().stream().noneMatch(s -> s != null && !isBlank(s.name()))) {
|
||||
throw new IllegalArgumentException("Il faut au moins une scène nommée.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Arc existant (vérifié : même campagne, linéaire) ou nouvel arc linéaire placé à la suite. */
|
||||
private String resolveArc(String campaignId, GuidedSkeleton skeleton) {
|
||||
List<Arc> arcs = arcRepository.findByCampaignId(campaignId);
|
||||
if (!isBlank(skeleton.arcId())) {
|
||||
Arc arc = arcs.stream().filter(a -> skeleton.arcId().equals(a.getId())).findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
|
||||
if (arc.getType() != ArcType.LINEAR) {
|
||||
throw new IllegalArgumentException("Une méthode guidée s'ajoute à un arc linéaire.");
|
||||
}
|
||||
return arc.getId();
|
||||
}
|
||||
// L'arc SYSTEM (« Quêtes libres », ordre 9999) reste en dernier : on ne le compte pas.
|
||||
int nextOrder = arcs.stream().filter(a -> a.getType() != ArcType.SYSTEM)
|
||||
.mapToInt(Arc::getOrder).max().orElse(-1) + 1;
|
||||
return arcService.createArc(Arc.builder()
|
||||
.name(skeleton.newArcName().trim())
|
||||
.campaignId(campaignId)
|
||||
.type(ArcType.LINEAR)
|
||||
.order(nextOrder)
|
||||
.build()).getId();
|
||||
}
|
||||
|
||||
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec) {
|
||||
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
||||
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
||||
return chapterService.createChapter(Chapter.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||
.gmNotes(blankToNull(spec.gmNotes()))
|
||||
.arcId(arcId)
|
||||
.order(nextOrder)
|
||||
.build());
|
||||
}
|
||||
|
||||
/** Chaque scène reçoit une sortie vers la suivante (la dernière n'en a pas). */
|
||||
private void linkInChain(List<Scene> scenes, String label) {
|
||||
for (int i = 0; i < scenes.size() - 1; i++) {
|
||||
Scene scene = scenes.get(i);
|
||||
scene.setBranches(new ArrayList<>(List.of(
|
||||
new SceneBranch(label, scenes.get(i + 1).getId(), null, LinkType.EXIT))));
|
||||
sceneRepository.save(scene);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String blankToNull(String s) {
|
||||
return isBlank(s) ? null : s.trim();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||
import com.loremind.domain.shared.ReorderSupport;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -29,8 +30,17 @@ public class NpcService {
|
||||
String campaignId,
|
||||
List<String> relatedPageIds,
|
||||
String folder,
|
||||
Integer order
|
||||
) {}
|
||||
Integer order,
|
||||
/** Rôle dans l'histoire ; null = inchangé (mise à jour) / non renseigné (création). */
|
||||
NpcStory story
|
||||
) {
|
||||
public NpcData(String name, String portraitImageId, String headerImageId, Map<String, String> values,
|
||||
Map<String, List<String>> imageValues, Map<String, Map<String, String>> keyValueValues,
|
||||
String campaignId, List<String> relatedPageIds, String folder, Integer order) {
|
||||
this(name, portraitImageId, headerImageId, values, imageValues, keyValueValues, campaignId,
|
||||
relatedPageIds, folder, order, null);
|
||||
}
|
||||
}
|
||||
|
||||
public Npc createNpc(NpcData data) {
|
||||
int order = data.order() != null
|
||||
@@ -47,6 +57,7 @@ public class NpcService {
|
||||
.relatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>())
|
||||
.folder(normalizeFolder(data.folder()))
|
||||
.order(order)
|
||||
.story(cleanStory(data.story()))
|
||||
.build();
|
||||
return npcRepository.save(npc);
|
||||
}
|
||||
@@ -70,12 +81,22 @@ public class NpcService {
|
||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||
existing.setRelatedPageIds(data.relatedPageIds() != null ? new ArrayList<>(data.relatedPageIds()) : new ArrayList<>());
|
||||
existing.setFolder(normalizeFolder(data.folder()));
|
||||
if (data.story() != null) {
|
||||
existing.setStory(cleanStory(data.story()));
|
||||
}
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
return npcRepository.save(existing);
|
||||
}
|
||||
|
||||
/** Fiche nettoyée, ou null si elle est vide (rien à stocker). */
|
||||
private static NpcStory cleanStory(NpcStory story) {
|
||||
if (story == null) return null;
|
||||
NpcStory clean = story.normalized();
|
||||
return clean.hasContent() ? clean : null;
|
||||
}
|
||||
|
||||
public void deleteNpc(String id) {
|
||||
npcRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@@ -125,6 +125,8 @@ public class SceneService {
|
||||
case "playerNarration" -> scene.setPlayerNarration(value);
|
||||
case "choicesConsequences" -> scene.setChoicesConsequences(value);
|
||||
case "combatDifficulty" -> scene.setCombatDifficulty(value);
|
||||
case "tactics" -> scene.setTactics(value);
|
||||
case "purpose" -> scene.setPurpose(value);
|
||||
case "enemies" -> scene.setEnemies(value);
|
||||
case "gmSecretNotes" -> scene.setGmSecretNotes(value);
|
||||
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Une remarque de relecture d'éditeur (Mentor d'écriture, phase M2) : un conseil
|
||||
* d'auteur sur la QUALITÉ de l'écriture, pas sur la complétude (ça, c'est le readiness).
|
||||
*
|
||||
* <p>Contrairement à {@link ReadinessGap}, le back ne rédige pas le texte : il
|
||||
* renvoie la règle et ses paramètres, et le front compose observation / pourquoi /
|
||||
* question depuis l'i18n ({@code writingReview.rules.<ruleId>}), en fr comme en en.</p>
|
||||
*
|
||||
* @param entityType type de l'entité concernée (réutilise celui du readiness pour les liens profonds)
|
||||
* @param entityId id de l'entité concernée
|
||||
* @param entityName libellé lisible de l'entité
|
||||
* @param ruleId identifiant stable de la règle (ex. {@code WRITE-002-FAKE-CHOICE})
|
||||
* @param category famille de la remarque (regroupement à l'affichage)
|
||||
* @param params valeurs à injecter dans le texte i18n (ex. {@code count}, {@code phrase})
|
||||
* @param arcId arc parent (navigation), ou {@code null}
|
||||
* @param chapterId chapitre parent (navigation), ou {@code null}
|
||||
*/
|
||||
public record WritingRemark(
|
||||
ReadinessEntityType entityType,
|
||||
String entityId,
|
||||
String entityName,
|
||||
String ruleId,
|
||||
WritingRemarkCategory category,
|
||||
Map<String, String> params,
|
||||
String arcId,
|
||||
String chapterId
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Relecture d'éditeur d'une campagne (Mentor d'écriture, phase M2).
|
||||
*
|
||||
* @param campaignId campagne relue
|
||||
* @param remarks remarques dans l'ordre de l'arbre (campagne, puis arc par arc)
|
||||
*/
|
||||
public record WritingReviewReport(String campaignId, List<WritingRemark> remarks) {
|
||||
}
|
||||
+539
@@ -0,0 +1,539 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Relecture d'éditeur (Mentor d'écriture, phase M2 — voir docs/conception-mentor-ecriture.md) :
|
||||
* conseils d'auteur sur la QUALITÉ de l'écriture (vrais choix, rythme, enjeux, narration),
|
||||
* là où le readiness ({@link CampaignReadinessService}) ne juge que la complétude.
|
||||
*
|
||||
* <p><b>Déterministe, sans IA, sans persistance</b> ; même chargement en une passe que le
|
||||
* readiness (arcs → chapitres → scènes). Purement indicatif : une remarque est un conseil,
|
||||
* jamais un blocage. Le texte est composé côté front à partir de {@code ruleId} + {@code params}.</p>
|
||||
*
|
||||
* <p>L'arc SYSTEM (« Quêtes libres ») est de la plomberie invisible : ses chapitres-conteneurs
|
||||
* ne reçoivent pas de remarque de niveau chapitre, mais leurs scènes sont relues comme les autres.</p>
|
||||
*/
|
||||
@Service
|
||||
public class WritingReviewService {
|
||||
|
||||
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
|
||||
static final int CORRIDOR_MIN_SCENES = 3;
|
||||
/** WRITE-003 : nombre minimal de scènes menant à une révélation (règle des 3 indices). */
|
||||
static final int REVELATION_MIN_INCOMING = 3;
|
||||
/** WRITE-011 / 012 / 014 : un chapitre « qui utilise le graphe » a au moins ce nombre de scènes reliées. */
|
||||
static final int LINKED_MIN_SCENES = 2;
|
||||
/** WRITE-012 : taille minimale d'un chapitre pour juger un passage obligé. */
|
||||
static final int CHOKEPOINT_MIN_SCENES = 4;
|
||||
/** WRITE-013 : nombre minimal de pièces pour juger la forme d'un donjon. */
|
||||
static final int DUNGEON_MIN_ROOMS = 4;
|
||||
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
|
||||
static final int PROACTIVE_MIN_SCENES = 3;
|
||||
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
||||
static final int MONOTONOUS_RUN = 3;
|
||||
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
||||
static final int LONG_NARRATION_CHARS = 1200;
|
||||
/** WRITE-010 : nombre minimal de scènes pour juger la part de scènes non typées. */
|
||||
static final int UNTYPED_MIN_SCENES = 5;
|
||||
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
||||
static final double UNTYPED_RATIO = 0.7;
|
||||
|
||||
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
||||
static final String KIND_COMBAT = "COMBAT";
|
||||
|
||||
/**
|
||||
* WRITE-007 : la narration décide à la place des personnages (action ou émotion imposée).
|
||||
* Volontairement restreint aux tournures sans ambiguïté, pour éviter les faux positifs.
|
||||
*/
|
||||
private static final Pattern NARRATION_DECIDES = Pattern.compile(
|
||||
"\\b(vous (?:décidez|choisissez|ressentez|avez (?:très |si )?peur"
|
||||
+ "|êtes (?:terrifié|effrayé|terrorisé|paniqué|soulagé|ému)e?s?"
|
||||
+ "|entrez|vous précipitez|dégainez|attaquez|fuyez)"
|
||||
+ "|you (?:decide|choose|feel (?:afraid|scared|uneasy|relieved|guilty)"
|
||||
+ "|are (?:afraid|scared|terrified|relieved|panicking)"
|
||||
+ "|enter|rush|draw your|attack|flee))\\b",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.UNICODE_CHARACTER_CLASS);
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final QuestRepository questRepository;
|
||||
private final NpcRepository npcRepository;
|
||||
|
||||
public WritingReviewService(CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
QuestRepository questRepository,
|
||||
NpcRepository npcRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.questRepository = questRepository;
|
||||
this.npcRepository = npcRepository;
|
||||
}
|
||||
|
||||
/** Relit toute la campagne et renvoie les remarques dans l'ordre de l'arbre. */
|
||||
public WritingReviewReport review(String campaignId) {
|
||||
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
||||
List<WritingRemark> treeRemarks = new ArrayList<>();
|
||||
|
||||
Set<String> arcsWithQuests = questRepository.findByCampaignId(campaignId).stream()
|
||||
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||
|
||||
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||
|
||||
int totalScenes = 0;
|
||||
int genericScenes = 0;
|
||||
for (Arc arc : arcs) {
|
||||
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
||||
|
||||
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
|
||||
if (visibleArc && countLines(arc.getHooks()) == 1) {
|
||||
treeRemarks.add(arcRemark(arc, "WRITE-017-SINGLE-HOOK", WritingRemarkCategory.AGENCY, Map.of()));
|
||||
}
|
||||
|
||||
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
||||
if (visibleArc && isBlank(arc.getStakes())
|
||||
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
||||
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||
}
|
||||
|
||||
List<Scene> lastChapterScenes = List.of();
|
||||
for (Chapter chapter : chapters) {
|
||||
List<Scene> scenes = new ArrayList<>(sceneRepository.findByChapterId(chapter.getId()));
|
||||
scenes.sort(Comparator.comparingInt(Scene::getOrder));
|
||||
totalScenes += scenes.size();
|
||||
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
||||
|
||||
if (visibleArc) {
|
||||
reviewChapter(arc, chapter, scenes, treeRemarks);
|
||||
}
|
||||
for (Scene scene : scenes) {
|
||||
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||
}
|
||||
reviewGraph(arc, chapter, scenes, treeRemarks);
|
||||
if (!scenes.isEmpty()) {
|
||||
lastChapterScenes = scenes;
|
||||
}
|
||||
}
|
||||
|
||||
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
||||
checkSingleEnding(arc, lastChapterScenes, treeRemarks);
|
||||
}
|
||||
}
|
||||
|
||||
// WRITE-010 — trop de scènes non typées pour juger le rythme.
|
||||
if (totalScenes >= UNTYPED_MIN_SCENES && (double) genericScenes / totalScenes > UNTYPED_RATIO) {
|
||||
String campaignName = campaignRepository.findById(campaignId).map(Campaign::getName).orElse(null);
|
||||
int pct = (int) Math.round(100.0 * genericScenes / totalScenes);
|
||||
campaignRemarks.add(new WritingRemark(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
||||
"WRITE-010-UNTYPED-SCENES", WritingRemarkCategory.PACING,
|
||||
Map.of("percent", String.valueOf(pct), "count", String.valueOf(genericScenes)),
|
||||
null, null));
|
||||
}
|
||||
|
||||
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
|
||||
remarks.addAll(treeRemarks);
|
||||
remarks.addAll(reviewNpcs(campaignId));
|
||||
return new WritingReviewReport(campaignId, remarks);
|
||||
}
|
||||
|
||||
// --- Niveau chapitre ---------------------------------------------------------------
|
||||
|
||||
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
||||
|
||||
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
||||
boolean anyBranch = scenes.stream().anyMatch(WritingReviewService::hasBranches);
|
||||
boolean anyChoice = scenes.stream().anyMatch(s -> !isBlank(s.getChoicesConsequences()));
|
||||
if (scenes.size() >= CORRIDOR_MIN_SCENES && !anyBranch && !anyChoice) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-001-CORRIDOR", WritingRemarkCategory.AGENCY,
|
||||
Map.of("count", String.valueOf(scenes.size()))));
|
||||
}
|
||||
|
||||
// WRITE-004 — rythme monotone : N scènes d'affilée du même genre.
|
||||
MonotonousRun run = findMonotonousRun(scenes);
|
||||
if (run != null) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-004-MONOTONOUS-PACING", WritingRemarkCategory.PACING,
|
||||
Map.of("count", String.valueOf(run.length()), "kind", run.kind())));
|
||||
}
|
||||
|
||||
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
||||
if (isBlank(chapter.getNarrativeStakes())) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||
}
|
||||
|
||||
// WRITE-014 — enquête sans relance : des révélations, mais aucun événement que le MJ
|
||||
// peut déclencher si les joueurs tournent en rond.
|
||||
boolean investigation = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.REVELATION);
|
||||
boolean proactive = scenes.stream().anyMatch(s -> typeOf(s) == SceneType.EVENT);
|
||||
if (investigation && !proactive && scenes.size() >= PROACTIVE_MIN_SCENES && usesLinks(scenes)) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-014-NO-PROACTIVE", WritingRemarkCategory.PACING, Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
private record MonotonousRun(String kind, int length) {}
|
||||
|
||||
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
||||
private static MonotonousRun findMonotonousRun(List<Scene> scenes) {
|
||||
String currentKind = null;
|
||||
int length = 0;
|
||||
MonotonousRun found = null;
|
||||
for (Scene scene : scenes) {
|
||||
String kind = pacingKind(scene);
|
||||
if (kind != null && kind.equals(currentKind)) {
|
||||
length++;
|
||||
} else {
|
||||
if (found != null) return found;
|
||||
currentKind = kind;
|
||||
length = kind == null ? 0 : 1;
|
||||
}
|
||||
if (length >= MONOTONOUS_RUN) {
|
||||
found = new MonotonousRun(currentKind, length);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Genre d'une scène pour le rythme : COMBAT, sinon son type s'il est renseigné, sinon null. */
|
||||
private static String pacingKind(Scene scene) {
|
||||
if (isCombat(scene)) return KIND_COMBAT;
|
||||
SceneType type = typeOf(scene);
|
||||
return type == SceneType.GENERIC ? null : type.name();
|
||||
}
|
||||
|
||||
// --- Niveau scène -------------------------------------------------------------------
|
||||
|
||||
private void reviewScene(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
checkFakeChoice(arc, chapter, scene, chapterScenes, out);
|
||||
checkSingleClue(arc, chapter, scene, chapterScenes, out);
|
||||
checkNarration(arc, chapter, scene, out);
|
||||
checkCombatPurpose(arc, chapter, scene, out);
|
||||
checkLinearDungeon(arc, chapter, scene, out);
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE-013 — donjon en couloir : des pièces reliées entre elles, mais sans aucune boucle
|
||||
* (graphe des liens = arbre). Les joueurs ne choisissent pas leur route et ne peuvent ni
|
||||
* contourner un obstacle ni revenir par un autre chemin. Muet si les pièces ne sont pas reliées.
|
||||
*/
|
||||
private void checkLinearDungeon(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||
List<Room> rooms = scene.getRooms();
|
||||
if (rooms == null || rooms.size() < DUNGEON_MIN_ROOMS) return;
|
||||
Set<String> ids = rooms.stream().map(Room::getId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||
// Arêtes non orientées distinctes (A→B et B→A = un seul passage).
|
||||
Set<String> edges = new HashSet<>();
|
||||
for (Room r : rooms) {
|
||||
if (r.getBranches() == null) continue;
|
||||
for (RoomBranch b : r.getBranches()) {
|
||||
String to = b.targetRoomId();
|
||||
if (isBlank(r.getId()) || !ids.contains(to) || r.getId().equals(to)) continue;
|
||||
edges.add(r.getId().compareTo(to) < 0 ? r.getId() + "|" + to : to + "|" + r.getId());
|
||||
}
|
||||
}
|
||||
if (edges.isEmpty()) return;
|
||||
int components = countComponents(ids, edges);
|
||||
int loops = edges.size() - ids.size() + components;
|
||||
if (loops == 0 && components == 1) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-013-LINEAR-DUNGEON", WritingRemarkCategory.AGENCY,
|
||||
Map.of("rooms", String.valueOf(ids.size()))));
|
||||
}
|
||||
}
|
||||
|
||||
private static int countComponents(Set<String> nodes, Set<String> edges) {
|
||||
Map<String, Set<String>> adj = new HashMap<>();
|
||||
for (String n : nodes) adj.put(n, new HashSet<>());
|
||||
for (String e : edges) {
|
||||
String[] ab = e.split("\\|", 2);
|
||||
adj.get(ab[0]).add(ab[1]);
|
||||
adj.get(ab[1]).add(ab[0]);
|
||||
}
|
||||
Set<String> seen = new HashSet<>();
|
||||
int components = 0;
|
||||
for (String start : nodes) {
|
||||
if (!seen.add(start)) continue;
|
||||
components++;
|
||||
Deque<String> stack = new ArrayDeque<>(List.of(start));
|
||||
while (!stack.isEmpty()) {
|
||||
for (String next : adj.get(stack.pop())) {
|
||||
if (seen.add(next)) stack.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
return components;
|
||||
}
|
||||
|
||||
// --- Graphe du chapitre -------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Règles sur la forme du graphe des scènes d'un chapitre, seulement s'il utilise des liens
|
||||
* (sans aucun lien, c'est WRITE-001 qui parle) : WRITE-011 scène isolée, WRITE-012 passage
|
||||
* obligé. Les liens sont internes au chapitre (règle de SceneService).
|
||||
*/
|
||||
private void reviewGraph(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||
if (!usesLinks(scenes)) return;
|
||||
Map<String, Set<String>> next = successors(scenes);
|
||||
Set<String> withIncoming = next.values().stream().flatMap(Set::stream).collect(Collectors.toSet());
|
||||
|
||||
// WRITE-011 — scène isolée : ni lien entrant ni lien sortant (hors scène d'ouverture).
|
||||
for (int i = 1; i < scenes.size(); i++) {
|
||||
Scene s = scenes.get(i);
|
||||
if (next.get(s.getId()).isEmpty() && !withIncoming.contains(s.getId())) {
|
||||
out.add(sceneRemark(arc, chapter, s, "WRITE-011-ISOLATED-SCENE", WritingRemarkCategory.PACING, Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
checkChokepoint(arc, chapter, scenes, next, out);
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE-012 — passage obligé : depuis la scène d'ouverture, tous les chemins vers les
|
||||
* fins du chapitre traversent une même scène. Si les joueurs y échouent ou passent à côté,
|
||||
* tout s'arrête. Une seule remarque par chapitre (le premier passage obligé).
|
||||
*/
|
||||
private void checkChokepoint(Arc arc, Chapter chapter, List<Scene> scenes, Map<String, Set<String>> next,
|
||||
List<WritingRemark> out) {
|
||||
if (scenes.size() < CHOKEPOINT_MIN_SCENES) return;
|
||||
String entry = scenes.get(0).getId();
|
||||
if (next.get(entry).isEmpty()) return;
|
||||
Set<String> reachable = reach(entry, next, null);
|
||||
Set<String> ends = reachable.stream().filter(id -> next.get(id).isEmpty()).collect(Collectors.toSet());
|
||||
if (ends.isEmpty()) return; // Boucle sans fin : rien à juger.
|
||||
|
||||
List<Scene> chokepoints = new ArrayList<>();
|
||||
for (Scene s : scenes) {
|
||||
String id = s.getId();
|
||||
if (id.equals(entry) || ends.contains(id) || !reachable.contains(id)) continue;
|
||||
Set<String> without = reach(entry, next, id);
|
||||
if (ends.stream().noneMatch(without::contains)) chokepoints.add(s);
|
||||
}
|
||||
if (chokepoints.isEmpty()) return;
|
||||
out.add(sceneRemark(arc, chapter, chokepoints.get(0), "WRITE-012-CHOKEPOINT", WritingRemarkCategory.AGENCY,
|
||||
Map.of("count", String.valueOf(chokepoints.size()))));
|
||||
}
|
||||
|
||||
/** Successeurs de chaque scène du chapitre (liens vers des scènes du même chapitre seulement). */
|
||||
private static Map<String, Set<String>> successors(List<Scene> scenes) {
|
||||
Set<String> ids = scenes.stream().map(Scene::getId).collect(Collectors.toSet());
|
||||
Map<String, Set<String>> next = new HashMap<>();
|
||||
for (Scene s : scenes) {
|
||||
Set<String> targets = new LinkedHashSet<>();
|
||||
if (s.getBranches() != null) {
|
||||
for (SceneBranch b : s.getBranches()) {
|
||||
String to = b.targetSceneId();
|
||||
if (ids.contains(to) && !to.equals(s.getId())) targets.add(to);
|
||||
}
|
||||
}
|
||||
next.put(s.getId(), targets);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Scènes atteignables depuis {@code from} en suivant les liens, sans passer par {@code removed}. */
|
||||
private static Set<String> reach(String from, Map<String, Set<String>> next, String removed) {
|
||||
Set<String> seen = new HashSet<>();
|
||||
Deque<String> stack = new ArrayDeque<>(List.of(from));
|
||||
seen.add(from);
|
||||
while (!stack.isEmpty()) {
|
||||
for (String n : next.getOrDefault(stack.pop(), Set.of())) {
|
||||
if (!n.equals(removed) && seen.add(n)) stack.push(n);
|
||||
}
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
/** Le chapitre utilise le graphe : au moins {@link #LINKED_MIN_SCENES} scènes portent des liens. */
|
||||
private static boolean usesLinks(List<Scene> scenes) {
|
||||
return scenes.stream().filter(WritingReviewService::hasBranches).count() >= LINKED_MIN_SCENES;
|
||||
}
|
||||
|
||||
/** WRITE-002 — faux carrefour : plusieurs sorties qui mènent toutes au même endroit. */
|
||||
private void checkFakeChoice(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
List<SceneBranch> branches = scene.getBranches();
|
||||
if (branches == null || branches.size() < 2) return;
|
||||
Set<String> targets = branches.stream().map(SceneBranch::targetSceneId).collect(Collectors.toSet());
|
||||
if (targets.size() != 1) return;
|
||||
String target = targets.iterator().next();
|
||||
if (isBlank(target)) return; // Branche cassée : c'est l'affaire du readiness (SCENE-010).
|
||||
String targetName = chapterScenes.stream()
|
||||
.filter(s -> target.equals(s.getId())).map(Scene::getName)
|
||||
.filter(n -> !isBlank(n)).findFirst().orElse("?");
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-002-FAKE-CHOICE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("count", String.valueOf(branches.size()), "target", targetName)));
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE-003 — révélation à chemin unique (règle des 3 indices). Seulement dans un
|
||||
* chapitre qui utilise des liens : sans aucun lien, c'est WRITE-001 qui parle.
|
||||
*/
|
||||
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||
List<Scene> sources = chapterScenes.stream()
|
||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
|
||||
.toList();
|
||||
if (sources.size() < REVELATION_MIN_INCOMING) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("incoming", String.valueOf(sources.size()))));
|
||||
return;
|
||||
}
|
||||
// WRITE-015 — assez de chemins, mais tous du même genre (que des interrogatoires…) :
|
||||
// un groupe qui n'aime pas ce genre de scène passe à côté de tous les indices.
|
||||
Set<SceneType> kinds = sources.stream().map(WritingReviewService::typeOf).collect(Collectors.toSet());
|
||||
if (kinds.size() == 1 && !kinds.contains(SceneType.GENERIC)) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-015-SAME-SOURCE-CLUES", WritingRemarkCategory.AGENCY,
|
||||
Map.of("kind", kinds.iterator().next().name(), "count", String.valueOf(sources.size()))));
|
||||
}
|
||||
}
|
||||
|
||||
/** WRITE-006 — narration trop longue ; WRITE-007 — narration qui décide à la place des PJ. */
|
||||
private void checkNarration(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||
String narration = scene.getPlayerNarration();
|
||||
if (isBlank(narration)) return;
|
||||
int length = narration.strip().length();
|
||||
if (length > LONG_NARRATION_CHARS) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-006-LONG-NARRATION", WritingRemarkCategory.NARRATION,
|
||||
Map.of("chars", String.valueOf(length))));
|
||||
}
|
||||
Matcher m = NARRATION_DECIDES.matcher(narration);
|
||||
if (m.find()) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-007-NARRATION-DECIDES", WritingRemarkCategory.NARRATION,
|
||||
Map.of("phrase", m.group(1))));
|
||||
}
|
||||
}
|
||||
|
||||
/** WRITE-008 — combat sans but : ni choix décrits, ni notes sur les motivations des ennemis. */
|
||||
private void checkCombatPurpose(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||
if (isCombat(scene) && isBlank(scene.getChoicesConsequences()) && isBlank(scene.getGmSecretNotes())
|
||||
&& isBlank(scene.getTactics())) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-008-COMBAT-NO-PURPOSE", WritingRemarkCategory.STAKES,
|
||||
Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Niveau arc -----------------------------------------------------------------------
|
||||
|
||||
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
||||
private void checkSingleEnding(Arc arc, List<Scene> lastChapterScenes, List<WritingRemark> out) {
|
||||
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
||||
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
||||
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
||||
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
||||
Map.of("arc", labelOr(arc.getName(), "Arc")), arc.getId(), finale.getChapterId()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- PNJ ----------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* WRITE-016 — opposant ou allié sans motivation : un PNJ qui pèse sur l'intrigue doit
|
||||
* vouloir quelque chose, sinon le MJ ne sait pas comment le faire réagir. Les figurants
|
||||
* et les PNJ sans rôle précisé ne sont pas jugés (pas de bruit sur les seconds rôles).
|
||||
*/
|
||||
private List<WritingRemark> reviewNpcs(String campaignId) {
|
||||
List<WritingRemark> out = new ArrayList<>();
|
||||
for (Npc npc : npcRepository.findByCampaignId(campaignId)) {
|
||||
NpcStory story = npc.getStory();
|
||||
if (story != null && story.drivesThePlot() && story.normalized().motivation() == null) {
|
||||
out.add(new WritingRemark(ReadinessEntityType.NPC, npc.getId(), labelOr(npc.getName(), "PNJ"),
|
||||
"WRITE-016-NPC-NO-MOTIVATION", WritingRemarkCategory.STAKES,
|
||||
Map.of("role", story.normalized().role()), null, null));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- Helpers ----------------------------------------------------------------------------
|
||||
|
||||
/** Nombre de lignes non vides (une accroche par ligne, puces « - » comprises). */
|
||||
private static int countLines(String text) {
|
||||
if (isBlank(text)) return 0;
|
||||
return (int) text.lines().filter(l -> !l.isBlank()).count();
|
||||
}
|
||||
|
||||
private static boolean isCombat(Scene scene) {
|
||||
return typeOf(scene) == SceneType.ENCOUNTER
|
||||
|| !isBlank(scene.getCombatDifficulty())
|
||||
|| !isBlank(scene.getEnemies())
|
||||
|| (scene.getEnemyIds() != null && scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id)));
|
||||
}
|
||||
|
||||
private static boolean hasBranches(Scene scene) {
|
||||
return scene.getBranches() != null && !scene.getBranches().isEmpty();
|
||||
}
|
||||
|
||||
private static SceneType typeOf(Scene scene) {
|
||||
return Objects.requireNonNullElse(scene.getType(), SceneType.GENERIC);
|
||||
}
|
||||
|
||||
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
||||
WritingRemarkCategory category, Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
||||
ruleId, category, params, arc.getId(), chapter.getId());
|
||||
}
|
||||
|
||||
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
||||
WritingRemarkCategory category, Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
||||
ruleId, category, params, arc.getId(), chapter.getId());
|
||||
}
|
||||
|
||||
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
||||
Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
||||
ruleId, category, params, arc.getId(), null);
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String labelOr(String value, String fallback) {
|
||||
return isBlank(value) ? fallback : value;
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,11 @@ public class SessionService {
|
||||
return sessionRepository.findActive();
|
||||
}
|
||||
|
||||
/** Toutes les sessions en cours, la plus récente d'abord (raccourci « Séance en cours »). */
|
||||
public List<Session> getAllActive() {
|
||||
return sessionRepository.findAllActive();
|
||||
}
|
||||
|
||||
public Optional<Session> getActiveByPlaythrough(String playthroughId) {
|
||||
return sessionRepository.findActiveByPlaythroughId(playthroughId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Verdict « une tablette peut-elle joindre ce PC ? », calculé à partir des faits lus sur
|
||||
* le système. Logique pure (testable sans Windows).
|
||||
*
|
||||
* @param supported vérification possible (Windows)
|
||||
* @param ready rien ne bloque côté PC
|
||||
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
|
||||
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
|
||||
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
|
||||
* @param thirdPartyFirewalls pare-feu tiers présents : leurs réglages ne sont pas lisibles, donc {@code ready}
|
||||
* ne peut pas être garanti — le front avertit l'utilisateur de les régler lui-même
|
||||
* @param program exécutable concerné
|
||||
* @param platform {@code windows} ou {@code linux}
|
||||
* @param linuxFirewall Linux : pare-feu actif ({@code ufw}, {@code firewalld}, {@code none})
|
||||
* @param portOpen Linux : port autorisé ({@code null} = invérifiable sans droits administrateur)
|
||||
* @param fixCommand Linux : commande à lancer pour ouvrir le port, ou {@code null}
|
||||
*/
|
||||
public record NetworkReadiness(
|
||||
boolean supported,
|
||||
boolean ready,
|
||||
List<String> publicNetworks,
|
||||
boolean firewallAllowed,
|
||||
boolean firewallBlocked,
|
||||
List<String> thirdPartyFirewalls,
|
||||
String program,
|
||||
String platform,
|
||||
String linuxFirewall,
|
||||
Boolean portOpen,
|
||||
String fixCommand
|
||||
) {
|
||||
|
||||
static final String PUBLIC = "Public";
|
||||
static final String PRIVATE = "Private";
|
||||
|
||||
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
|
||||
if (snapshot == null || !snapshot.supported()) {
|
||||
return new NetworkReadiness(false, false, List.of(), false, false, List.of(), null, null, null, null, null);
|
||||
}
|
||||
if (NetworkSnapshot.LINUX.equals(snapshot.platform())) {
|
||||
return evaluateLinux(snapshot);
|
||||
}
|
||||
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
|
||||
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
|
||||
boolean blockedPrivate = covers(rules, "Block", PRIVATE);
|
||||
boolean publicOpen = covers(rules, "Allow", PUBLIC) && !covers(rules, "Block", PUBLIC);
|
||||
|
||||
List<String> publicNetworks = (snapshot.networks() == null ? List.<NetworkSnapshot.Network>of() : snapshot.networks())
|
||||
.stream()
|
||||
.filter(n -> PUBLIC.equalsIgnoreCase(n.category()))
|
||||
.map(n -> n.name() != null && !n.name().isBlank() ? n.name() : n.alias())
|
||||
.toList();
|
||||
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
|
||||
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
|
||||
|
||||
// « ready » ne porte que sur ce qui est lisible (Windows) ; un pare-feu tiers est signalé à part.
|
||||
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
|
||||
List<String> thirdParty = snapshot.thirdPartyFirewalls() == null ? List.of() : snapshot.thirdPartyFirewalls();
|
||||
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, thirdParty,
|
||||
snapshot.program(), NetworkSnapshot.WINDOWS, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Linux : prêt si aucun pare-feu (ufw, firewalld) n'est actif, ou si le port est ouvert.
|
||||
* Port invérifiable (ufw sans droits root) : pas prêt, mais pas en erreur — le front
|
||||
* affiche la commande « au cas où ».
|
||||
*/
|
||||
private static NetworkReadiness evaluateLinux(NetworkSnapshot s) {
|
||||
String fw = s.linuxFirewall() == null ? "none" : s.linuxFirewall();
|
||||
boolean ready = "none".equals(fw) || Boolean.TRUE.equals(s.portOpen());
|
||||
return new NetworkReadiness(true, ready, List.of(), false, false, List.of(), null,
|
||||
NetworkSnapshot.LINUX, fw, s.portOpen(), ready ? null : linuxCommand(fw, s.port()));
|
||||
}
|
||||
|
||||
static String linuxCommand(String firewall, int port) {
|
||||
return switch (firewall) {
|
||||
case "ufw" -> "sudo ufw allow " + port + "/tcp";
|
||||
case "firewalld" -> "sudo firewall-cmd --permanent --add-port=" + port + "/tcp && sudo firewall-cmd --reload";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
|
||||
private static boolean covers(List<NetworkSnapshot.FirewallRule> rules, String action, String profile) {
|
||||
return rules.stream()
|
||||
.filter(r -> action.equalsIgnoreCase(r.action()) && "True".equalsIgnoreCase(r.enabled()))
|
||||
.anyMatch(r -> profiles(r.profile()).stream().anyMatch(p -> p.equals("any") || p.equals(profile.toLowerCase(Locale.ROOT))));
|
||||
}
|
||||
|
||||
private static List<String> profiles(String raw) {
|
||||
if (raw == null) return List.of();
|
||||
return Arrays.stream(raw.split(","))
|
||||
.map(s -> s.trim().toLowerCase(Locale.ROOT))
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Vue publique d'un appareil appairé (jamais l'empreinte du jeton). */
|
||||
public record PairedDevice(String id, String name, String userAgent, Instant createdAt, Instant lastSeenAt) {
|
||||
|
||||
static PairedDevice of(RemoteDevice d) {
|
||||
return new PairedDevice(d.getId(), d.getName(), d.getUserAgent(), d.getCreatedAt(), d.getLastSeenAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Code d'appairage à 6 chiffres affiché sur le PC (usage unique). */
|
||||
public record PairingCode(String code, Instant expiresAt) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
/** Appairage refusé : code absent, faux, expiré, ou trop d'essais. Message prêt à afficher. */
|
||||
public class PairingRejectedException extends RuntimeException {
|
||||
|
||||
public PairingRejectedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
/**
|
||||
* Résultat d'un appairage réussi.
|
||||
*
|
||||
* @param token jeton d'appareil en clair : à poser en cookie, jamais renvoyé dans le corps
|
||||
* @param device l'appareil enregistré
|
||||
*/
|
||||
public record PairingResult(String token, PairedDevice device) {
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.Deque;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
|
||||
* <p>
|
||||
* Modèle de confiance : le connecteur habituel reste limité à la machine (127.0.0.1) et
|
||||
* n'exige rien, comme avant. Quand le MJ active l'accès distant, un SECOND connecteur
|
||||
* s'ouvre sur le réseau local ; tout ce qui y arrive doit présenter un jeton d'appareil,
|
||||
* obtenu en saisissant un code à 6 chiffres affiché sur le PC (usage unique, 5 minutes,
|
||||
* 5 essais). Les Paramètres restent réservés à la machine (filtre {@code RemoteAccessFilter}).
|
||||
* <p>
|
||||
* Uniquement en mode bureau (profil {@code local}) : en Docker, rien de tout ceci n'existe.
|
||||
*/
|
||||
@Service
|
||||
@Profile("local")
|
||||
public class RemoteAccessService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RemoteAccessService.class);
|
||||
|
||||
static final Duration CODE_TTL = Duration.ofMinutes(5);
|
||||
static final int CODE_MAX_ATTEMPTS = 5;
|
||||
/** Garde-fou anti force brute tous codes confondus : au-delà, plus aucun essai pendant 1 min. */
|
||||
static final int GLOBAL_MAX_FAILURES_PER_MINUTE = 20;
|
||||
/** On ne réécrit « vu pour la dernière fois » qu'au plus une fois par minute et par appareil. */
|
||||
static final Duration TOUCH_INTERVAL = Duration.ofMinutes(1);
|
||||
static final int DEVICE_NAME_MAX = 100;
|
||||
static final int USER_AGENT_MAX = 300;
|
||||
|
||||
private final RemoteAccessConfigRepository configRepository;
|
||||
private final RemoteDeviceRepository deviceRepository;
|
||||
private final LanConnector lanConnector;
|
||||
private final int localPort;
|
||||
private final Clock clock;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
private PairingCode currentCode;
|
||||
private int attemptsLeft;
|
||||
private final Deque<Instant> recentFailures = new ArrayDeque<>();
|
||||
private String lastError;
|
||||
|
||||
@Autowired
|
||||
public RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||
RemoteDeviceRepository deviceRepository,
|
||||
LanConnector lanConnector,
|
||||
@Value("${server.port:8080}") int localPort) {
|
||||
this(configRepository, deviceRepository, lanConnector, localPort, Clock.systemUTC());
|
||||
}
|
||||
|
||||
RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||
RemoteDeviceRepository deviceRepository,
|
||||
LanConnector lanConnector,
|
||||
int localPort,
|
||||
Clock clock) {
|
||||
this.configRepository = configRepository;
|
||||
this.deviceRepository = deviceRepository;
|
||||
this.lanConnector = lanConnector;
|
||||
this.localPort = localPort;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// --- Réglage -----------------------------------------------------------------------
|
||||
|
||||
/** Au démarrage : rouvre le connecteur si l'accès distant était activé. Ne bloque jamais le lancement. */
|
||||
public synchronized void applySavedConfig() {
|
||||
RemoteAccessConfig config = currentConfig();
|
||||
if (!config.enabled()) return;
|
||||
try {
|
||||
lanConnector.start(config.port());
|
||||
lastError = null;
|
||||
} catch (IllegalStateException e) {
|
||||
lastError = e.getMessage();
|
||||
log.warn("Accès distant activé mais connecteur impossible à ouvrir : {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Active ou désactive l'accès distant. À l'activation, le connecteur est ouvert AVANT
|
||||
* d'enregistrer le réglage : un port occupé laisse l'accès désactivé.
|
||||
*
|
||||
* @throws IllegalArgumentException port hors plage ou identique au port local
|
||||
* @throws IllegalStateException port déjà occupé
|
||||
*/
|
||||
public synchronized RemoteAccessStatus configure(boolean enabled, int port) {
|
||||
if (port < 1024 || port > 65535) {
|
||||
throw new IllegalArgumentException("Le port doit être compris entre 1024 et 65535.");
|
||||
}
|
||||
if (port == localPort) {
|
||||
throw new IllegalArgumentException("Choisissez un port différent de celui de l'application (" + localPort + ").");
|
||||
}
|
||||
if (enabled) {
|
||||
lanConnector.start(port);
|
||||
} else {
|
||||
lanConnector.stop();
|
||||
currentCode = null;
|
||||
}
|
||||
lastError = null;
|
||||
configRepository.save(new RemoteAccessConfig(enabled, port));
|
||||
return status();
|
||||
}
|
||||
|
||||
public synchronized RemoteAccessStatus status() {
|
||||
RemoteAccessConfig config = currentConfig();
|
||||
int running = lanConnector.runningPort();
|
||||
List<String> urls = running > 0
|
||||
? lanConnector.lanAddresses().stream().map(ip -> "http://" + ip + ":" + running).toList()
|
||||
: List.of();
|
||||
List<PairedDevice> devices = deviceRepository.findAll().stream()
|
||||
.sorted(Comparator.comparing(RemoteDevice::getCreatedAt, Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.map(PairedDevice::of)
|
||||
.toList();
|
||||
return new RemoteAccessStatus(config.enabled(), config.port(), running > 0, urls, lastError, devices);
|
||||
}
|
||||
|
||||
private RemoteAccessConfig currentConfig() {
|
||||
return configRepository.find().orElseGet(RemoteAccessConfig::disabledByDefault);
|
||||
}
|
||||
|
||||
// --- Appairage -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Nouveau code d'appairage (remplace le précédent).
|
||||
*
|
||||
* @throws IllegalStateException si l'accès distant n'est pas ouvert
|
||||
*/
|
||||
public synchronized PairingCode newPairingCode() {
|
||||
if (lanConnector.runningPort() <= 0) {
|
||||
throw new IllegalStateException("Activez d'abord l'accès depuis le réseau local.");
|
||||
}
|
||||
String code = String.format("%06d", random.nextInt(1_000_000));
|
||||
currentCode = new PairingCode(code, clock.instant().plus(CODE_TTL));
|
||||
attemptsLeft = CODE_MAX_ATTEMPTS;
|
||||
return currentCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Échange un code valide contre un jeton d'appareil (à poser en cookie). Le code est
|
||||
* consommé : un second appareil demande un nouveau code.
|
||||
*
|
||||
* @throws PairingRejectedException code absent, faux, expiré ou trop d'essais
|
||||
*/
|
||||
public synchronized PairingResult pair(String code, String deviceName, String userAgent) {
|
||||
Instant now = clock.instant();
|
||||
pruneFailures(now);
|
||||
if (recentFailures.size() >= GLOBAL_MAX_FAILURES_PER_MINUTE) {
|
||||
throw new PairingRejectedException("Trop d'essais. Patientez une minute.");
|
||||
}
|
||||
if (currentCode == null || now.isAfter(currentCode.expiresAt())) {
|
||||
currentCode = null;
|
||||
recordFailure(now);
|
||||
throw new PairingRejectedException("Aucun code valide : affichez un nouveau code sur le PC.");
|
||||
}
|
||||
if (code == null || !constantTimeEquals(code.trim(), currentCode.code())) {
|
||||
recordFailure(now);
|
||||
if (--attemptsLeft <= 0) {
|
||||
currentCode = null;
|
||||
throw new PairingRejectedException("Trop d'essais : affichez un nouveau code sur le PC.");
|
||||
}
|
||||
throw new PairingRejectedException("Code incorrect.");
|
||||
}
|
||||
currentCode = null;
|
||||
|
||||
String token = newToken();
|
||||
RemoteDevice device = deviceRepository.save(RemoteDevice.builder()
|
||||
.name(clean(deviceName, DEVICE_NAME_MAX, "Appareil"))
|
||||
.tokenHash(sha256(token))
|
||||
.userAgent(clean(userAgent, USER_AGENT_MAX, null))
|
||||
.createdAt(now)
|
||||
.lastSeenAt(now)
|
||||
.build());
|
||||
log.info("Accès distant : appareil appairé « {} »", device.getName());
|
||||
return new PairingResult(token, PairedDevice.of(device));
|
||||
}
|
||||
|
||||
/** Appareil correspondant au jeton présenté, s'il est connu (sinon : appairage requis). */
|
||||
public Optional<RemoteDevice> authenticate(String token) {
|
||||
if (token == null || token.isBlank()) return Optional.empty();
|
||||
Optional<RemoteDevice> device = deviceRepository.findByTokenHash(sha256(token));
|
||||
device.ifPresent(d -> {
|
||||
Instant now = clock.instant();
|
||||
if (d.getLastSeenAt() == null || d.getLastSeenAt().plus(TOUCH_INTERVAL).isBefore(now)) {
|
||||
deviceRepository.touch(d.getId(), now);
|
||||
}
|
||||
});
|
||||
return device;
|
||||
}
|
||||
|
||||
/** Coupe l'accès d'un appareil. */
|
||||
public boolean revoke(String deviceId) {
|
||||
return deviceRepository.deleteById(deviceId);
|
||||
}
|
||||
|
||||
/** Port réseau réglé (ouvert ou non) : celui que le pare-feu doit laisser passer. */
|
||||
public synchronized int configuredPort() {
|
||||
return currentConfig().port();
|
||||
}
|
||||
|
||||
/** Port du connecteur réseau ouvert, ou -1 (pour le filtre : qui vient « de l'extérieur » ?). */
|
||||
public int lanPort() {
|
||||
return lanConnector.runningPort();
|
||||
}
|
||||
|
||||
// --- Outils -----------------------------------------------------------------------------
|
||||
|
||||
private void recordFailure(Instant now) {
|
||||
recentFailures.addLast(now);
|
||||
}
|
||||
|
||||
private void pruneFailures(Instant now) {
|
||||
Instant limit = now.minus(Duration.ofMinutes(1));
|
||||
while (!recentFailures.isEmpty() && recentFailures.peekFirst().isBefore(limit)) {
|
||||
recentFailures.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
private String newToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
static String sha256(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 indisponible", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean constantTimeEquals(String a, String b) {
|
||||
return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String clean(String value, int max, String fallback) {
|
||||
if (value == null || value.isBlank()) return fallback;
|
||||
String trimmed = value.strip();
|
||||
return trimmed.length() > max ? trimmed.substring(0, max) : trimmed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* État de l'accès distant, pour l'écran Paramètres du PC.
|
||||
*
|
||||
* @param enabled accès activé (réglage enregistré)
|
||||
* @param port port réseau dédié
|
||||
* @param running connecteur réseau effectivement ouvert
|
||||
* @param urls adresses à taper sur la tablette (une par interface réseau locale)
|
||||
* @param lastError dernière erreur d'ouverture (ex. port occupé au démarrage), ou null
|
||||
* @param devices appareils appairés
|
||||
*/
|
||||
public record RemoteAccessStatus(
|
||||
boolean enabled,
|
||||
int port,
|
||||
boolean running,
|
||||
List<String> urls,
|
||||
String lastError,
|
||||
List<PairedDevice> devices
|
||||
) {
|
||||
}
|
||||
@@ -44,6 +44,9 @@ public class Campaign {
|
||||
*/
|
||||
private String graphPositions;
|
||||
|
||||
/** Fiche « Publication » (couverture, page technique, crédits…). Null = jamais renseignée. */
|
||||
private CampaignPublication publication;
|
||||
|
||||
public boolean isLinkedToLore() {
|
||||
return this.loreId != null && !this.loreId.isBlank();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.loremind.domain.campaigncontext;
|
||||
|
||||
/** Lightweight search projection with the ancestors needed to open a result. */
|
||||
public record CampaignContentHit(String kind, String id, String name,
|
||||
String campaignId, String campaignName, String arcId, String arcName,
|
||||
String chapterId, String chapterName) {}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.loremind.domain.campaigncontext;
|
||||
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
* Fiche « Publication » d'une campagne : ce qu'un module vendu ou partagé affiche en
|
||||
* couverture, page technique, introduction pour le MJ et page de crédits.
|
||||
* <p>
|
||||
* Tout est en texte libre (« 1 à 3 », « 3-5 joueurs », « 2 séances de 4 h ») : chaque
|
||||
* système de jeu a ses conventions, l'auteur écrit ce qu'il veut voir imprimé.
|
||||
* Valeur immuable ; {@link #normalized()} nettoie une saisie (blancs → null, longueurs bornées).
|
||||
*
|
||||
* @param subtitle sous-titre de couverture
|
||||
* @param author auteur(s) affichés en couverture
|
||||
* @param system système de jeu tel qu'il doit apparaître (« D&D 5e », « Chroniques Oubliées »)
|
||||
* @param levels niveaux des personnages
|
||||
* @param players nombre de joueurs
|
||||
* @param duration durée de jeu estimée
|
||||
* @param pitch argument : l'aventure en quelques lignes
|
||||
* @param gmBackground contexte caché, réservé au MJ (ce qui s'est vraiment passé)
|
||||
* @param hooks accroches pour impliquer les personnages (une par ligne « - … »)
|
||||
* @param contentWarnings avertissements de contenu (thèmes sensibles)
|
||||
* @param credits crédits : auteur, illustrations, relecture, testeurs…
|
||||
* @param legal licence et mentions légales
|
||||
* @param version version du document (« 1.0 »)
|
||||
* @param coverImageId image de couverture (id d'image), nullable
|
||||
*/
|
||||
public record CampaignPublication(
|
||||
String subtitle,
|
||||
String author,
|
||||
String system,
|
||||
String levels,
|
||||
String players,
|
||||
String duration,
|
||||
String pitch,
|
||||
String gmBackground,
|
||||
String hooks,
|
||||
String contentWarnings,
|
||||
String credits,
|
||||
String legal,
|
||||
String version,
|
||||
String coverImageId
|
||||
) {
|
||||
|
||||
private static final int SHORT_MAX = 200;
|
||||
private static final int LONG_MAX = 20_000;
|
||||
|
||||
public static CampaignPublication empty() {
|
||||
return new CampaignPublication(null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
/** Copie nettoyée : textes rognés, blancs → null, longueurs bornées. */
|
||||
public CampaignPublication normalized() {
|
||||
UnaryOperator<String> shortText = s -> clean(s, SHORT_MAX);
|
||||
UnaryOperator<String> longText = s -> clean(s, LONG_MAX);
|
||||
return new CampaignPublication(
|
||||
shortText.apply(subtitle), shortText.apply(author), shortText.apply(system),
|
||||
shortText.apply(levels), shortText.apply(players), shortText.apply(duration),
|
||||
longText.apply(pitch), longText.apply(gmBackground), longText.apply(hooks),
|
||||
longText.apply(contentWarnings), longText.apply(credits), longText.apply(legal),
|
||||
shortText.apply(version), shortText.apply(coverImageId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si au moins un champ est renseigné. (Pas de getter {@code isEmpty()} : il serait
|
||||
* sérialisé en JSON comme un champ de plus.)
|
||||
*/
|
||||
public boolean hasContent() {
|
||||
return !normalized().equals(empty());
|
||||
}
|
||||
|
||||
/** Au moins une information de la page technique (système, niveaux, joueurs, durée). */
|
||||
public boolean hasTechnicalSheet() {
|
||||
return present(system) || present(levels) || present(players) || present(duration);
|
||||
}
|
||||
|
||||
/** Au moins une information de la page de crédits. */
|
||||
public boolean hasCredits() {
|
||||
return present(author) || present(credits) || present(legal) || present(version);
|
||||
}
|
||||
|
||||
private static boolean present(String s) {
|
||||
return s != null && !s.isBlank();
|
||||
}
|
||||
|
||||
private static String clean(String s, int max) {
|
||||
if (s == null) return null;
|
||||
String t = s.trim();
|
||||
if (t.isEmpty()) return null;
|
||||
return t.length() > max ? t.substring(0, max) : t;
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,9 @@ public class Npc {
|
||||
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
|
||||
private int order;
|
||||
|
||||
/** Rôle dans l'histoire (rôle, motivation, ce qu'il sait, signe distinctif). Null = non renseigné. */
|
||||
private NpcStory story;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.loremind.domain.campaigncontext.bestiary;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Fiche « rôle dans l'histoire » d'un PNJ, indépendante du système de jeu (le gabarit du
|
||||
* système porte les caractéristiques) : ce qui rend le PNJ jouable et utile au récit.
|
||||
*
|
||||
* @param role place dans l'histoire : {@code OPPONENT} (s'oppose aux PJ), {@code ALLY}
|
||||
* (les aide), {@code RESOURCE} (détient une information ou un service),
|
||||
* {@code EXTRA} (figurant) ; null = non précisé
|
||||
* @param motivation ce qu'il veut, et ce qu'il est prêt à faire pour l'obtenir
|
||||
* @param knowledge ce qu'il sait (et peut révéler) — réservé au MJ
|
||||
* @param mannerism signe distinctif à jouer (geste, phrasé, tic)
|
||||
*/
|
||||
public record NpcStory(String role, String motivation, String knowledge, String mannerism) {
|
||||
|
||||
public static final Set<String> ROLES = Set.of("OPPONENT", "ALLY", "RESOURCE", "EXTRA");
|
||||
private static final int SHORT_MAX = 300;
|
||||
private static final int LONG_MAX = 10_000;
|
||||
|
||||
/** Copie nettoyée : rôle inconnu → null, textes rognés (blancs → null) et bornés. */
|
||||
public NpcStory normalized() {
|
||||
String r = role == null ? null : role.trim().toUpperCase(Locale.ROOT);
|
||||
// Set.of(...).contains(null) lève une NullPointerException : rôle absent testé à part.
|
||||
return new NpcStory(r != null && ROLES.contains(r) ? r : null,
|
||||
clean(motivation, LONG_MAX), clean(knowledge, LONG_MAX), clean(mannerism, SHORT_MAX));
|
||||
}
|
||||
|
||||
/** Vrai si au moins un élément est renseigné. */
|
||||
public boolean hasContent() {
|
||||
NpcStory n = normalized();
|
||||
return n.role() != null || n.motivation() != null || n.knowledge() != null || n.mannerism() != null;
|
||||
}
|
||||
|
||||
/** Un PNJ qui pèse sur l'intrigue (opposant ou allié) : sa motivation est attendue. */
|
||||
public boolean drivesThePlot() {
|
||||
String r = normalized().role();
|
||||
return "OPPONENT".equals(r) || "ALLY".equals(r);
|
||||
}
|
||||
|
||||
private static String clean(String s, int max) {
|
||||
if (s == null) return null;
|
||||
String t = s.trim();
|
||||
if (t.isEmpty()) return null;
|
||||
return t.length() > max ? t.substring(0, max) : t;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.loremind.domain.campaigncontext.ports;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||
import java.util.List;
|
||||
|
||||
public interface CampaignContentSearchRepository {
|
||||
List<CampaignContentHit> searchByName(String query);
|
||||
}
|
||||
@@ -38,6 +38,8 @@ public class Arc {
|
||||
private String gmNotes; // Notes privées du MJ (non exportées vers FoundryVTT)
|
||||
private String rewards; // Récompenses et progression
|
||||
private String resolution; // Dénouement prévu
|
||||
private String hiddenTruth; // Histoire cachée : ce qui s'est vraiment passé (réservé au MJ)
|
||||
private String hooks; // Accroches : pourquoi les personnages s'en mêlent (une par ligne)
|
||||
|
||||
/**
|
||||
* IDs des pages du Lore associées à cet arc (weak cross-context references).
|
||||
|
||||
@@ -48,6 +48,8 @@ public class Scene {
|
||||
|
||||
// === Combat ou rencontre ===
|
||||
private String combatDifficulty; // Difficulté estimée
|
||||
private String tactics; // Tactique et moral des adversaires (quand fuient-ils, se rendent-ils ?)
|
||||
private String purpose; // Utilité : ce que l'histoire perd si on coupe la scène
|
||||
private String enemies; // Liste des ennemis et créatures (texte libre)
|
||||
|
||||
/**
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.loremind.domain.campaigncontext.writingreview;
|
||||
|
||||
/**
|
||||
* Famille d'une remarque de relecture (Mentor d'écriture, phase M2). Sert à
|
||||
* regrouper les conseils côté front ; n'implique aucune gravité : une remarque de
|
||||
* relecture est un conseil d'auteur, jamais un blocage.
|
||||
*/
|
||||
public enum WritingRemarkCategory {
|
||||
/** Pouvoir des joueurs : vrais choix, chemins multiples, issues alternatives. */
|
||||
AGENCY,
|
||||
/** Rythme : variété des scènes, lisibilité de la structure. */
|
||||
PACING,
|
||||
/** Enjeux : ce que les joueurs risquent, pourquoi l'adversité agit. */
|
||||
STAKES,
|
||||
/** Narration : textes lus aux joueurs. */
|
||||
NARRATION
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.persistence.converter;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
/**
|
||||
* Convertit la fiche {@link CampaignPublication} en JSON stocké dans une colonne TEXT,
|
||||
* et inversement. Fiche vide → NULL en base. Champs inconnus ignorés (fiche écrite par
|
||||
* une version plus récente).
|
||||
*/
|
||||
@Converter
|
||||
public class CampaignPublicationJsonConverter implements AttributeConverter<CampaignPublication, String> {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(CampaignPublication attribute) {
|
||||
if (attribute == null || !attribute.hasContent()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.writeValueAsString(attribute);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur sérialisation CampaignPublication → JSON", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CampaignPublication convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readValue(dbData, CampaignPublication.class);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur désérialisation JSON → CampaignPublication", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.persistence.converter;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
/**
|
||||
* Convertit la fiche {@link NpcStory} (rôle dans l'histoire d'un PNJ) en JSON stocké dans une colonne TEXT,
|
||||
* et inversement. Fiche vide → NULL en base. Champs inconnus ignorés (fiche écrite par
|
||||
* une version plus récente).
|
||||
*/
|
||||
@Converter
|
||||
public class NpcStoryJsonConverter implements AttributeConverter<NpcStory, String> {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(NpcStory attribute) {
|
||||
if (attribute == null || !attribute.hasContent()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.writeValueAsString(attribute);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur sérialisation NpcStory → JSON", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public NpcStory convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readValue(dbData, NpcStory.class);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Erreur désérialisation JSON → NpcStory", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,12 @@ public class ArcJpaEntity {
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String resolution;
|
||||
|
||||
@Column(name = "hidden_truth", columnDefinition = "TEXT")
|
||||
private String hiddenTruth;
|
||||
|
||||
@Column(name = "hooks", columnDefinition = "TEXT")
|
||||
private String hooks;
|
||||
|
||||
/**
|
||||
* IDs des pages du Lore liées à cet arc, stockés en JSON dans une colonne TEXT.
|
||||
* Pas de FK cross-context : respect des Bounded Contexts.
|
||||
|
||||
+7
@@ -1,5 +1,7 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.infrastructure.persistence.converter.CampaignPublicationJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -63,6 +65,11 @@ public class CampaignJpaEntity {
|
||||
@Column(name = "graph_positions", columnDefinition = "TEXT")
|
||||
private String graphPositions;
|
||||
|
||||
/** Fiche « Publication » (JSON). NULL = jamais renseignée. */
|
||||
@Column(name = "publication", columnDefinition = "TEXT")
|
||||
@Convert(converter = CampaignPublicationJsonConverter.class)
|
||||
private CampaignPublication publication;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||
|
||||
@@ -67,6 +67,11 @@ public class NpcJpaEntity {
|
||||
@Column(name = "\"order\"", nullable = false)
|
||||
private int order;
|
||||
|
||||
/** Fiche « rôle dans l'histoire » (JSON). NULL = non renseignée. */
|
||||
@Column(name = "story", columnDefinition = "TEXT")
|
||||
@Convert(converter = com.loremind.infrastructure.persistence.converter.NpcStoryJsonConverter.class)
|
||||
private com.loremind.domain.campaigncontext.bestiary.NpcStory story;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
|
||||
+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;
|
||||
}
|
||||
@@ -78,6 +78,14 @@ public class SceneJpaEntity {
|
||||
@Column(name = "choices_consequences", columnDefinition = "TEXT")
|
||||
private String choicesConsequences;
|
||||
|
||||
// Tactique et moral des adversaires
|
||||
@Column(name = "tactics", columnDefinition = "TEXT")
|
||||
private String tactics;
|
||||
|
||||
// Utilité de la scène dans l'histoire
|
||||
@Column(name = "purpose", columnDefinition = "TEXT")
|
||||
private String purpose;
|
||||
|
||||
// Combat
|
||||
@Column(name = "combat_difficulty", columnDefinition = "TEXT")
|
||||
private String combatDifficulty;
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
+4
@@ -77,6 +77,8 @@ public class PostgresArcRepository implements ArcRepository {
|
||||
.gmNotes(jpaEntity.getGmNotes())
|
||||
.rewards(jpaEntity.getRewards())
|
||||
.resolution(jpaEntity.getResolution())
|
||||
.hiddenTruth(jpaEntity.getHiddenTruth())
|
||||
.hooks(jpaEntity.getHooks())
|
||||
// Defensive copy : jamais de null en domaine pour simplifier les appelants.
|
||||
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
||||
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
||||
@@ -104,6 +106,8 @@ public class PostgresArcRepository implements ArcRepository {
|
||||
.gmNotes(arc.getGmNotes())
|
||||
.rewards(arc.getRewards())
|
||||
.resolution(arc.getResolution())
|
||||
.hiddenTruth(arc.getHiddenTruth())
|
||||
.hooks(arc.getHooks())
|
||||
.relatedPageIds(arc.getRelatedPageIds() != null
|
||||
? new ArrayList<>(arc.getRelatedPageIds())
|
||||
: new ArrayList<>())
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** One bounded query; never loads complete scenes or one tree per campaign. */
|
||||
@Repository
|
||||
public class PostgresCampaignContentSearchRepository implements CampaignContentSearchRepository {
|
||||
private final NamedParameterJdbcTemplate jdbc;
|
||||
|
||||
public PostgresCampaignContentSearchRepository(NamedParameterJdbcTemplate jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
private static final String SQL = """
|
||||
SELECT * FROM (
|
||||
SELECT 'arc' AS kind, a.id, a.name, c.id AS campaign_id, c.name AS campaign_name,
|
||||
a.id AS arc_id, a.name AS arc_name, CAST(NULL AS BIGINT) AS chapter_id,
|
||||
CAST(NULL AS VARCHAR) AS chapter_name
|
||||
FROM arcs a JOIN campaigns c ON c.id = a.campaign_id
|
||||
WHERE a.type <> 'SYSTEM' AND LOWER(a.name) LIKE :query ESCAPE '!'
|
||||
UNION ALL
|
||||
SELECT 'chapter', ch.id, ch.name, c.id, c.name, a.id, a.name, ch.id, ch.name
|
||||
FROM chapters ch JOIN arcs a ON a.id = ch.arc_id JOIN campaigns c ON c.id = a.campaign_id
|
||||
WHERE a.type <> 'SYSTEM' AND LOWER(ch.name) LIKE :query ESCAPE '!'
|
||||
UNION ALL
|
||||
SELECT 'scene', s.id, s.name, c.id, c.name, a.id,
|
||||
CASE WHEN a.type = 'SYSTEM' THEN NULL ELSE a.name END, ch.id, ch.name
|
||||
FROM scenes s JOIN chapters ch ON ch.id = s.chapter_id
|
||||
JOIN arcs a ON a.id = ch.arc_id JOIN campaigns c ON c.id = a.campaign_id
|
||||
WHERE LOWER(s.name) LIKE :query ESCAPE '!'
|
||||
UNION ALL
|
||||
SELECT 'quest', q.id, q.name, c.id, c.name, a.id, a.name, NULL, NULL
|
||||
FROM quests q JOIN campaigns c ON c.id = q.campaign_id
|
||||
LEFT JOIN arcs a ON a.id = q.arc_id AND a.campaign_id = c.id
|
||||
WHERE LOWER(q.name) LIKE :query ESCAPE '!'
|
||||
) hits
|
||||
ORDER BY LOWER(name), campaign_id, kind, id
|
||||
LIMIT 80
|
||||
""";
|
||||
|
||||
@Override
|
||||
public List<CampaignContentHit> searchByName(String query) {
|
||||
String pattern = "%" + query.toLowerCase(Locale.ROOT)
|
||||
.replace("!", "!!").replace("%", "!%").replace("_", "!_") + "%";
|
||||
return jdbc.query(SQL, Map.of("query", pattern), (rs, row) -> new CampaignContentHit(
|
||||
rs.getString("kind"), rs.getString("id"), rs.getString("name"),
|
||||
rs.getString("campaign_id"), rs.getString("campaign_name"),
|
||||
rs.getString("arc_id"), rs.getString("arc_name"),
|
||||
rs.getString("chapter_id"), rs.getString("chapter_name")));
|
||||
}
|
||||
}
|
||||
+2
@@ -76,6 +76,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
||||
.loreId(jpaEntity.getLoreId())
|
||||
.gameSystemId(jpaEntity.getGameSystemId())
|
||||
.graphPositions(jpaEntity.getGraphPositions())
|
||||
.publication(jpaEntity.getPublication())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -92,6 +93,7 @@ public class PostgresCampaignRepository implements CampaignRepository {
|
||||
.loreId(campaign.getLoreId())
|
||||
.gameSystemId(campaign.getGameSystemId())
|
||||
.graphPositions(campaign.getGraphPositions())
|
||||
.publication(campaign.getPublication())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -68,6 +68,7 @@ public class PostgresNpcRepository implements NpcRepository {
|
||||
.campaignId(e.getCampaignId().toString())
|
||||
.relatedPageIds(e.getRelatedPageIds() != null ? new ArrayList<>(e.getRelatedPageIds()) : new ArrayList<>())
|
||||
.folder(e.getFolder())
|
||||
.story(e.getStory())
|
||||
.order(e.getOrder())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.updatedAt(e.getUpdatedAt())
|
||||
@@ -87,6 +88,7 @@ public class PostgresNpcRepository implements NpcRepository {
|
||||
.campaignId(Long.parseLong(n.getCampaignId()))
|
||||
.relatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>())
|
||||
.folder(n.getFolder())
|
||||
.story(n.getStory())
|
||||
.order(n.getOrder())
|
||||
.createdAt(n.getCreatedAt())
|
||||
.updatedAt(n.getUpdatedAt())
|
||||
|
||||
+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();
|
||||
}
|
||||
}
|
||||
+4
@@ -80,6 +80,8 @@ public class PostgresSceneRepository implements SceneRepository {
|
||||
.gmSecretNotes(jpaEntity.getGmSecretNotes())
|
||||
.choicesConsequences(jpaEntity.getChoicesConsequences())
|
||||
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
||||
.tactics(jpaEntity.getTactics())
|
||||
.purpose(jpaEntity.getPurpose())
|
||||
.enemies(jpaEntity.getEnemies())
|
||||
.enemyIds(jpaEntity.getEnemyIds() != null
|
||||
? new ArrayList<>(jpaEntity.getEnemyIds())
|
||||
@@ -123,6 +125,8 @@ public class PostgresSceneRepository implements SceneRepository {
|
||||
.gmSecretNotes(scene.getGmSecretNotes())
|
||||
.choicesConsequences(scene.getChoicesConsequences())
|
||||
.combatDifficulty(scene.getCombatDifficulty())
|
||||
.tactics(scene.getTactics())
|
||||
.purpose(scene.getPurpose())
|
||||
.enemies(scene.getEnemies())
|
||||
.enemyIds(scene.getEnemyIds() != null
|
||||
? new ArrayList<>(scene.getEnemyIds())
|
||||
|
||||
+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))
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.transfer;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||
@@ -99,11 +100,20 @@ class CampaignContentInserter {
|
||||
e.setPlayerCount(d.playerCount());
|
||||
e.setLoreId(d.loreId()); // remappe en 2e passe
|
||||
e.setGameSystemId(d.gameSystemId()); // remappe en 2e passe
|
||||
e.setPublication(remapCover(maps, d.publication()));
|
||||
maps.campaignMap.put(d.id(), campaignRepo.save(e).getId());
|
||||
}
|
||||
result.count("campaigns", maps.campaignMap.size());
|
||||
}
|
||||
|
||||
/** Fiche « Publication » : l'image de couverture suit le remapping des images importées. */
|
||||
private static CampaignPublication remapCover(ImportIdMaps maps, CampaignPublication p) {
|
||||
if (p == null || p.coverImageId() == null) return p;
|
||||
return new CampaignPublication(p.subtitle(), p.author(), p.system(), p.levels(), p.players(),
|
||||
p.duration(), p.pitch(), p.gmBackground(), p.hooks(), p.contentWarnings(), p.credits(),
|
||||
p.legal(), p.version(), IdRemapper.remapStringId(maps.imageMap, p.coverImageId()));
|
||||
}
|
||||
|
||||
/** Arc (relatedPageIds remappe en 2e passe). */
|
||||
private void insertArcs(ContentExport export, ImportIdMaps maps, ImportResult.Builder result) {
|
||||
for (ContentExport.ArcDto d : nullSafe(export.arcs())) {
|
||||
@@ -119,6 +129,8 @@ class CampaignContentInserter {
|
||||
e.setGmNotes(d.gmNotes());
|
||||
e.setRewards(d.rewards());
|
||||
e.setResolution(d.resolution());
|
||||
e.setHiddenTruth(d.hiddenTruth());
|
||||
e.setHooks(d.hooks());
|
||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
||||
e.setIllustrationImageIds(IdRemapper.remapStringList(maps.imageMap, d.illustrationImageIds()));
|
||||
maps.arcMap.put(d.id(), arcRepo.save(e).getId());
|
||||
@@ -257,6 +269,7 @@ class CampaignContentInserter {
|
||||
e.setRelatedPageIds(d.relatedPageIds()); // remappe en 2e passe
|
||||
e.setFolder(d.folder());
|
||||
e.setOrder(d.order());
|
||||
e.setStory(d.story());
|
||||
maps.npcMap.put(d.id(), npcRepo.save(e).getId());
|
||||
}
|
||||
result.count("npcs", maps.npcMap.size());
|
||||
@@ -307,6 +320,8 @@ class CampaignContentInserter {
|
||||
e.setBattlemaps(resolveBattlemaps(d, maps));
|
||||
e.setGraphX(d.graphX());
|
||||
e.setGraphY(d.graphY());
|
||||
e.setTactics(d.tactics());
|
||||
e.setPurpose(d.purpose());
|
||||
e.setBranches(d.branches()); // remappe en 2e passe
|
||||
// Rooms : l'id (UUID) et les branches restent tels quels ; seules leurs refs
|
||||
// d'images (galerie + plan) sont remappees vers les images importees.
|
||||
|
||||
@@ -200,7 +200,7 @@ public class ExportService {
|
||||
List<QuestJpaEntity> campaignQuests = questRepo.findByCampaignId(cid);
|
||||
// Images/fichiers : uniquement les binaires RÉFÉRENCÉS par la clôture (si option active).
|
||||
BinaryClosure binaries = req.includeImages()
|
||||
? loadBinaryClosure(structure, lore, play, campaignQuests) : BinaryClosure.EMPTY;
|
||||
? loadBinaryClosure(campaign, structure, lore, play, campaignQuests) : BinaryClosure.EMPTY;
|
||||
|
||||
ContentExport.CampaignDto campaignDto = campaignDto(campaign, req.includeLore());
|
||||
|
||||
@@ -304,9 +304,11 @@ public class ExportService {
|
||||
private static final BinaryClosure EMPTY = new BinaryClosure(List.of(), List.of());
|
||||
}
|
||||
|
||||
private BinaryClosure loadBinaryClosure(StructuralClosure structure, LoreClosure lore, PlayClosure play,
|
||||
private BinaryClosure loadBinaryClosure(CampaignJpaEntity campaign, StructuralClosure structure,
|
||||
LoreClosure lore, PlayClosure play,
|
||||
List<QuestJpaEntity> campaignQuests) {
|
||||
Set<String> imageRefs = new LinkedHashSet<>();
|
||||
if (campaign.getPublication() != null) add(imageRefs, campaign.getPublication().coverImageId());
|
||||
structure.arcs().forEach(a -> addAll(imageRefs, a.getIllustrationImageIds()));
|
||||
structure.chapters().forEach(c -> addAll(imageRefs, c.getIllustrationImageIds()));
|
||||
campaignQuests.forEach(q -> addAll(imageRefs, q.getIllustrationImageIds()));
|
||||
@@ -340,7 +342,7 @@ public class ExportService {
|
||||
ContentExport.CampaignDto dto = toCampaignDto(campaign);
|
||||
if (includeLore) return dto;
|
||||
return new ContentExport.CampaignDto(dto.id(), dto.name(), dto.description(),
|
||||
dto.arcsCount(), dto.playerCount(), null, dto.gameSystemId());
|
||||
dto.arcsCount(), dto.playerCount(), null, dto.gameSystemId(), dto.publication());
|
||||
}
|
||||
|
||||
// ----- Helpers de chargement -----
|
||||
@@ -471,6 +473,9 @@ public class ExportService {
|
||||
/** Collecte les IDs d'images référencés par toutes les entités exportées (avant résolution en storageKey). */
|
||||
private Set<String> collectImageIdRefs(ContentExport export) {
|
||||
Set<String> refs = new LinkedHashSet<>();
|
||||
for (ContentExport.CampaignDto c : export.campaigns()) {
|
||||
if (c.publication() != null) add(refs, c.publication().coverImageId());
|
||||
}
|
||||
for (ContentExport.ArcDto a : export.arcs()) addAll(refs, a.illustrationImageIds());
|
||||
for (ContentExport.ChapterDto c : export.chapters()) addAll(refs, c.illustrationImageIds());
|
||||
addQuestImageRefs(refs, export.quests());
|
||||
@@ -599,7 +604,8 @@ public class ExportService {
|
||||
|
||||
private ContentExport.CampaignDto toCampaignDto(CampaignJpaEntity e) {
|
||||
return new ContentExport.CampaignDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getArcsCount(), e.getPlayerCount(), e.getLoreId(), e.getGameSystemId());
|
||||
e.getArcsCount(), e.getPlayerCount(), e.getLoreId(), e.getGameSystemId(),
|
||||
e.getPublication());
|
||||
}
|
||||
|
||||
private ContentExport.ArcDto toArcDto(ArcJpaEntity e) {
|
||||
@@ -608,7 +614,7 @@ public class ExportService {
|
||||
e.getType() != null ? e.getType().name() : null,
|
||||
e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(),
|
||||
e.getRewards(), e.getResolution(), e.getRelatedPageIds(),
|
||||
e.getIllustrationImageIds());
|
||||
e.getIllustrationImageIds(), e.getHiddenTruth(), e.getHooks());
|
||||
}
|
||||
|
||||
private ContentExport.ChapterDto toChapterDto(ChapterJpaEntity e) {
|
||||
@@ -637,7 +643,7 @@ public class ExportService {
|
||||
e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(),
|
||||
e.getIllustrationImageIds(), null, null, // legacy battlemap : plus émis
|
||||
e.getBattlemaps(), e.getBranches(), e.getRooms(), e.getType(),
|
||||
e.getGraphX(), e.getGraphY());
|
||||
e.getGraphX(), e.getGraphY(), e.getTactics(), e.getPurpose());
|
||||
}
|
||||
|
||||
private ContentExport.CharacterDto toCharacterDto(CharacterJpaEntity e) {
|
||||
@@ -649,7 +655,7 @@ public class ExportService {
|
||||
private ContentExport.NpcDto toNpcDto(NpcJpaEntity e) {
|
||||
return new ContentExport.NpcDto(e.getId(), e.getName(), e.getPortraitImageId(),
|
||||
e.getHeaderImageId(), e.getValues(), e.getImageValues(), e.getKeyValueValues(),
|
||||
e.getCampaignId(), e.getRelatedPageIds(), e.getFolder(), e.getOrder());
|
||||
e.getCampaignId(), e.getRelatedPageIds(), e.getFolder(), e.getOrder(), e.getStory());
|
||||
}
|
||||
|
||||
private ContentExport.EnemyDto toEnemyDto(EnemyJpaEntity e) {
|
||||
|
||||
@@ -128,7 +128,9 @@ public record ContentExport(
|
||||
int arcsCount,
|
||||
int playerCount,
|
||||
String loreId,
|
||||
String gameSystemId
|
||||
String gameSystemId,
|
||||
/** Fiche « Publication » ; absente des bundles antérieurs (null). */
|
||||
com.loremind.domain.campaigncontext.CampaignPublication publication
|
||||
) {}
|
||||
|
||||
public record ArcDto(
|
||||
@@ -145,7 +147,10 @@ public record ContentExport(
|
||||
String rewards,
|
||||
String resolution,
|
||||
List<String> relatedPageIds,
|
||||
List<String> illustrationImageIds
|
||||
List<String> illustrationImageIds,
|
||||
/** Histoire cachée et accroches ; absentes des bundles antérieurs (null). */
|
||||
String hiddenTruth,
|
||||
String hooks
|
||||
) {}
|
||||
|
||||
public record ChapterDto(
|
||||
@@ -195,7 +200,10 @@ public record ContentExport(
|
||||
List<Room> rooms,
|
||||
SceneType type,
|
||||
Double graphX,
|
||||
Double graphY
|
||||
Double graphY,
|
||||
/** Tactique des adversaires et utilité ; absentes des bundles antérieurs (null). */
|
||||
String tactics,
|
||||
String purpose
|
||||
) {}
|
||||
|
||||
public record CharacterDto(
|
||||
@@ -222,7 +230,9 @@ public record ContentExport(
|
||||
Long campaignId,
|
||||
List<String> relatedPageIds,
|
||||
String folder,
|
||||
int order
|
||||
int order,
|
||||
/** Rôle dans l'histoire ; absent des bundles antérieurs (null). */
|
||||
com.loremind.domain.campaigncontext.bestiary.NpcStory story
|
||||
) {}
|
||||
|
||||
public record EnemyDto(
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
package com.loremind.infrastructure.transfer.pdf;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.infrastructure.persistence.entity.ArcJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.entity.ChapterJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.entity.SceneJpaEntity;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.*;
|
||||
|
||||
/**
|
||||
* Annexes d'un module publie : ce que le MJ consulte en jeu sans feuilleter tout le livret.
|
||||
* <ul>
|
||||
* <li>Revelations et indices : pour chaque revelation, les scenes qui y menent (et leur page) —
|
||||
* le MJ voit d'un coup d'oeil ce que les joueurs peuvent encore decouvrir ;</li>
|
||||
* <li>index des PNJ et des adversaires (avec les scenes ou ces derniers apparaissent) ;</li>
|
||||
* <li>cartes : chaque battlemap et plan de piece sur sa propre page paysage, en grand,
|
||||
* prete a imprimer ou a montrer aux joueurs.</li>
|
||||
* </ul>
|
||||
* Les renvois vers des parties absentes sont neutralises en fin de rendu ({@link PdfHtml#resolveRefs}).
|
||||
*/
|
||||
final class PdfAppendices {
|
||||
|
||||
/** Une carte rendue en pleine page paysage dans l'annexe. */
|
||||
record MapPage(String anchor, String title, PdfImage image) {}
|
||||
|
||||
/** Ligne d'index (PNJ ou adversaire). */
|
||||
record IndexRow(String anchor, String name, String folder, String level) {}
|
||||
|
||||
/** Resolution des cartes en annexe (plus fine que les illustrations : elles sont imprimees en grand). */
|
||||
static final int MAP_MAX = 2400;
|
||||
private static final String TD_OPEN = "<td>";
|
||||
private static final String TD_CLOSE = "</td>";
|
||||
|
||||
private PdfAppendices() {}
|
||||
|
||||
// ====================================================================== Cartes
|
||||
|
||||
/**
|
||||
* Cartes de chaque scene, dans l'ordre du livret : battlemaps (images uniquement) puis
|
||||
* plans des pieces. Encodees UNE fois : la scene y renvoie, l'annexe les affiche.
|
||||
*/
|
||||
static Map<Long, List<MapPage>> collectMaps(Structure st, PdfImageEncoder encoder) {
|
||||
Map<Long, List<MapPage>> maps = new LinkedHashMap<>();
|
||||
for (SceneJpaEntity sc : scenesInOrder(st)) {
|
||||
List<MapPage> pages = new ArrayList<>();
|
||||
if (sc.getBattlemaps() != null) {
|
||||
int i = 0;
|
||||
for (var bm : sc.getBattlemaps()) {
|
||||
PdfImage img = encoder.fileImage(bm.mediaFileId(), MAP_MAX);
|
||||
if (img == null) continue;
|
||||
String label = notBlank(bm.label()) ? sc.getName() + " — " + bm.label().trim() : sc.getName();
|
||||
pages.add(new MapPage("map-" + sc.getId() + "-" + (i++), label, img));
|
||||
}
|
||||
}
|
||||
if (sc.getRooms() != null) {
|
||||
List<Room> rooms = new ArrayList<>(sc.getRooms());
|
||||
rooms.sort(Comparator.comparingInt(Room::getOrder));
|
||||
for (Room r : rooms) {
|
||||
PdfImage img = encoder.image(r.getMapImageId(), MAP_MAX);
|
||||
if (img != null) {
|
||||
pages.add(new MapPage(roomMapAnchor(sc.getId(), r.getId()),
|
||||
sc.getName() + " — Plan : " + r.getName(), img));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!pages.isEmpty()) maps.put(sc.getId(), pages);
|
||||
}
|
||||
return maps;
|
||||
}
|
||||
|
||||
static String roomMapAnchor(Long sceneId, String roomId) {
|
||||
return "map-room-" + sceneId + "-" + (roomId == null ? "x" : roomId.replaceAll("[^A-Za-z0-9_-]", ""));
|
||||
}
|
||||
|
||||
/**
|
||||
* Partie « Cartes » : une carte par page paysage (page nommee {@code landscape}), titre
|
||||
* en tete, image la plus grande possible sans deformation.
|
||||
*/
|
||||
static void mapsPart(PdfExportService.Ctx ctx, Map<Long, List<MapPage>> maps) {
|
||||
if (maps.isEmpty()) return;
|
||||
StringBuilder b = ctx.body;
|
||||
PdfExportOptions.PageFormat format = ctx.opt.format();
|
||||
// Page paysage : largeur = hauteur du format portrait. Marges 1 cm, ~1,6 cm pour le titre.
|
||||
double pageW = format.landscapeWidthCm() - 2.0;
|
||||
double pageH = format.widthCm - 2.0 - 1.6;
|
||||
StringBuilder bms = new StringBuilder();
|
||||
boolean first = true;
|
||||
for (List<MapPage> pages : maps.values()) {
|
||||
for (MapPage p : pages) {
|
||||
b.append("<div class=\"map-page\"");
|
||||
if (first) b.append(" id=\"part-maps\"");
|
||||
b.append("><div class=\"map-title\" id=\"").append(p.anchor()).append("\">")
|
||||
.append(esc(p.title())).append("</div>");
|
||||
double w = Math.min(pageW, pageH * p.image().w() / p.image().h());
|
||||
b.append("<img style=\"width:").append(cm(w)).append("\" src=\"").append(p.image().uri()).append("\"/>");
|
||||
b.append(DIV_CLOSE);
|
||||
bms.append(bookmark(p.title(), p.anchor(), ""));
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
ctx.addToc(0, "Cartes", "part-maps");
|
||||
ctx.bookmarks.append(bookmark("Cartes", "part-maps", bms.toString()));
|
||||
}
|
||||
|
||||
// ====================================================================== Annexes MJ
|
||||
|
||||
/** Revelations et indices : chaque scene REVELATION, et les scenes qui y menent. */
|
||||
static void revelations(StringBuilder b, Structure st) {
|
||||
List<SceneJpaEntity> scenes = scenesInOrder(st);
|
||||
List<SceneJpaEntity> revelations = scenes.stream()
|
||||
.filter(s -> s.getType() == SceneType.REVELATION).toList();
|
||||
if (revelations.isEmpty()) return;
|
||||
|
||||
b.append("<h2 class=\"section-head\" id=\"annex-revelations\">Révélations et indices</h2>");
|
||||
b.append("<p class=\"prose annex-intro\">Pour chaque révélation, les scènes qui permettent de la "
|
||||
+ "découvrir. Visez au moins trois chemins : les joueurs en manqueront toujours un.</p>");
|
||||
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Révélation</th>"
|
||||
+ "<th>Y mènent</th></tr></thead><tbody>");
|
||||
int row = 0;
|
||||
for (SceneJpaEntity rev : revelations) {
|
||||
String anchor = "scene-" + rev.getId();
|
||||
b.append(trTag(row++)).append(TD_OPEN).append(xref(anchor, rev.getName())).append(' ')
|
||||
.append(pageRef(anchor)).append(TD_CLOSE).append(TD_OPEN);
|
||||
List<String> sources = incoming(rev, scenes);
|
||||
if (sources.isEmpty()) {
|
||||
b.append("<span class=\"annex-warn\">Aucune scène n'y mène.</span>");
|
||||
} else {
|
||||
b.append("<ul class=\"annex-list\">");
|
||||
for (String s : sources) b.append("<li>").append(s).append("</li>");
|
||||
b.append("</ul>");
|
||||
}
|
||||
b.append(TD_TR_CLOSE);
|
||||
}
|
||||
b.append(TBODY_TABLE_CLOSE);
|
||||
}
|
||||
|
||||
/** Scenes (du meme chapitre) qui ont un lien vers {@code target}, en HTML avec renvoi. */
|
||||
private static List<String> incoming(SceneJpaEntity target, List<SceneJpaEntity> scenes) {
|
||||
String targetId = String.valueOf(target.getId());
|
||||
List<String> out = new ArrayList<>();
|
||||
for (SceneJpaEntity s : scenes) {
|
||||
if (s.getBranches() == null || Objects.equals(s.getId(), target.getId())) continue;
|
||||
for (SceneBranch br : s.getBranches()) {
|
||||
if (!targetId.equals(br.targetSceneId())) continue;
|
||||
String anchor = "scene-" + s.getId();
|
||||
StringBuilder line = new StringBuilder(xref(anchor, s.getName())).append(' ').append(pageRef(anchor));
|
||||
if (br.kind() == LinkType.CLUE) line.append(" <span class=\"annex-kind\">indice</span>");
|
||||
else if (br.kind() == LinkType.LEAD) line.append(" <span class=\"annex-kind\">piste</span>");
|
||||
if (notBlank(br.label())) line.append(" — ").append(esc(br.label().trim()));
|
||||
out.add(line.toString());
|
||||
break; // une ligne par scene source
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Index alphabetique : nom (renvoi), dossier, niveau eventuel, apparitions eventuelles, page. */
|
||||
static void index(StringBuilder b, String anchorId, String title, List<IndexRow> rows,
|
||||
Map<String, List<String>> appearances) {
|
||||
if (rows.isEmpty()) return;
|
||||
List<IndexRow> sorted = new ArrayList<>(rows);
|
||||
sorted.sort(Comparator.comparing(r -> r.name() == null ? "" : r.name().toLowerCase(Locale.ROOT)));
|
||||
boolean withLevel = sorted.stream().anyMatch(r -> notBlank(r.level()));
|
||||
boolean withAppearances = appearances != null && !appearances.isEmpty();
|
||||
|
||||
b.append("<h2 class=\"section-head\" id=\"").append(anchorId).append("\">").append(esc(title)).append("</h2>");
|
||||
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Nom</th><th>Dossier</th>");
|
||||
if (withLevel) b.append("<th>Niv.</th>");
|
||||
if (withAppearances) b.append("<th>Apparaît dans</th>");
|
||||
b.append("<th class=\"page-col\">Page</th></tr></thead><tbody>");
|
||||
int row = 0;
|
||||
for (IndexRow r : sorted) {
|
||||
b.append(trTag(row++)).append(TD_OPEN).append(xref(r.anchor(), r.name())).append(TD_CLOSE)
|
||||
.append(TD_OPEN).append(esc(notBlank(r.folder()) ? r.folder().replace("/", " / ") : "—")).append(TD_CLOSE);
|
||||
if (withLevel) b.append(TD_OPEN).append(esc(notBlank(r.level()) ? r.level() : "—")).append(TD_CLOSE);
|
||||
if (withAppearances) {
|
||||
List<String> where = appearances.getOrDefault(r.anchor(), List.of());
|
||||
b.append(TD_OPEN).append(where.isEmpty() ? "—" : String.join(", ", where)).append(TD_CLOSE);
|
||||
}
|
||||
b.append("<td class=\"page-col\">").append(pageRef(r.anchor())).append(TD_TR_CLOSE);
|
||||
}
|
||||
b.append(TBODY_TABLE_CLOSE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ou apparait chaque adversaire : ancre de sa fiche ({@code enemy-<id>}) -> scenes
|
||||
* (renvois) qui le citent, dans la scene elle-meme ou dans l'une de ses pieces.
|
||||
*/
|
||||
static Map<String, List<String>> enemyAppearances(Structure st) {
|
||||
Map<String, Set<Long>> sceneIdsByEnemy = new LinkedHashMap<>();
|
||||
Map<Long, SceneJpaEntity> byId = new LinkedHashMap<>();
|
||||
for (SceneJpaEntity sc : scenesInOrder(st)) {
|
||||
byId.put(sc.getId(), sc);
|
||||
List<String> ids = new ArrayList<>();
|
||||
if (sc.getEnemyIds() != null) ids.addAll(sc.getEnemyIds());
|
||||
if (sc.getRooms() != null) {
|
||||
for (Room r : sc.getRooms()) if (r.getEnemyIds() != null) ids.addAll(r.getEnemyIds());
|
||||
}
|
||||
for (String id : ids) {
|
||||
if (notBlank(id)) sceneIdsByEnemy.computeIfAbsent("enemy-" + id.trim(), k -> new LinkedHashSet<>()).add(sc.getId());
|
||||
}
|
||||
}
|
||||
Map<String, List<String>> out = new LinkedHashMap<>();
|
||||
sceneIdsByEnemy.forEach((enemyAnchor, sceneIds) -> {
|
||||
List<String> refs = new ArrayList<>();
|
||||
for (Long sid : sceneIds) {
|
||||
String anchor = "scene-" + sid;
|
||||
refs.add(xref(anchor, byId.get(sid).getName()) + " " + pageRef(anchor));
|
||||
}
|
||||
out.put(enemyAnchor, refs);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Toutes les scenes dans l'ordre du livret (arcs, chapitres, scenes). */
|
||||
private static List<SceneJpaEntity> scenesInOrder(Structure st) {
|
||||
List<SceneJpaEntity> out = new ArrayList<>();
|
||||
for (ArcJpaEntity arc : st.arcs) {
|
||||
for (ChapterJpaEntity ch : st.chaptersByArc.getOrDefault(arc.getId(), List.of())) {
|
||||
out.addAll(st.scenesByChapter.getOrDefault(ch.getId(), List.of()));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.loremind.infrastructure.transfer.pdf;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Options de l'export PDF choisies par l'utilisateur.
|
||||
*
|
||||
* @param gmContent vrai = version MJ complète ; faux = version joueurs (aucun secret :
|
||||
* notes MJ, conséquences, sorties, combats, contexte caché…)
|
||||
* @param format format de page
|
||||
* @param printFriendly vrai = sans aplats de couleur (économie d'encre)
|
||||
* @param sections parties incluses
|
||||
* @param loreScope pages de lore incluses (si la partie Lore est demandée)
|
||||
*/
|
||||
public record PdfExportOptions(boolean gmContent, PageFormat format, boolean printFriendly,
|
||||
Set<Section> sections, LoreScope loreScope) {
|
||||
|
||||
/**
|
||||
* Parties du livret qu'on peut inclure ou non. APPENDIX = annexes MJ (revelations et
|
||||
* indices, index PNJ et adversaires ; jamais en version joueurs) ; MAPS = cartes en
|
||||
* pleine page paysage (les scenes y renvoient au lieu de les afficher en petit).
|
||||
*/
|
||||
public enum Section { NARRATIVE, QUESTS, NPCS, ENEMIES, TABLES, LORE, APPENDIX, MAPS }
|
||||
|
||||
/** Pages de lore exportées : toutes, ou seulement celles liées au contenu de la campagne. */
|
||||
public enum LoreScope { ALL, LINKED }
|
||||
|
||||
/**
|
||||
* Format de page : dimensions (cm), marges (haut, côtés, bas) et taille du texte courant.
|
||||
* A5 : marges et corps réduits pour garder une ligne lisible sur une page étroite.
|
||||
*/
|
||||
public enum PageFormat {
|
||||
A4("A4", 21.0, 29.7, 2.2, 1.7, 2.0, 10.0, 12.5),
|
||||
A5("A5", 14.8, 21.0, 1.7, 1.3, 1.6, 9.0, 7.0),
|
||||
LETTER("letter", 21.59, 27.94, 2.2, 1.8, 2.0, 10.0, 12.0);
|
||||
|
||||
final String cssSize;
|
||||
final double widthCm;
|
||||
final double heightCm;
|
||||
final double marginTopCm;
|
||||
final double marginSideCm;
|
||||
final double marginBottomCm;
|
||||
final double bodyPt;
|
||||
/** Hauteur max de l'illustration de couverture : la couverture tient sur une page. */
|
||||
final double coverArtMaxCm;
|
||||
|
||||
PageFormat(String cssSize, double widthCm, double heightCm, double marginTopCm, double marginSideCm,
|
||||
double marginBottomCm, double bodyPt, double coverArtMaxCm) {
|
||||
this.cssSize = cssSize;
|
||||
this.widthCm = widthCm;
|
||||
this.heightCm = heightCm;
|
||||
this.marginTopCm = marginTopCm;
|
||||
this.marginSideCm = marginSideCm;
|
||||
this.marginBottomCm = marginBottomCm;
|
||||
this.bodyPt = bodyPt;
|
||||
this.coverArtMaxCm = coverArtMaxCm;
|
||||
}
|
||||
|
||||
/** Largeur d'une page tournée en paysage (= hauteur en portrait). */
|
||||
double landscapeWidthCm() {
|
||||
return heightCm;
|
||||
}
|
||||
|
||||
/** Largeur utile (page moins les deux marges latérales). */
|
||||
double contentWidthCm() {
|
||||
return widthCm - 2 * marginSideCm;
|
||||
}
|
||||
}
|
||||
|
||||
public PdfExportOptions {
|
||||
format = format != null ? format : PageFormat.A4;
|
||||
sections = sections == null || sections.isEmpty()
|
||||
? EnumSet.allOf(Section.class) : EnumSet.copyOf(sections);
|
||||
loreScope = loreScope != null ? loreScope : LoreScope.ALL;
|
||||
}
|
||||
|
||||
/** Livret MJ complet en A4 : le comportement historique de l'export. */
|
||||
public static PdfExportOptions defaults() {
|
||||
return new PdfExportOptions(true, PageFormat.A4, false, EnumSet.allOf(Section.class), LoreScope.ALL);
|
||||
}
|
||||
|
||||
public boolean includes(Section section) {
|
||||
return sections.contains(section);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit les options depuis les paramètres de requête (valeurs inconnues ignorées,
|
||||
* absentes = défaut). {@code sections} : liste séparée par des virgules.
|
||||
*/
|
||||
public static PdfExportOptions parse(String edition, String format, Boolean print,
|
||||
String sections, String lore) {
|
||||
boolean gm = !"player".equalsIgnoreCase(trim(edition));
|
||||
PageFormat pf = enumOrNull(PageFormat.class, format);
|
||||
LoreScope scope = enumOrNull(LoreScope.class, lore);
|
||||
Set<Section> set = EnumSet.noneOf(Section.class);
|
||||
if (sections != null) {
|
||||
for (String s : sections.split(",")) {
|
||||
Section sec = enumOrNull(Section.class, s);
|
||||
if (sec != null) set.add(sec);
|
||||
}
|
||||
}
|
||||
return new PdfExportOptions(gm, pf, Boolean.TRUE.equals(print), set, scope);
|
||||
}
|
||||
|
||||
private static String trim(String s) {
|
||||
return s == null ? "" : s.trim();
|
||||
}
|
||||
|
||||
private static <E extends Enum<E>> E enumOrNull(Class<E> type, String raw) {
|
||||
String v = trim(raw).toUpperCase(Locale.ROOT);
|
||||
if (v.isEmpty()) return null;
|
||||
try {
|
||||
return Enum.valueOf(type, v);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+592
-160
File diff suppressed because it is too large
Load Diff
@@ -88,7 +88,8 @@ final class PdfHtml {
|
||||
*/
|
||||
static void box(StringBuilder b, String cssClass, String label, String value) {
|
||||
if (!notBlank(value)) return;
|
||||
b.append("<div class=\"box ").append(cssClass).append("\">");
|
||||
boolean longText = isLongBox(value);
|
||||
b.append("<div class=\"box ").append(cssClass).append(longText ? " flow" : "").append("\">");
|
||||
b.append("<div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE);
|
||||
List<TextBlock> blocks = parseBlocks(value);
|
||||
for (int i = 0; i < blocks.size(); i++) {
|
||||
@@ -106,6 +107,11 @@ final class PdfHtml {
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
|
||||
/** Borne conservative des encadres qui peuvent rester entiers dans une colonne A4. */
|
||||
static boolean isLongBox(String text) {
|
||||
return text.length() > 900 || text.lines().count() > 12;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bloc "libelle en tete de ligne + valeur" si la valeur est non vide. Le libelle est
|
||||
* rendu EN LIGNE devant le premier paragraphe (style stat-block : compact et balayable),
|
||||
@@ -139,6 +145,71 @@ final class PdfHtml {
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
|
||||
// ----- Renvois internes (« voir p. 12 ») -----
|
||||
|
||||
private static final java.util.regex.Pattern ID_ATTR = java.util.regex.Pattern.compile(" id=\"([^\"]+)\"");
|
||||
private static final java.util.regex.Pattern XREF = java.util.regex.Pattern.compile(
|
||||
"<a class=\"xref\" href=\"#([^\"]+)\">(.*?)</a>");
|
||||
private static final java.util.regex.Pattern PREF = java.util.regex.Pattern.compile(
|
||||
"<a class=\"pref\" href=\"#([^\"]+)\"></a>");
|
||||
|
||||
/** Nom cliquable vers une ancre du livret (retire par {@link #resolveRefs} si l'ancre manque). */
|
||||
static String xref(String anchor, String text) {
|
||||
return "<a class=\"xref\" href=\"#" + anchor + "\">" + esc(text) + "</a>";
|
||||
}
|
||||
|
||||
/** Numero de page de l'ancre, rendu « (p. 12) » par target-counter (cf. export.css). */
|
||||
static String pageRef(String anchor) {
|
||||
return "<a class=\"pref\" href=\"#" + anchor + "\"></a>";
|
||||
}
|
||||
|
||||
/**
|
||||
* Neutralise les renvois vers des ancres absentes du document (partie non exportee,
|
||||
* scene d'une quete exclue...) : le nom reste en texte simple, le numero de page disparait.
|
||||
* openhtmltopdf ne sait pas resoudre target-counter vers une ancre inexistante.
|
||||
*/
|
||||
static String resolveRefs(String html) {
|
||||
java.util.Set<String> ids = new java.util.HashSet<>();
|
||||
java.util.regex.Matcher m = ID_ATTR.matcher(html);
|
||||
while (m.find()) ids.add(m.group(1));
|
||||
String out = XREF.matcher(html).replaceAll(r -> ids.contains(r.group(1))
|
||||
? java.util.regex.Matcher.quoteReplacement(r.group())
|
||||
: java.util.regex.Matcher.quoteReplacement(r.group(2)));
|
||||
return PREF.matcher(out).replaceAll(r -> ids.contains(r.group(1))
|
||||
? java.util.regex.Matcher.quoteReplacement(r.group()) : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Champ « libelle + elements » dont les elements sont DEJA du HTML (renvois, liens) :
|
||||
* un seul element en ligne apres le libelle, plusieurs en liste a puces.
|
||||
*/
|
||||
static void blockHtml(StringBuilder b, String label, List<String> htmlItems) {
|
||||
if (htmlItems == null || htmlItems.isEmpty()) return;
|
||||
b.append("<div class=\"field\"><span class=\"field-label\">").append(esc(label)).append(SPAN_CLOSE);
|
||||
if (htmlItems.size() == 1) {
|
||||
b.append(htmlItems.get(0));
|
||||
} else {
|
||||
b.append("<ul>");
|
||||
for (String item : htmlItems) b.append("<li>").append(item).append("</li>");
|
||||
b.append("</ul>");
|
||||
}
|
||||
b.append(DIV_CLOSE);
|
||||
}
|
||||
|
||||
/** Texte courant sans libelle : paragraphes et listes a puces (« - ... »). */
|
||||
static void prose(StringBuilder b, String value) {
|
||||
if (!notBlank(value)) return;
|
||||
for (TextBlock t : parseBlocks(value)) {
|
||||
if (t.list()) {
|
||||
b.append("<ul class=\"prose-list\">");
|
||||
for (String line : t.lines()) b.append("<li>").append(esc(line)).append("</li>");
|
||||
b.append("</ul>");
|
||||
} else {
|
||||
b.append("<p class=\"prose\">").append(paragraphHtml(t)).append("</p>");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String paragraphHtml(TextBlock t) {
|
||||
StringBuilder p = new StringBuilder();
|
||||
for (int i = 0; i < t.lines().size(); i++) {
|
||||
|
||||
@@ -65,6 +65,11 @@ class PdfImageEncoder {
|
||||
|
||||
/** Battlemap (fichier stocke) re-encodee, seulement si c'est une image (pas une video). */
|
||||
PdfImage fileImage(String fileId) {
|
||||
return fileImage(fileId, ILLUSTRATION_MAX);
|
||||
}
|
||||
|
||||
/** Idem, avec une cote max choisie (cartes pleine page de l'annexe : plus fines). */
|
||||
PdfImage fileImage(String fileId, int maxDim) {
|
||||
if (fileId == null || fileId.isBlank()) return null;
|
||||
StoredFileJpaEntity e;
|
||||
try {
|
||||
@@ -75,7 +80,7 @@ class PdfImageEncoder {
|
||||
if (e == null) return null;
|
||||
String ct = e.getContentType();
|
||||
if (ct == null || !ct.startsWith("image/")) return null; // mp4/webm -> ignore
|
||||
return encode(fileStorage.download(e.getStorageKey()), ILLUSTRATION_MAX, fileId);
|
||||
return encode(fileStorage.download(e.getStorageKey()), maxDim, fileId);
|
||||
}
|
||||
|
||||
/** Lit un flux image, le redimensionne (max maxDim) et le re-encode en data-URI JPEG. */
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.loremind.infrastructure.transfer.pdf;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||
import org.apache.pdfbox.util.Matrix;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.io.IOException;
|
||||
|
||||
/** Motifs vectoriels originaux, confines aux 49 points de marge inferieure des pages A4.
|
||||
* Les dessiner apres la pagination conserve les renvois, le texte et la mise en page. */
|
||||
final class PdfPageOrnaments {
|
||||
private static final Color INK = new Color(0x34594f);
|
||||
private static final Color SAGE = new Color(0xa8bbae);
|
||||
private static final Color PALE = new Color(0xe6ece3);
|
||||
private static final Color GOLD = new Color(0xb5a278);
|
||||
private static final Color PRINT = new Color(0x999999);
|
||||
|
||||
private PdfPageOrnaments() {}
|
||||
|
||||
static void draw(PDDocument document, PdfExportOptions options) throws IOException {
|
||||
if (options.format() != PdfExportOptions.PageFormat.A4) return;
|
||||
// Pas de decoration sur la couverture, ni sur les annexes cartographiques paysage.
|
||||
for (int i = 1; i < document.getNumberOfPages(); i++) {
|
||||
var page = document.getPage(i);
|
||||
var bounds = page.getMediaBox();
|
||||
if (bounds.getWidth() > bounds.getHeight()) continue;
|
||||
try (var canvas = new PDPageContentStream(document, page,
|
||||
PDPageContentStream.AppendMode.PREPEND, true, true)) {
|
||||
canvas.saveGraphicsState();
|
||||
canvas.addRect(0, 0, bounds.getWidth(), 49);
|
||||
canvas.clip();
|
||||
// Le coin exterieur est plus ample ; alternance pour les pages en vis-a-vis.
|
||||
corner(canvas, 0, false, i % 2 == 1 ? 1f : .72f, options.printFriendly());
|
||||
corner(canvas, bounds.getWidth(), true, i % 2 == 0 ? 1f : .72f, options.printFriendly());
|
||||
folio(canvas, bounds.getWidth() / 2, options.printFriendly());
|
||||
canvas.restoreGraphicsState();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void corner(PDPageContentStream c, float x, boolean mirror, float scale,
|
||||
boolean print) throws IOException {
|
||||
c.saveGraphicsState();
|
||||
c.transform(new Matrix(mirror ? -scale : scale, 0, 0, scale, x, 0));
|
||||
if (!print) {
|
||||
c.setNonStrokingColor(PALE);
|
||||
c.moveTo(0, 49);
|
||||
c.curveTo(35, 18, 94, 9, 184, 0);
|
||||
c.lineTo(0, 0);
|
||||
c.closePath();
|
||||
c.fill();
|
||||
c.setNonStrokingColor(SAGE);
|
||||
c.moveTo(0, 35);
|
||||
c.curveTo(40, 8, 81, 8, 150, 0);
|
||||
c.lineTo(0, 0);
|
||||
c.closePath();
|
||||
c.fill();
|
||||
c.setNonStrokingColor(INK);
|
||||
c.moveTo(0, 21);
|
||||
c.curveTo(22, 9, 63, 3, 110, 0);
|
||||
c.lineTo(0, 0);
|
||||
c.closePath();
|
||||
c.fill();
|
||||
c.setNonStrokingColor(SAGE);
|
||||
for (int col = 0; col < 17; col++) {
|
||||
float dx = 14 + col * 8;
|
||||
for (int row = 0; row < 4; row++) {
|
||||
float dy = 43 - col * 1.6f - row * 6;
|
||||
if (dy > 13) dot(c, dx + (row % 2) * 3, dy, .35f + row * .12f);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.setStrokingColor(print ? PRINT : GOLD);
|
||||
c.setLineWidth(.45f);
|
||||
c.moveTo(0, 43);
|
||||
c.curveTo(32, 16, 85, 7, 170, 3);
|
||||
c.stroke();
|
||||
c.restoreGraphicsState();
|
||||
}
|
||||
|
||||
private static void folio(PDPageContentStream c, float center, boolean print) throws IOException {
|
||||
c.setStrokingColor(print ? PRINT : GOLD);
|
||||
c.setNonStrokingColor(print ? PRINT : GOLD);
|
||||
c.setLineWidth(.4f);
|
||||
for (int side : new int[]{-1, 1}) {
|
||||
c.moveTo(center + side * 18, 27);
|
||||
c.lineTo(center + side * 37, 27);
|
||||
c.stroke();
|
||||
float x = center + side * 43;
|
||||
c.moveTo(x, 29);
|
||||
c.lineTo(x + 2, 27);
|
||||
c.lineTo(x, 25);
|
||||
c.lineTo(x - 2, 27);
|
||||
c.closePath();
|
||||
if (print) c.stroke(); else c.fill();
|
||||
}
|
||||
}
|
||||
|
||||
private static void dot(PDPageContentStream c, float x, float y, float r) throws IOException {
|
||||
float k = r * .552285f;
|
||||
c.moveTo(x + r, y);
|
||||
c.curveTo(x + r, y + k, x + k, y + r, x, y + r);
|
||||
c.curveTo(x - k, y + r, x - r, y + k, x - r, y);
|
||||
c.curveTo(x - r, y - k, x - k, y - r, x, y - r);
|
||||
c.curveTo(x + k, y - r, x + r, y - k, x + r, y);
|
||||
c.closePath();
|
||||
c.fill();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.CampaignContentSearchService;
|
||||
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/search-content")
|
||||
public class CampaignContentSearchController {
|
||||
private final CampaignContentSearchService service;
|
||||
|
||||
public CampaignContentSearchController(CampaignContentSearchService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<CampaignContentHit> search(@RequestParam("q") String query) {
|
||||
return service.search(query);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.CampaignService;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.CampaignDTO;
|
||||
import com.loremind.infrastructure.web.mapper.CampaignMapper;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -72,6 +73,18 @@ public class CampaignController {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/** Fiche « Publication » (couverture, page technique, crédits) utilisée par l'export PDF. */
|
||||
@GetMapping("/{id}/publication")
|
||||
public ResponseEntity<CampaignPublication> getPublication(@PathVariable String id) {
|
||||
return ResponseEntity.ok(campaignService.getPublication(id));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/publication")
|
||||
public ResponseEntity<CampaignPublication> updatePublication(@PathVariable String id,
|
||||
@RequestBody CampaignPublication body) {
|
||||
return ResponseEntity.ok(campaignService.updatePublication(id, body));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<CampaignDTO> updateCampaign(@PathVariable String id, @RequestBody CampaignDTO campaignDTO) {
|
||||
Campaign updatedCampaign = campaignService.updateCampaign(
|
||||
|
||||
+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));
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,8 @@ public class NpcController {
|
||||
dto.getCampaignId(),
|
||||
dto.getRelatedPageIds(),
|
||||
dto.getFolder(),
|
||||
order
|
||||
order,
|
||||
dto.getStory()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+15
-3
@@ -1,5 +1,6 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions;
|
||||
import com.loremind.infrastructure.transfer.pdf.PdfExportService;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -8,6 +9,7 @@ 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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
@@ -18,6 +20,10 @@ import java.util.NoSuchElementException;
|
||||
* <p>
|
||||
* {@code GET /api/campaigns/{campaignId}/pdf-export} -> application/pdf (structure
|
||||
* narrative + PNJ/ennemis + lore + battlemaps).
|
||||
* <p>
|
||||
* Options (toutes facultatives, defaut = livret MJ complet en A4) :
|
||||
* {@code edition=gm|player}, {@code format=A4|A5|LETTER}, {@code print=true} (sans aplats),
|
||||
* {@code sections=NARRATIVE,QUESTS,NPCS,ENEMIES,TABLES,LORE}, {@code lore=ALL|LINKED}.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/pdf-export")
|
||||
@@ -30,17 +36,23 @@ public class PdfExportController {
|
||||
}
|
||||
|
||||
@GetMapping(produces = MediaType.APPLICATION_PDF_VALUE)
|
||||
public ResponseEntity<byte[]> export(@PathVariable String campaignId) {
|
||||
public ResponseEntity<byte[]> export(@PathVariable String campaignId,
|
||||
@RequestParam(required = false) String edition,
|
||||
@RequestParam(required = false) String format,
|
||||
@RequestParam(required = false) Boolean print,
|
||||
@RequestParam(required = false) String sections,
|
||||
@RequestParam(required = false) String lore) {
|
||||
PdfExportOptions options = PdfExportOptions.parse(edition, format, print, sections, lore);
|
||||
byte[] pdf;
|
||||
String name;
|
||||
try {
|
||||
name = pdfExportService.campaignName(campaignId);
|
||||
pdf = pdfExportService.export(campaignId);
|
||||
pdf = pdfExportService.export(campaignId, options);
|
||||
} catch (NoSuchElementException e) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
}
|
||||
|
||||
String filename = slug(name) + ".pdf";
|
||||
String filename = slug(name) + (options.gmContent() ? "" : "_joueurs") + ".pdf";
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||
.contentType(MediaType.APPLICATION_PDF)
|
||||
|
||||
+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));
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ public class ArcDTO {
|
||||
private String gmNotes;
|
||||
private String rewards;
|
||||
private String resolution;
|
||||
private String hiddenTruth;
|
||||
private String hooks;
|
||||
|
||||
/** IDs des pages du Lore liées à cet arc (weak cross-context references). */
|
||||
private List<String> relatedPageIds = new ArrayList<>();
|
||||
|
||||
@@ -24,5 +24,6 @@ public class NpcDTO {
|
||||
/** IDs de Pages de Lore référencées par ce PNJ (référence faible cross-context). */
|
||||
private List<String> relatedPageIds = new ArrayList<>();
|
||||
private String folder;
|
||||
private com.loremind.domain.campaigncontext.bestiary.NpcStory story;
|
||||
private int order;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ public class SceneDTO {
|
||||
private String gmSecretNotes;
|
||||
private String choicesConsequences;
|
||||
private String combatDifficulty;
|
||||
private String tactics;
|
||||
private String purpose;
|
||||
private String enemies;
|
||||
|
||||
/** IDs des fiches du bestiaire engagées dans la rencontre (weak refs). */
|
||||
|
||||
@@ -32,6 +32,8 @@ public class ArcMapper {
|
||||
dto.setGmNotes(arc.getGmNotes());
|
||||
dto.setRewards(arc.getRewards());
|
||||
dto.setResolution(arc.getResolution());
|
||||
dto.setHiddenTruth(arc.getHiddenTruth());
|
||||
dto.setHooks(arc.getHooks());
|
||||
dto.setRelatedPageIds(copyList(arc.getRelatedPageIds()));
|
||||
dto.setIllustrationImageIds(copyList(arc.getIllustrationImageIds()));
|
||||
return dto;
|
||||
@@ -55,6 +57,8 @@ public class ArcMapper {
|
||||
.gmNotes(dto.getGmNotes())
|
||||
.rewards(dto.getRewards())
|
||||
.resolution(dto.getResolution())
|
||||
.hiddenTruth(dto.getHiddenTruth())
|
||||
.hooks(dto.getHooks())
|
||||
.relatedPageIds(copyList(dto.getRelatedPageIds()))
|
||||
.illustrationImageIds(copyList(dto.getIllustrationImageIds()))
|
||||
.build();
|
||||
|
||||
@@ -23,6 +23,7 @@ public class NpcMapper {
|
||||
dto.setCampaignId(n.getCampaignId());
|
||||
dto.setRelatedPageIds(n.getRelatedPageIds() != null ? new ArrayList<>(n.getRelatedPageIds()) : new ArrayList<>());
|
||||
dto.setFolder(n.getFolder());
|
||||
dto.setStory(n.getStory());
|
||||
dto.setOrder(n.getOrder());
|
||||
return dto;
|
||||
}
|
||||
@@ -40,6 +41,7 @@ public class NpcMapper {
|
||||
.campaignId(dto.getCampaignId())
|
||||
.relatedPageIds(dto.getRelatedPageIds() != null ? new ArrayList<>(dto.getRelatedPageIds()) : new ArrayList<>())
|
||||
.folder(dto.getFolder())
|
||||
.story(dto.getStory())
|
||||
.order(dto.getOrder())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ public class SceneMapper {
|
||||
dto.setGmSecretNotes(scene.getGmSecretNotes());
|
||||
dto.setChoicesConsequences(scene.getChoicesConsequences());
|
||||
dto.setCombatDifficulty(scene.getCombatDifficulty());
|
||||
dto.setTactics(scene.getTactics());
|
||||
dto.setPurpose(scene.getPurpose());
|
||||
dto.setEnemies(scene.getEnemies());
|
||||
dto.setEnemyIds(scene.getEnemyIds() != null
|
||||
? new ArrayList<>(scene.getEnemyIds())
|
||||
@@ -81,6 +83,8 @@ public class SceneMapper {
|
||||
.gmSecretNotes(dto.getGmSecretNotes())
|
||||
.choicesConsequences(dto.getChoicesConsequences())
|
||||
.combatDifficulty(dto.getCombatDifficulty())
|
||||
.tactics(dto.getTactics())
|
||||
.purpose(dto.getPurpose())
|
||||
.enemies(dto.getEnemies())
|
||||
.enemyIds(dto.getEnemyIds() != null
|
||||
? new ArrayList<>(dto.getEnemyIds())
|
||||
|
||||
@@ -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);
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Fiche « Publication » d'une campagne (module à vendre ou à partager) : sous-titre,
|
||||
-- auteur, page technique, argument, contexte MJ, accroches, crédits, licence,
|
||||
-- image de couverture… Stockée en JSON (texte libre, évolutif) ; NULL = jamais renseignée.
|
||||
ALTER TABLE campaigns ADD COLUMN publication TEXT;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Champs d'écriture (mentor) :
|
||||
-- scène : tactique et moral des adversaires, utilité (ce qu'on perd si on la coupe) ;
|
||||
-- arc : histoire cachée, accroches ;
|
||||
-- PNJ : fiche « rôle dans l'histoire » (rôle, motivation, ce qu'il sait, signe distinctif) en JSON.
|
||||
ALTER TABLE scenes ADD COLUMN tactics TEXT;
|
||||
ALTER TABLE scenes ADD COLUMN purpose TEXT;
|
||||
ALTER TABLE arcs ADD COLUMN hidden_truth TEXT;
|
||||
ALTER TABLE arcs ADD COLUMN hooks TEXT;
|
||||
ALTER TABLE npcs ADD COLUMN story TEXT;
|
||||
@@ -0,0 +1,16 @@
|
||||
/* Format A5 : surcharges ajoutees apres export.css (page etroite, couverture sur une seule page).
|
||||
ATTENTION : ce CSS est injecte tel quel dans le document XML — ni esperluette ni chevron ici. */
|
||||
.cover { padding-top: 3.2cm; }
|
||||
.cover.has-art { padding-top: .3cm; }
|
||||
.cover-kicker { font-size: 8.5pt; letter-spacing: .25em; }
|
||||
.cover-title { font-size: 21pt; margin-top: .3cm; }
|
||||
.cover-subtitle { font-size: 11pt; margin-top: .2cm; }
|
||||
.cover-rule { margin: .35cm auto; }
|
||||
.cover-art { margin: .1cm 0 .35cm; }
|
||||
.cover-edition { margin-top: .25cm; }
|
||||
.cover-author { margin-top: .5cm; font-size: 11pt; }
|
||||
.cover-version { margin-top: .15cm; }
|
||||
h1.part, h1.toc-title { font-size: 16pt; }
|
||||
.arc-head { font-size: 12.5pt; }
|
||||
.chapter-head { font-size: 11.5pt; }
|
||||
.scene { margin-left: .15cm; }
|
||||
@@ -0,0 +1,93 @@
|
||||
/* Edition A4 : narration en colonnes, palette encre et sauge.
|
||||
CSS pagine OpenHTMLtoPDF ; les tableaux detailles et cartes restent pleine largeur. */
|
||||
@page {
|
||||
@top-center { content: '__HEADER__'; font-family: 'DejaVu Sans', sans-serif; font-size: 7pt;
|
||||
color: #34594f; letter-spacing: .12em; border-bottom: .5pt solid #b3bfb4; padding-bottom: 6pt; }
|
||||
@bottom-center { content: counter(page); font-size: 9pt; color: #34594f; font-family: 'DejaVu Serif', serif; }
|
||||
}
|
||||
@page:first { @top-center { content: none; border: 0; } }
|
||||
body { margin: 0; color: #292c29; line-height: 1.42; word-wrap: break-word; }
|
||||
.editorial-flow { column-count: 2; column-gap: .8cm; }
|
||||
.editorial-flow p, .editorial-flow .field, .editorial-flow .box { orphans: 3; widows: 3; }
|
||||
.editorial-flow .prose { text-align: left; }
|
||||
/* Un bloc en ligne est deplace entier par le moteur de colonnes. Les encadres longs
|
||||
restent fluides, sans fond ni bordure susceptibles de deborder sur la colonne suivante. */
|
||||
.editorial-flow .box, .editorial-flow .illus { display: inline-block; width: 100%; box-sizing: border-box; }
|
||||
.editorial-flow .box.flow { display: block; background: none; border: 0; padding: .1cm 0; }
|
||||
.editorial-flow .box.flow .box-label { border-top: 1pt solid #9a8351; padding-top: .12cm; }
|
||||
.editorial-flow .arc-head, .editorial-flow .chapter-head, .editorial-flow .scene-head,
|
||||
.editorial-flow .section-head { display: inline-block; width: 100%; box-sizing: border-box; }
|
||||
.cover { padding-top: 3cm; }
|
||||
.cover.has-art { padding-top: .3cm; }
|
||||
.cover-title { font-family: 'DejaVu Serif', serif; font-size: 32pt; line-height: 1.12;
|
||||
letter-spacing: -.03em; color: #193c34; }
|
||||
.cover-kicker { color: #456656; font-size: 9pt; letter-spacing: .18em; }
|
||||
.cover-subtitle { font-family: 'DejaVu Serif', serif; color: #545b50; font-style: italic; font-size: 13pt; }
|
||||
.cover-rule { width: 5cm; border-bottom: 1.5pt solid #9a8351; }
|
||||
.cover-art { margin: .35cm 0 .5cm; }
|
||||
.cover-art img { border: 0; }
|
||||
.cover-meta { color: #34594f; font-size: 9pt; }
|
||||
.cover-author { color: #193c34; margin-top: .6cm; }
|
||||
.cover-version { color: #67746a; }
|
||||
@page illustrated-cover { size: A4; margin: 0;
|
||||
@top-center { content: none; border: 0; }
|
||||
@bottom-center { content: none; }
|
||||
}
|
||||
.cover-illustrated { page: illustrated-cover; position: relative; width: 21cm; height: 29.65cm;
|
||||
padding: 0; margin: 0; overflow: hidden; background: #193c34; }
|
||||
.cover-background { position: absolute; }
|
||||
.cover-caption { position: absolute; bottom: 1.2cm; left: 1.3cm; right: 1.3cm;
|
||||
background: #193c34; padding: .7cm .7cm .6cm; }
|
||||
.cover-caption .cover-title { color: #fffdf4; }
|
||||
.cover-caption .cover-kicker, .cover-caption .cover-meta, .cover-caption .cover-version { color: #d4dfce; }
|
||||
.cover-caption .cover-subtitle, .cover-caption .cover-author { color: #fffdf4; }
|
||||
.cover-caption .cover-rule { border-color: #c9b47e; }
|
||||
.cover-caption .cover-edition { color: #e1ca8e; }
|
||||
.credits-title, .credits-subtitle { color: #34594f; }
|
||||
.legal { border-color: #b3bfb4; }
|
||||
h1.part, h1.toc-title { font-family: 'DejaVu Serif', serif; font-size: 25pt; line-height: 1.15;
|
||||
letter-spacing: -.02em; text-transform: none; color: #193c34; border-bottom: 1.5pt solid #9a8351;
|
||||
padding-bottom: .22cm; margin-bottom: .5cm; }
|
||||
.toc tr.lvl0 td { color: #193c34; border-bottom-color: #b3bfb4; }
|
||||
.toc td { border-bottom-color: #d4d9d0; }
|
||||
.arc { margin: 0 0 .4cm; }
|
||||
.arc-head { background: none; padding: .12cm 0 .18cm; border-radius: 0;
|
||||
border-top: 2pt solid #34594f; border-bottom: .5pt solid #9a8351;
|
||||
color: #193c34; font-family: 'DejaVu Serif', serif; font-size: 19pt; line-height: 1.18; }
|
||||
.chapter-head { background: none; border: 0; border-bottom: 1pt solid #b3bfb4;
|
||||
padding: 0 0 .12cm; font-family: 'DejaVu Serif', serif; font-size: 15pt; line-height: 1.2; color: #34594f; }
|
||||
.eyebrow, .eyebrow-light { color: #637767; font-size: 6.5pt; margin-bottom: .08cm; }
|
||||
.scene { border: 0; border-radius: 0; background: none; padding: 0; margin: .4cm 0 .3cm; }
|
||||
.scene-head { color: #193c34; font-size: 11pt; text-transform: uppercase; letter-spacing: .03em;
|
||||
border-bottom: .5pt solid #b3bfb4; padding-bottom: .08cm; }
|
||||
.scene-meta { color: #687365; font-size: 8.5pt; }
|
||||
.room { background: none; border: 0;
|
||||
padding: 0 0 0 .22cm; margin: .3cm 0; }
|
||||
.room-head { color: #695a36; border-left: 1pt solid #9a8351; padding-left: .18cm; }
|
||||
h2.section-head { font-family: 'DejaVu Serif', serif; font-size: 14pt; color: #34594f; border-bottom-color: #b3bfb4; }
|
||||
h3.folder { color: #456656; border-bottom-color: #b3bfb4; }
|
||||
.field { margin: .2cm 0; }
|
||||
.field-label { color: #34594f; font-size: 7.5pt; letter-spacing: .02em; }
|
||||
.box { padding: .25cm .3cm; margin: .25cm 0; border-radius: 0; }
|
||||
.box-label { letter-spacing: .06em; }
|
||||
.box ul { padding-left: .4cm; margin: .12cm 0; }
|
||||
.readaloud { background: #edf1e7; border: .75pt solid #456656; font-style: normal; color: #234438; }
|
||||
.readaloud .box-label { color: #34594f; }
|
||||
.secret { background: #f5f1e7; border: 0; border-left: 2pt solid #9a8351; }
|
||||
.secret .box-label { color: #79683e; }
|
||||
.combat { background: #f8eeea; border-left-color: #9b5547; }
|
||||
.card { background: #fafbf7; border-color: #c5cec1; border-radius: 0; }
|
||||
.persona-name { font-family: 'DejaVu Serif', serif; color: #193c34; font-size: 14pt; }
|
||||
.level, .illus .caption { color: #637767; }
|
||||
.illus { margin: .35cm 0; }
|
||||
.illus img { border: 0; border-radius: 0; }
|
||||
.illus .caption { font-size: 7pt; letter-spacing: .04em; }
|
||||
.tech-table { width: 100%; }
|
||||
.stats-table thead th, .stat-array th { background: #e7ede2; color: #34594f; border-color: #b3bfb4; }
|
||||
.stats-table tbody th { background: #f0f3eb; }
|
||||
.stats-table tr.alt td { background: #f0f3eb; }
|
||||
.stats-table td, .stats-table th, .stat-array td { border-color: #d4d9d0; }
|
||||
.stats-table .roll-col, a.xref { color: #34594f; }
|
||||
a.xref { border-bottom-color: #b3bfb4; }
|
||||
a.pref:after, .annex-kind { color: #637767; }
|
||||
.map-title { color: #193c34; }
|
||||
@@ -0,0 +1,14 @@
|
||||
/* Mode impression : surcharges ajoutees apres export.css. Aucun aplat de couleur (economie
|
||||
d'encre, rendu net en noir et blanc) ; les filets et bordures portent la hierarchie.
|
||||
ATTENTION : ce CSS est injecte tel quel dans le document XML — ni esperluette ni chevron ici. */
|
||||
.arc-head { background: none; color: #1f1c33; border-top: 2pt solid #2e2a4a; border-bottom: 2pt solid #2e2a4a;
|
||||
border-radius: 0; }
|
||||
.arc-head .eyebrow-light { color: #6d6787; }
|
||||
.chapter-head { background: none; border-left: 4pt solid #555; }
|
||||
.scene, .room, .card { background: none; }
|
||||
.readaloud { background: none; }
|
||||
.secret { background: none; border: 1pt dashed #777; }
|
||||
.combat { background: none; border-left: 3pt solid #555; }
|
||||
.warning { background: none; border-left: 3pt solid #555; }
|
||||
.stats-table thead th, .stats-table tbody th, .stat-array th { background: none; }
|
||||
.stats-table tr.alt td { background: none; }
|
||||
@@ -1,20 +1,41 @@
|
||||
@page { size: A4; margin: 2.2cm 1.7cm 2cm;
|
||||
@page { size: __PAGE_SIZE__; margin: __PAGE_MARGIN__;
|
||||
@top-center { content: '__HEADER__'; font-family: 'DejaVu Sans', sans-serif; font-size: 7.5pt;
|
||||
letter-spacing: .22em; text-transform: uppercase; color: #b3a9d6; }
|
||||
@bottom-center { content: counter(page); font-family: 'DejaVu Sans', sans-serif; font-size: 9pt; color: #999; } }
|
||||
@page:first { @top-center { content: none; } } /* NOSONAR css:S4662 — pseudo-page CSS paged media, supportee par openhtmltopdf */
|
||||
body { font-family: 'DejaVu Serif', serif; font-size: 10pt; color: #26243a; line-height: 1.5; }
|
||||
body { font-family: 'DejaVu Serif', serif; font-size: __BODY_PT__; color: #26243a; line-height: 1.5; }
|
||||
a { color: inherit; text-decoration: none; }
|
||||
/* --- Couverture --- */
|
||||
.cover { text-align: center; padding-top: 5.5cm; page-break-after: always; }
|
||||
.cover .subtitle { font-family: 'DejaVu Sans', sans-serif; font-size: 11pt; letter-spacing: .35em;
|
||||
.cover.has-art { padding-top: 1.2cm; }
|
||||
.cover-kicker { font-family: 'DejaVu Sans', sans-serif; font-size: 11pt; letter-spacing: .35em;
|
||||
text-transform: uppercase; color: #8a7bc8; }
|
||||
.cover-subtitle { font-family: 'DejaVu Sans', sans-serif; font-size: 13pt; color: #5b5180; margin-top: .3cm; }
|
||||
.cover-art { margin: .2cm 0 .6cm; }
|
||||
.cover-art img { border: 1pt solid #cfc9e0; }
|
||||
.cover-edition { margin-top: .4cm; font-family: 'DejaVu Sans', sans-serif; font-size: 9pt; letter-spacing: .2em;
|
||||
text-transform: uppercase; color: #a08b4f; }
|
||||
.cover-author { margin-top: 1cm; font-family: 'DejaVu Sans', sans-serif; font-size: 12pt; color: #2e2a4a; }
|
||||
.cover-version { margin-top: .3cm; font-family: 'DejaVu Sans', sans-serif; font-size: 8.5pt; color: #b0aac4; }
|
||||
.cover-title { font-family: 'DejaVu Sans', sans-serif; font-size: 30pt; text-transform: uppercase;
|
||||
letter-spacing: .04em; color: #2e2a4a; margin: .45cm 0 0; }
|
||||
.cover-rule { width: 3.6cm; border-bottom: 2.5pt solid #8a7bc8; margin: .5cm auto; }
|
||||
.cover-meta { font-family: 'DejaVu Sans', sans-serif; font-size: 9.5pt; color: #8076a3; letter-spacing: .06em; }
|
||||
.cover-desc { margin: 1.1cm auto 0; max-width: 12.5cm; color: #444; }
|
||||
.cover-date { margin-top: 1.4cm; font-family: 'DejaVu Sans', sans-serif; font-size: 8.5pt; color: #b0aac4; }
|
||||
/* --- Page de credits (verso de couverture) --- */
|
||||
.credits-page { page-break-after: always; padding-top: 1cm; font-size: 9pt; }
|
||||
.credits-title { font-family: 'DejaVu Sans', sans-serif; font-size: 14pt; font-weight: bold; color: #2e2a4a; }
|
||||
.credits-subtitle { font-family: 'DejaVu Sans', sans-serif; color: #5b5180; margin-bottom: .5cm; }
|
||||
.legal { margin-top: .8cm; padding-top: .3cm; border-top: 1pt solid #d8d2e8; font-size: 8pt; color: #555; }
|
||||
/* --- Introduction (module publie) --- */
|
||||
h2.section-head { page-break-after: avoid; font-family: 'DejaVu Sans', sans-serif; font-size: 12.5pt;
|
||||
color: #463b78; border-bottom: 1pt solid #d8d2e8; padding-bottom: 2pt; margin: .55cm 0 .2cm; }
|
||||
p.prose { margin: 0 0 .2cm; text-align: justify; }
|
||||
ul.prose-list { margin: .05cm 0 .25cm; padding-left: .55cm; }
|
||||
ul.prose-list li { margin: 0 0 .08cm; }
|
||||
.tech-table { width: auto; min-width: 60%; }
|
||||
.warning { background: #fff6e8; border-left: 3pt solid #d39a3a; }
|
||||
.warning .box-label { color: #a8701f; }
|
||||
/* --- Sommaire --- */
|
||||
.toc-page { page-break-after: always; }
|
||||
h1.toc-title { font-family: 'DejaVu Sans', sans-serif; font-size: 20pt; text-transform: uppercase;
|
||||
@@ -55,9 +76,11 @@ h3.folder { page-break-after: avoid; font-family: 'DejaVu Sans', sans-serif; col
|
||||
.eyebrow-light { color: #c9c0e8; }
|
||||
.scene-meta { font-style: italic; color: #6d6787; margin: -.05cm 0 .16cm; }
|
||||
/* --- Encadres speciaux (codes visuels des livres de JdR) --- */
|
||||
.box { border-radius: 3pt; padding: .2cm .35cm; margin: .2cm 0; page-break-inside: avoid; }
|
||||
/* Encadres coupables entre deux pages (un long secret MJ ne laisse plus une demi-page blanche) ;
|
||||
le libelle reste solidaire de sa premiere ligne. */
|
||||
.box { border-radius: 3pt; padding: .2cm .35cm; margin: .2cm 0; page-break-inside: auto; }
|
||||
.box-label { font-family: 'DejaVu Sans', sans-serif; font-size: 7.5pt; text-transform: uppercase;
|
||||
letter-spacing: .1em; font-weight: bold; font-style: normal; margin-bottom: .06cm; }
|
||||
letter-spacing: .1em; font-weight: bold; font-style: normal; margin-bottom: .06cm; page-break-after: avoid; }
|
||||
.readaloud { background: #faf6ea; border-top: 2pt solid #cbbd93; border-bottom: 2pt solid #cbbd93;
|
||||
border-radius: 0; font-style: italic; }
|
||||
.readaloud .box-label { color: #a08b4f; }
|
||||
@@ -78,6 +101,7 @@ div.field-label { margin: .12cm 0 .06cm; padding-right: 0; }
|
||||
/* --- Cartes (fiches PNJ/ennemis, pages de lore) --- */
|
||||
.card { page-break-inside: avoid; border: 1pt solid #e3e0ee; border-radius: 4pt;
|
||||
padding: .32cm .4cm; margin: .32cm 0; background: #fcfcfe; }
|
||||
.card.flow { page-break-inside: auto; }
|
||||
.card-body { display: block; }
|
||||
.persona { width: 100%; border-collapse: collapse; }
|
||||
.persona-portrait { width: 3cm; vertical-align: top; padding: 0 .45cm 0 0; }
|
||||
@@ -99,6 +123,7 @@ div.field-label { margin: .12cm 0 .06cm; padding-right: 0; }
|
||||
.stats-table thead th { background: #f1eef9; color: #4a3f7a; border-bottom: 1pt solid #d8d1ec; }
|
||||
.stats-table tbody th { width: 32%; color: #555; font-weight: bold; background: #f8f7fc; }
|
||||
.stats-table tr.alt td { background: #f6f5fa; }
|
||||
.stats-table tr { page-break-inside: avoid; }
|
||||
.stats-table .roll-col { width: 1.8cm; text-align: center; font-weight: bold; color: #4a3f7a; }
|
||||
.stats-table .entry-detail { color: #555; font-size: 8.5pt; }
|
||||
.stat-array { border-collapse: collapse; font-family: 'DejaVu Sans', sans-serif; font-size: 9pt;
|
||||
@@ -106,3 +131,23 @@ div.field-label { margin: .12cm 0 .06cm; padding-right: 0; }
|
||||
.stat-array th { background: #f1eef9; color: #4a3f7a; border: 1pt solid #ddd6ee;
|
||||
padding: 2.5pt 9pt; text-align: center; }
|
||||
.stat-array td { border: 1pt solid #e6e2f2; padding: 2.5pt 9pt; text-align: center; }
|
||||
/* --- Renvois internes : nom cliquable + numero de page « (p. 12) » --- */
|
||||
a.xref { color: #463b78; border-bottom: .5pt dotted #b9aede; }
|
||||
a.pref:after { content: "(p. " target-counter(attr(href), page) ")"; font-family: 'DejaVu Sans', sans-serif;
|
||||
font-size: 7.5pt; color: #8a7bc8; }
|
||||
/* --- Annexes --- */
|
||||
.annex-intro { color: #555; font-size: 9pt; }
|
||||
.annex-table td { vertical-align: top; }
|
||||
.annex-table .page-col { width: 1.6cm; text-align: right; }
|
||||
ul.annex-list { margin: 0; padding-left: .45cm; }
|
||||
ul.annex-list li { margin: 0 0 .04cm; }
|
||||
.annex-kind { font-family: 'DejaVu Sans', sans-serif; font-size: 7pt; text-transform: uppercase;
|
||||
letter-spacing: .06em; color: #7d6fb0; }
|
||||
.annex-warn { color: #a84f49; font-style: italic; }
|
||||
/* --- Cartes en pleine page paysage (page nommee) --- */
|
||||
@page landscape { size: __PAGE_SIZE__ landscape; margin: 1cm; @top-center { content: none; }
|
||||
@bottom-center { content: counter(page); font-family: 'DejaVu Sans', sans-serif; font-size: 8pt; color: #999; } }
|
||||
.map-page { page: landscape; page-break-before: always; text-align: center; }
|
||||
.map-title { font-family: 'DejaVu Sans', sans-serif; font-size: 11pt; font-weight: bold; color: #2e2a4a;
|
||||
text-align: left; margin: 0 0 .3cm; }
|
||||
.map-page img { display: block; margin: 0 auto; border: 1pt solid #cfc9e0; }
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
||||
import com.loremind.application.playcontext.PlaythroughService;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
@@ -407,4 +408,37 @@ class CampaignServiceTest {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> campaignService.updateGraphPositions("missing", "{}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publication_isEmptyWhenNeverFilled_andSavedCleaned() {
|
||||
when(campaignRepository.findById("campaign-1")).thenReturn(Optional.of(testCampaign));
|
||||
assertFalse(campaignService.getPublication("campaign-1").hasContent());
|
||||
|
||||
when(campaignRepository.save(any(Campaign.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
CampaignPublication saved = campaignService.updatePublication("campaign-1",
|
||||
new CampaignPublication(" Sous-titre ", " ", null, null, null, null, null, null, null,
|
||||
null, null, null, null, null));
|
||||
|
||||
assertEquals("Sous-titre", saved.subtitle());
|
||||
assertNull(saved.author());
|
||||
assertEquals("Sous-titre", testCampaign.getPublication().subtitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publication_emptiedIsStoredAsNull() {
|
||||
when(campaignRepository.findById("campaign-1")).thenReturn(Optional.of(testCampaign));
|
||||
when(campaignRepository.save(any(Campaign.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
campaignService.updatePublication("campaign-1", CampaignPublication.empty());
|
||||
|
||||
assertNull(testCampaign.getPublication());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publication_unknownCampaign_throws() {
|
||||
when(campaignRepository.findById("nope")).thenReturn(Optional.empty());
|
||||
assertThrows(IllegalArgumentException.class, () -> campaignService.getPublication("nope"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> campaignService.updatePublication("nope", CampaignPublication.empty()));
|
||||
}
|
||||
}
|
||||
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.application.playcontext.ClockService;
|
||||
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.SceneType;
|
||||
import com.loremind.domain.playcontext.ClockTrigger;
|
||||
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.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;
|
||||
@Mock private PlaythroughRepository playthroughRepository;
|
||||
@Mock private ClockService clockService;
|
||||
|
||||
@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));
|
||||
}
|
||||
|
||||
// --- Liens explicites (Enquête en nœuds) et horloge (Plan du méchant) ---
|
||||
|
||||
private static GuidedSkeleton withLinks(List<GuidedSkeleton.SceneSpec> scenes, List<GuidedSkeleton.LinkSpec> links,
|
||||
GuidedSkeleton.ClockSpec clock) {
|
||||
return new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Enquête", "Accroche", null, null, "Le notaire est coupable"),
|
||||
scenes, false, null, links, clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitLinks_areAddedWithTheirKind_andIndexesSurviveSkippedScenes() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
// La scène d'index 1 n'a pas de nom : ignorée, mais les index des liens restent ceux d'origine.
|
||||
List<GuidedSkeleton.SceneSpec> scenes = List.of(
|
||||
room("Accroche", SceneType.EVENT), room(" ", SceneType.LOCATION),
|
||||
room("Piste", SceneType.NPC), room("Conclusion", SceneType.REVELATION));
|
||||
|
||||
service.create(CAMP, withLinks(scenes, List.of(
|
||||
new GuidedSkeleton.LinkSpec(0, 2, "Piste", LinkType.LEAD),
|
||||
new GuidedSkeleton.LinkSpec(2, 3, "Indice", LinkType.CLUE),
|
||||
new GuidedSkeleton.LinkSpec(0, 1, "Vers la scène ignorée", LinkType.LEAD),
|
||||
new GuidedSkeleton.LinkSpec(3, 3, "Boucle sur soi", LinkType.EXIT),
|
||||
new GuidedSkeleton.LinkSpec(0, 9, "Hors limites", LinkType.EXIT)), null));
|
||||
|
||||
Scene hook = createdScenes.get(0);
|
||||
Scene lead = createdScenes.get(1);
|
||||
Scene end = createdScenes.get(2);
|
||||
assertEquals(1, hook.getBranches().size(), "seul le lien valide de l'accroche est gardé");
|
||||
assertEquals(lead.getId(), hook.getBranches().get(0).targetSceneId());
|
||||
assertEquals(LinkType.LEAD, hook.getBranches().get(0).kind());
|
||||
assertEquals(end.getId(), lead.getBranches().get(0).targetSceneId());
|
||||
assertEquals(LinkType.CLUE, lead.getBranches().get(0).kind());
|
||||
assertTrue(end.getBranches() == null || end.getBranches().isEmpty());
|
||||
verify(sceneRepository, times(2)).save(any(Scene.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chapterGmNotes_arePersisted() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
service.create(CAMP, withLinks(List.of(room("S", SceneType.EVENT)), null, null));
|
||||
|
||||
ArgumentCaptor<Chapter> chapter = ArgumentCaptor.forClass(Chapter.class);
|
||||
verify(chapterService).createChapter(chapter.capture());
|
||||
assertEquals("Le notaire est coupable", chapter.getValue().getGmNotes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clock_isCreatedInEveryPlaythroughOfTheCampaign() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
when(playthroughRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Playthrough.builder().id("p1").campaignId(CAMP).build(),
|
||||
Playthrough.builder().id("p2").campaignId(CAMP).build()));
|
||||
|
||||
GuidedSkeleton.Result result = service.create(CAMP, withLinks(List.of(room("Étape 1", SceneType.EVENT)), null,
|
||||
new GuidedSkeleton.ClockSpec(" La régence ", "La loi martiale", 6)));
|
||||
|
||||
assertEquals(2, result.clocks());
|
||||
verify(clockService).create("p1", "La régence", "La loi martiale", 6, ClockTrigger.NONE, null, null);
|
||||
verify(clockService).create("p2", "La régence", "La loi martiale", 6, ClockTrigger.NONE, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noClock_whenNotRequested() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
GuidedSkeleton.Result result = service.create(CAMP, skeleton(null, "Arc", false));
|
||||
assertEquals(0, result.clocks());
|
||||
verify(clockService, never()).create(any(), any(), any(), org.mockito.ArgumentMatchers.anyInt(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.bestiary.Npc;
|
||||
import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import 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;
|
||||
@Mock private NpcRepository npcRepository;
|
||||
|
||||
@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_twoPathsAreStillBelowTheThreeClueRule() {
|
||||
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()));
|
||||
assertEquals("2", remark("WRITE-003-SINGLE-CLUE").params().get("incoming"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_withThreeVariedPaths() {
|
||||
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("s3", 2).type(SceneType.EVENT).branches(List.of(SceneBranch.of("C", "rev"))).build(),
|
||||
scene("rev", 3).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
assertFalse(ruleIds().contains("WRITE-015-SAME-SOURCE-CLUES"));
|
||||
}
|
||||
|
||||
@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"));
|
||||
}
|
||||
|
||||
// --- WRITE-011 : scène isolée ---
|
||||
|
||||
private static SceneBranch to(String target) {
|
||||
return SceneBranch.of("vers " + target, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isolatedScene_noLinkInNorOut_inALinkedChapter() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(to("s2"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(to("s3"))).build(),
|
||||
scene("s3", 2).build(),
|
||||
scene("lost", 3).type(SceneType.LOCATION).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-011-ISOLATED-SCENE");
|
||||
assertEquals("lost", r.entityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isolatedScene_notRaised_forAnOpeningOrAProactiveScene_orWithoutLinks() {
|
||||
// « event » n'a pas de lien entrant mais en a un sortant : scène que le MJ déclenche.
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(to("s2"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("event", 2).type(SceneType.EVENT).branches(List.of(to("s2"))).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-011-ISOLATED-SCENE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isolatedScene_notRaised_whenTheChapterDoesNotUseLinks() {
|
||||
tree(List.of(scene("s1", 0).branches(List.of(to("s2"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-011-ISOLATED-SCENE"), "une seule scène reliée : pas un graphe");
|
||||
}
|
||||
|
||||
// --- WRITE-012 : passage obligé ---
|
||||
|
||||
@Test
|
||||
void chokepoint_everyPathGoesThroughOneScene() {
|
||||
// s1 → (a | b) → gate → (end1 | end2)
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(to("a"), to("b"))).build(),
|
||||
scene("a", 1).type(SceneType.LOCATION).branches(List.of(to("gate"))).build(),
|
||||
scene("b", 2).branches(List.of(to("gate"))).build(),
|
||||
scene("gate", 3).type(SceneType.LOCATION).branches(List.of(to("end1"), to("end2"))).build(),
|
||||
scene("end1", 4).build(),
|
||||
scene("end2", 5).type(SceneType.EVENT).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-012-CHOKEPOINT");
|
||||
assertEquals("gate", r.entityId());
|
||||
assertEquals("1", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chokepoint_notRaised_whenAnotherRouteExists() {
|
||||
// s1 → a → end ; s1 → b → end : deux routes indépendantes.
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(to("a"), to("b"))).build(),
|
||||
scene("a", 1).type(SceneType.LOCATION).branches(List.of(to("end"))).build(),
|
||||
scene("b", 2).branches(List.of(to("end"))).build(),
|
||||
scene("end", 3).type(SceneType.EVENT).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-012-CHOKEPOINT"));
|
||||
}
|
||||
|
||||
// --- WRITE-013 : donjon en couloir ---
|
||||
|
||||
private static Room room(String id, String... targets) {
|
||||
List<RoomBranch> branches = new ArrayList<>();
|
||||
for (String t : targets) branches.add(RoomBranch.of("porte", t));
|
||||
return Room.builder().id(id).name(id).order(0).branches(branches).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void linearDungeon_roomsLinkedWithoutAnyLoop() {
|
||||
tree(List.of(scene("crypt", 0).type(SceneType.LOCATION).rooms(List.of(
|
||||
room("r1", "r2"), room("r2", "r1", "r3"), room("r3", "r4"), room("r4"))).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-013-LINEAR-DUNGEON");
|
||||
assertEquals("4", r.params().get("rooms"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void linearDungeon_notRaised_withALoop_orUnlinkedRooms() {
|
||||
tree(List.of(
|
||||
scene("loop", 0).type(SceneType.LOCATION).rooms(List.of(
|
||||
room("r1", "r2"), room("r2", "r3"), room("r3", "r4"), room("r4", "r1"))).build(),
|
||||
scene("plain", 1).rooms(List.of(room("x1"), room("x2"), room("x3"), room("x4"))).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-013-LINEAR-DUNGEON"));
|
||||
}
|
||||
|
||||
// --- WRITE-014 : enquête sans relance ---
|
||||
|
||||
@Test
|
||||
void noProactive_investigationWithoutAnyEvent() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(to("s2"), to("rev"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(to("rev"))).build(),
|
||||
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||
assertEquals(ReadinessEntityType.CHAPTER, remark("WRITE-014-NO-PROACTIVE").entityType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noProactive_notRaised_withAnEventScene() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(to("s2"), to("rev"))).build(),
|
||||
scene("s2", 1).type(SceneType.EVENT).branches(List.of(to("rev"))).build(),
|
||||
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-014-NO-PROACTIVE"));
|
||||
}
|
||||
|
||||
// --- WRITE-015 : indices tous du même genre ---
|
||||
|
||||
@Test
|
||||
void sameSourceClues_threePathsAllFromNpcScenes() {
|
||||
tree(List.of(
|
||||
scene("n1", 0).branches(List.of(to("rev"))).build(),
|
||||
scene("n2", 1).branches(List.of(to("rev"))).build(),
|
||||
scene("n3", 2).branches(List.of(to("rev"))).build(),
|
||||
scene("rev", 3).type(SceneType.REVELATION).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-015-SAME-SOURCE-CLUES");
|
||||
assertEquals("NPC", r.params().get("kind"));
|
||||
assertEquals("3", r.params().get("count"));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
// --- WRITE-008 : la tactique des adversaires donne un but au combat ---
|
||||
|
||||
@Test
|
||||
void combatPurpose_notRaised_whenTacticsAreWritten() {
|
||||
tree(List.of(scene("fight", 0).type(SceneType.ENCOUNTER).choicesConsequences(null)
|
||||
.tactics("Ils fuient dès que leur chef tombe").build()));
|
||||
assertFalse(ruleIds().contains("WRITE-008-COMBAT-NO-PURPOSE"));
|
||||
}
|
||||
|
||||
// --- WRITE-016 : opposant ou allié sans motivation ---
|
||||
|
||||
@Test
|
||||
void npcWithoutMotivation_onlyForPlotDrivingRoles() {
|
||||
when(npcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Npc.builder().id("n1").name("Ysolde").story(new NpcStory("OPPONENT", " ", null, null)).build(),
|
||||
Npc.builder().id("n2").name("Borin").story(new NpcStory("ALLY", "Protéger sa fille", null, null)).build(),
|
||||
Npc.builder().id("n3").name("Le passant").story(new NpcStory("EXTRA", null, null, null)).build(),
|
||||
Npc.builder().id("n4").name("Sans fiche").build()));
|
||||
|
||||
List<WritingRemark> remarks = service.review(CAMP).remarks().stream()
|
||||
.filter(r -> r.ruleId().equals("WRITE-016-NPC-NO-MOTIVATION")).toList();
|
||||
assertEquals(1, remarks.size());
|
||||
assertEquals("n1", remarks.get(0).entityId());
|
||||
assertEquals(ReadinessEntityType.NPC, remarks.get(0).entityType());
|
||||
assertEquals("OPPONENT", remarks.get(0).params().get("role"));
|
||||
}
|
||||
|
||||
// --- WRITE-017 : une seule accroche ---
|
||||
|
||||
@Test
|
||||
void singleHook_whenTheArcHasExactlyOne() {
|
||||
Arc arc = arc("arc", ArcType.HUB);
|
||||
arc.setHooks("- Le prêtre a disparu");
|
||||
tree(arc, chapter("chap", "arc"), List.of(scene("s1", 0).build()));
|
||||
assertEquals(ReadinessEntityType.ARC, remark("WRITE-017-SINGLE-HOOK").entityType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleHook_notRaised_withSeveralHooks_orNone() {
|
||||
Arc several = arc("arc", ArcType.HUB);
|
||||
several.setHooks("- Le prêtre a disparu\n\n- Une récompense est offerte");
|
||||
tree(several, chapter("chap", "arc"), List.of(scene("s1", 0).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-017-SINGLE-HOOK"));
|
||||
|
||||
Arc none = arc("arc", ArcType.HUB);
|
||||
tree(none, chapter("chap", "arc"), List.of(scene("s1", 0).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-017-SINGLE-HOOK"), "accroches non renseignées : pas de remarque");
|
||||
}
|
||||
}
|
||||
@@ -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)); }
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user