Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10574ba0c5 | ||
|
|
ace2e486fc | ||
|
|
c008c22e09 | ||
|
|
bf606c23d1 | ||
|
|
1898e8b1ae | ||
|
|
e77ad85be9 | ||
|
|
11939fe39e | ||
|
|
8958822545 | ||
|
|
007bcce8a7 | ||
|
|
a985bbd018 | ||
|
|
1c9ac524db | ||
|
|
abf66733fe | ||
|
|
763219412b | ||
|
|
cccf2b85db | ||
|
|
6ae9238fee | ||
|
|
0ef1380265 | ||
|
|
9a7e93b162 | ||
|
|
106754fd77 | ||
|
|
0c0581e894 | ||
|
|
dae0508c93 | ||
|
|
cbd59a5bd9 | ||
|
|
d759bc8131 | ||
|
|
ac7648f9fe | ||
|
|
d9a90f8412 | ||
|
|
2e9632de49 | ||
|
|
fbb1956e17 |
@@ -47,7 +47,7 @@ jobs:
|
||||
|
||||
# Detection du canal :
|
||||
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
|
||||
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR prives
|
||||
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR publics
|
||||
# loremind-beta-<component> ; backup Gitea avec :version)
|
||||
- name: Extract version & channel
|
||||
id: meta
|
||||
@@ -74,8 +74,8 @@ jobs:
|
||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
# Build & push canal BETA
|
||||
# GHCR : repos prives loremind-beta-<component> (gated par PAT distribue
|
||||
# via le relais Patreon aux tiers Compagnon).
|
||||
# GHCR : repos PUBLICS loremind-beta-<component> (canal beta libre ;
|
||||
# le switcher bascule IMAGE_NAMESPACE vers ce prefixe).
|
||||
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne
|
||||
# pas faire upgrader les installs branchees sur Gitea).
|
||||
- name: Build & push ${{ matrix.component }} (beta)
|
||||
|
||||
@@ -12,12 +12,10 @@ name: Desktop installers
|
||||
# inclus) pour que le tag declenche ce workflow.
|
||||
#
|
||||
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
||||
# Tag beta vX.Y.Z-beta* -> AUCUNE publication publique. Le .msi est depose en
|
||||
# ARTEFACT PRIVE du run (telechargeable seulement par
|
||||
# toi via l'onglet Actions) ; tu le joins ensuite a un
|
||||
# post Patreon reserve a un palier. Patreon = la
|
||||
# barriere d'acces (equivalent du registry prive +
|
||||
# relais pour les images Docker beta).
|
||||
# Tag beta vX.Y.Z-beta* -> GitHub Release PUBLIQUE marquee « pre-release » : le
|
||||
# canal beta est libre. /releases/latest l'ignore, donc
|
||||
# seules les installations beta en sont prevenues
|
||||
# (cf. DesktopUpdateService).
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -106,6 +104,10 @@ jobs:
|
||||
windows:
|
||||
needs: tests
|
||||
runs-on: windows-latest
|
||||
# Reprises par le job `publish` (tag de la release, statut pre-release).
|
||||
outputs:
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
isbeta: ${{ steps.ver.outputs.isbeta }}
|
||||
steps:
|
||||
# En declenchement manuel, on checkout le TAG correspondant a la version
|
||||
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
||||
@@ -169,33 +171,20 @@ jobs:
|
||||
shell: pwsh
|
||||
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||
|
||||
# STABLE uniquement : Release GitHub publique avec le .msi.
|
||||
# tag_name explicite : en declenchement manuel, github.ref est une branche,
|
||||
# donc on cible le tag derive (la release est attachee au bon tag).
|
||||
- name: Publish installer to GitHub Release (stable)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.ver.outputs.tag }}
|
||||
files: core/target/dist-out/*.msi
|
||||
fail_on_unmatched_files: true
|
||||
generate_release_notes: true
|
||||
|
||||
# BETA uniquement : artefact PRIVE (pas de release publique). A recuperer
|
||||
# via l'onglet Actions puis a joindre a un post Patreon gate par palier.
|
||||
- name: Upload installer as private artifact (beta)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
||||
# Le .msi est passe au job `publish`, seul a creer la release.
|
||||
- name: Keep installer for the release
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: loremind-beta-${{ steps.ver.outputs.version }}-msi
|
||||
name: installer-windows
|
||||
path: core/target/dist-out/*.msi
|
||||
retention-days: 90
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
||||
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
||||
# Brain empaquete via python-build-standalone (pas de Python embeddable Linux
|
||||
# officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de
|
||||
# publication que windows : stable -> release publique ; beta -> artefact prive.
|
||||
# publication que windows : stable -> release publique ; beta -> pre-release.
|
||||
linux:
|
||||
needs: tests
|
||||
runs-on: ubuntu-latest
|
||||
@@ -242,21 +231,40 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
||||
|
||||
# STABLE uniquement : attache l'AppImage a la release publique (meme tag que
|
||||
# le .msi -> les deux installeurs sur la meme release).
|
||||
- name: Publish AppImage to GitHub Release (stable)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.ver.outputs.tag }}
|
||||
files: core/target/dist-out/DM_Loremind*.AppImage
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
# BETA uniquement : artefact PRIVE (pas de release publique).
|
||||
- name: Upload AppImage as private artifact (beta)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
||||
# L'AppImage est passee au job `publish`, seul a creer la release.
|
||||
- name: Keep AppImage for the release
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: loremind-beta-${{ steps.ver.outputs.version }}-appimage
|
||||
name: installer-linux
|
||||
path: core/target/dist-out/DM_Loremind*.AppImage
|
||||
retention-days: 90
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
# PUBLICATION : un seul job cree la release et y attache les deux installeurs.
|
||||
# Quand windows et linux publiaient chacun de leur cote, ils tournaient en
|
||||
# parallele et creaient DEUX releases pour le meme tag (une publiee, une en
|
||||
# brouillon), l'un echouant sur « already_exists ». Rien n'est publie si l'un
|
||||
# des deux builds echoue : une release a toujours ses deux installeurs.
|
||||
# Relancer le workflow pour une version deja publiee met la release a jour et
|
||||
# remplace les fichiers de meme nom (pas besoin de la supprimer).
|
||||
publish:
|
||||
needs: [windows, linux]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get installers
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: installer-*
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
|
||||
# tag_name explicite : en declenchement manuel, github.ref est une branche.
|
||||
# Une beta est publiee en pre-release (ignoree par /releases/latest).
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.windows.outputs.tag }}
|
||||
files: dist/*
|
||||
fail_on_unmatched_files: true
|
||||
generate_release_notes: true
|
||||
prerelease: ${{ needs.windows.outputs.isbeta == 'true' }}
|
||||
|
||||
@@ -7,11 +7,6 @@
|
||||
brain/data/settings.json
|
||||
*.key
|
||||
*.pem
|
||||
# Exception : la cle PUBLIQUE JWT du relais Patreon est destinee a etre
|
||||
# embarquee dans le binaire. Pas de risque a la committer (c'est une cle
|
||||
# publique par construction). Sans cette exception, le module licensing
|
||||
# est silencieusement desactive dans les builds CI.
|
||||
!core/src/main/resources/licensing/jwt-public-key.pem
|
||||
|
||||
# ============================================================================
|
||||
# Java / Spring Boot / Maven
|
||||
|
||||
+1
-2
@@ -7,7 +7,6 @@
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
|
||||
## Découvrir DM Loremind en vidéo
|
||||
@@ -67,7 +66,7 @@ Quelques limites à connaître :
|
||||
|
||||
DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
||||
- **Canal bêta** — les nouveautés en avant-première, gratuites pour tous : bascule depuis les Paramètres (Docker) ou pré-version GitHub (bureau)
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||
|
||||
## Licence
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/en/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
|
||||
## See DM Loremind in action
|
||||
@@ -67,7 +66,7 @@ A few limitations to be aware of:
|
||||
|
||||
DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support:
|
||||
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — early access to features, roadmap voting, exclusive devlogs
|
||||
- **Beta channel** — new features ahead of time, free for everyone: switch from Settings (Docker) or install a GitHub pre-release (desktop)
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
||||
|
||||
## License
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.application.generate_page import GeneratePageUseCase
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import conversation_title as title_prompts
|
||||
from app.application.prompts import guided_answers as guided_answers_prompts
|
||||
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
||||
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
||||
from app.application.prompts import session_recap as session_recap_prompts
|
||||
@@ -290,3 +291,82 @@ async def generate_session_recap(
|
||||
if not recap:
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
||||
return SessionRecapResponseDTO(recap=recap)
|
||||
|
||||
|
||||
# --- Méthodes guidées : proposer des réponses à partir d'une idée (Mentor d'écriture) ----
|
||||
|
||||
|
||||
class GuidedOptionDTO(BaseModel):
|
||||
"""Choix possible d'une question à choix : valeur technique + libellé lisible."""
|
||||
|
||||
value: str
|
||||
label: str = Field(default="")
|
||||
|
||||
|
||||
class GuidedFieldDTO(BaseModel):
|
||||
"""Une question de la méthode guidée (décrite par le front, relayée par le Core)."""
|
||||
|
||||
key: str
|
||||
label: str = Field(default="")
|
||||
hint: str = Field(default="")
|
||||
step: str = Field(default="")
|
||||
options: list[GuidedOptionDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class GuidedAnswersRequestDTO(BaseModel):
|
||||
method_name: str = Field(default="")
|
||||
method_principle: str = Field(default="")
|
||||
idea: str = Field(default="")
|
||||
context: str = Field(default="")
|
||||
fields: list[GuidedFieldDTO] = Field(default_factory=list)
|
||||
existing: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class GuidedAnswersResponseDTO(BaseModel):
|
||||
"""Une réponse proposée par clé (clés demandées uniquement, choix valides, non vides)."""
|
||||
|
||||
answers: dict[str, str]
|
||||
|
||||
|
||||
@router.post("/generate/guided-answers", response_model=GuidedAnswersResponseDTO)
|
||||
async def generate_guided_answers(
|
||||
body: GuidedAnswersRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> GuidedAnswersResponseDTO:
|
||||
"""Propose des réponses aux questions d'une méthode guidée à partir de l'idée du MJ.
|
||||
|
||||
Rien n'est enregistré : le front remplit les champs vides, le MJ relit et corrige. Une
|
||||
question à choix n'accepte qu'une des valeurs proposées ; le reste est ignoré.
|
||||
"""
|
||||
by_key = {f.key: f for f in body.fields if f.key}
|
||||
prompt = guided_answers_prompts.guided_answers_prompt(
|
||||
body.method_name, body.method_principle, body.idea, body.context,
|
||||
[f.model_dump() for f in body.fields], body.existing, language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de réponses exploitables.")
|
||||
return GuidedAnswersResponseDTO(answers=_clean_guided_answers(parsed.get("answers"), by_key))
|
||||
|
||||
|
||||
def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dict[str, str]:
|
||||
"""Garde les clés demandées, non vides ; une question à choix n'accepte qu'une valeur proposée."""
|
||||
out: dict[str, str] = {}
|
||||
if not isinstance(raw, dict):
|
||||
return out
|
||||
for key, value in raw.items():
|
||||
field = by_key.get(str(key))
|
||||
if field is None or not isinstance(value, (str, int, float)):
|
||||
continue
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
continue
|
||||
if field.options and text not in {o.value for o in field.options}:
|
||||
continue
|
||||
out[field.key] = text
|
||||
return out
|
||||
|
||||
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
|
||||
sections: dict[str, str]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
# Règles en deux langues : {code langue → sections} et langue d'origine du livre.
|
||||
sections_by_language: dict[str, dict[str, str]] = {}
|
||||
source_language: str = ""
|
||||
|
||||
|
||||
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||
@@ -70,6 +73,8 @@ async def import_rules(
|
||||
sections=result.sections,
|
||||
page_count=result.page_count,
|
||||
ocr_page_count=result.ocr_page_count,
|
||||
sections_by_language=result.sections_by_language,
|
||||
source_language=result.source_language,
|
||||
)
|
||||
|
||||
|
||||
@@ -115,6 +120,7 @@ async def import_rules_stream(
|
||||
@router.post("/import/campaign/stream")
|
||||
async def import_campaign_stream(
|
||||
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
file: UploadFile = File(...),
|
||||
) -> StreamingResponse:
|
||||
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
||||
@@ -131,7 +137,7 @@ async def import_campaign_stream(
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(content):
|
||||
async for ev in use_case.stream(content, language=language):
|
||||
event_type = ev.pop("type")
|
||||
yield sse_event(event_type, ev)
|
||||
except PdfExtractionError as exc:
|
||||
|
||||
@@ -361,7 +361,7 @@ class ImportCampaignUseCase:
|
||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||
self._map_concurrency = max(1, map_concurrency)
|
||||
|
||||
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult:
|
||||
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
@@ -371,7 +371,7 @@ class ImportCampaignUseCase:
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
results = await asyncio.gather(*(
|
||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||
for i, c in wave
|
||||
))
|
||||
for res in results:
|
||||
@@ -386,7 +386,7 @@ class ImportCampaignUseCase:
|
||||
npcs=merger.npcs(),
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes):
|
||||
async def stream(self, pdf_bytes: bytes, language: str = "fr"):
|
||||
"""Variante streamée : yield des évènements d'avancement.
|
||||
|
||||
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
||||
@@ -432,7 +432,7 @@ class ImportCampaignUseCase:
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
gathered = asyncio.gather(
|
||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||
for i, c in wave),
|
||||
return_exceptions=True,
|
||||
)
|
||||
@@ -553,21 +553,23 @@ class ImportCampaignUseCase:
|
||||
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
||||
|
||||
async def _map_chunk(
|
||||
self, chunk: str, *, index: int, total: int, toc_block: str = ""
|
||||
self, chunk: str, *, index: int, total: int, toc_block: str = "", language: str = "fr"
|
||||
) -> dict:
|
||||
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
||||
return await self._extract_payload(
|
||||
chunk, index=index, total=total, depth=0, toc_block=toc_block)
|
||||
chunk, index=index, total=total, depth=0, toc_block=toc_block, language=language)
|
||||
|
||||
async def _extract_payload(
|
||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = ""
|
||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = "",
|
||||
language: str = "fr",
|
||||
) -> dict:
|
||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
||||
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
||||
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||
prompt = (
|
||||
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME)
|
||||
prompts.MAP_SYSTEM.format(default_arc=prompts.default_arc_name(language))
|
||||
+ prompts.language_block(language)
|
||||
+ toc_section
|
||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||
"Renvoie maintenant le JSON de l'arborescence."
|
||||
@@ -591,9 +593,9 @@ class ImportCampaignUseCase:
|
||||
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||
"re-découpage en 2 moitiés plus digestes…")
|
||||
a = await self._extract_payload(
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
b = await self._extract_payload(
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||
payload, truncated = self._parse_payload(raw, index=index)
|
||||
|
||||
@@ -607,9 +609,9 @@ class ImportCampaignUseCase:
|
||||
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||
"re-découpage en 2 moitiés plus digestes…")
|
||||
a = await self._extract_payload(
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
b = await self._extract_payload(
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||
if truncated:
|
||||
logger.warning(
|
||||
|
||||
@@ -26,6 +26,7 @@ from app.application.import_status import (
|
||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import import_rules as prompts
|
||||
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
|
||||
from app.application.streaming import with_heartbeat
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||
|
||||
@@ -90,6 +91,9 @@ _ANCHORS_SCHEMA: dict = {
|
||||
}
|
||||
|
||||
|
||||
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
|
||||
_DETECT_CHARS = 20_000
|
||||
|
||||
class _SectionMerger:
|
||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||
|
||||
@@ -250,10 +254,25 @@ class ImportRulesUseCase:
|
||||
merger = _SectionMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||
sections = merger.result()
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
by_language = {source: sections}
|
||||
translator = RulesTranslator(self._llm)
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
|
||||
by_language[target] = {
|
||||
titles.get(title, title): await translator.translate_content(content, source, target)
|
||||
for title, content in sections.items()
|
||||
}
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
return RulesImportResult(
|
||||
sections=merger.result(),
|
||||
sections=sections,
|
||||
page_count=doc.page_count,
|
||||
ocr_page_count=doc.ocr_page_count,
|
||||
sections_by_language=by_language,
|
||||
source_language=source,
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
||||
@@ -344,14 +363,57 @@ class ImportRulesUseCase:
|
||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||
return
|
||||
|
||||
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
|
||||
# langue de l'application. Un échec de traduction n'annule pas l'import.
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
by_language: dict[str, dict[str, str]] = {source: sections}
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
async for ev in self._translate_events(sections, source, target):
|
||||
if ev["type"] == "_translated":
|
||||
by_language[target] = ev["sections"]
|
||||
else:
|
||||
yield ev
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(target)}) impossible : {str(exc)[:200]}"}
|
||||
|
||||
yield {
|
||||
"type": "done",
|
||||
"sections": sections,
|
||||
"sections_by_language": by_language,
|
||||
"source_language": source,
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
}
|
||||
|
||||
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
|
||||
"""Évènements d'avancement de la traduction ; le dernier est
|
||||
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
|
||||
translator = RulesTranslator(self._llm)
|
||||
titles = list(sections)
|
||||
total = len(titles)
|
||||
label = language_name(target)
|
||||
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
|
||||
mapping: dict[str, str] = {}
|
||||
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": 0, "total": total}
|
||||
elif kind == "result":
|
||||
mapping = unique_titles(payload)
|
||||
out: dict[str, str] = {}
|
||||
for i, title in enumerate(titles):
|
||||
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
|
||||
"current": i + 1, "total": total}
|
||||
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||
elif kind == "result":
|
||||
out[mapping.get(title, title)] = payload
|
||||
yield {"type": "_translated", "sections": out}
|
||||
|
||||
# --- MAP : un morceau → sections -----------------------------------------
|
||||
|
||||
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
||||
|
||||
@@ -113,5 +113,8 @@ async def generate_with_retry(
|
||||
+ str(exc)[:160]
|
||||
)
|
||||
await asyncio.sleep(wait)
|
||||
# Le message « nouvel essai dans Ns » deviendrait faux : on dit que
|
||||
# l'essai suivant est lancé (il peut durer plusieurs minutes).
|
||||
notify_status(f"Nouvel essai en cours (tentative {attempt + 2}/{_ATTEMPTS})…")
|
||||
assert last_error is not None
|
||||
raise last_error
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Prompt des méthodes guidées (Mentor d'écriture) : à partir de l'idée de départ du MJ,
|
||||
proposer des réponses aux questions de la méthode (Donjon en 5 salles, Enquête en nœuds,
|
||||
Plan du méchant…).
|
||||
|
||||
Générique : le front décrit la méthode (nom ; principe suivi du rôle de chaque étape, comme
|
||||
dans l'assistant manuel) et ses questions (clé, libellé,
|
||||
aide, étape, choix possibles) ; ce module ne fait que formuler le prompt. Les réponses
|
||||
déjà écrites par le MJ sont fournies pour rester cohérent et ne jamais être contredites.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
|
||||
def _field_line(field: dict) -> str:
|
||||
key = str(field.get("key") or "").strip()
|
||||
label = str(field.get("label") or key).strip()
|
||||
hint = str(field.get("hint") or "").strip()
|
||||
step = str(field.get("step") or "").strip()
|
||||
line = f'- "{key}"'
|
||||
if step:
|
||||
line += f" [{step}]"
|
||||
line += f" : {label}"
|
||||
if hint:
|
||||
line += f" — {hint}"
|
||||
options = field.get("options") or []
|
||||
if options:
|
||||
values = ", ".join(f'"{o.get("value")}" ({o.get("label")})' for o in options if o.get("value"))
|
||||
line += f" — UNE valeur parmi : {values}"
|
||||
return line
|
||||
|
||||
|
||||
def guided_answers_prompt(method_name: str, method_principle: str, idea: str, context: str,
|
||||
fields: list[dict], existing: dict[str, str], language: str) -> str:
|
||||
"""Construit le prompt. `fields` = [{key, label, hint, step, options}] ; `existing` = réponses du MJ."""
|
||||
fields_list = "\n".join(_field_line(f) for f in fields or [] if f.get("key"))
|
||||
existing_lines = "\n".join(
|
||||
f'- "{k}" : {v.strip()}' for k, v in (existing or {}).items() if isinstance(v, str) and v.strip())
|
||||
existing_block = (
|
||||
"\nCe que le MJ a DÉJÀ écrit (à respecter, ne le contredis jamais) :\n"
|
||||
f"{existing_lines}\n" if existing_lines else ""
|
||||
)
|
||||
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context and context.strip() else ""
|
||||
guide = method_principle.strip() if method_principle else ""
|
||||
guide_block = (
|
||||
"\nLa méthode, telle que le MJ la suit à la main (principe, puis rôle de chaque étape) :\n"
|
||||
f"{guide}\n" if guide else ""
|
||||
)
|
||||
return (
|
||||
"Tu es un auteur expérimenté de scénarios de jeu de rôle, qui aide un MJ à écrire son aventure "
|
||||
f"avec la méthode « {method_name.strip() or 'guidée'} ».\n"
|
||||
f"{guide_block}\n"
|
||||
f"Idée de départ du MJ : {idea.strip() or '(aucune : propose une aventure originale)'}\n"
|
||||
f"{context_block}{existing_block}\n"
|
||||
"Questions de la méthode auxquelles tu dois répondre (n'utilise QUE ces clés) :\n"
|
||||
f"{fields_list}\n\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"answers": {"cle": "réponse", ...}}\n'
|
||||
"- N'inclus QUE des clés de la liste. Pour une question à choix, renvoie EXACTEMENT une des "
|
||||
"valeurs proposées.\n"
|
||||
"- Pars de l'idée du MJ et développe-la : garde son ton, ses lieux, ses personnages ; n'en change "
|
||||
"pas le sujet.\n"
|
||||
"- Respecte la méthode : chaque réponse remplit le rôle de SON étape, tel que décrit ci-dessus "
|
||||
"(ex. une épreuve qui ne se règle pas par un combat, des pistes qui se recoupent). Ne mélange pas "
|
||||
"les étapes.\n"
|
||||
"- Toutes les réponses forment UNE aventure cohérente, concrète et jouable "
|
||||
"(noms, lieux, motivations précises ; pas de généralités).\n"
|
||||
"- Sois concis : un nom en quelques mots, une description en 2 à 4 phrases.\n"
|
||||
"- Donne toujours aux joueurs de vrais choix et plusieurs façons de progresser.\n"
|
||||
f"- Rédige les réponses en {language_name(language)}.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -1,7 +1,29 @@
|
||||
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
||||
from app.core.language import language_name
|
||||
|
||||
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||
DEFAULT_ARC_NAME = "Aventure principale"
|
||||
DEFAULT_ARC_NAMES = {"fr": DEFAULT_ARC_NAME, "en": "Main adventure"}
|
||||
|
||||
|
||||
def default_arc_name(language: str) -> str:
|
||||
"""Nom de l'arc unique, dans la langue de l'interface."""
|
||||
return DEFAULT_ARC_NAMES.get(language, DEFAULT_ARC_NAME)
|
||||
|
||||
|
||||
def language_block(language: str) -> str:
|
||||
"""Consigne de langue : les textes sont écrits dans la langue de l'interface, quelle que
|
||||
soit celle du livre (traduits fidèlement s'il le faut). Les TITRES et noms propres restent
|
||||
ceux du livre : la fusion des morceaux se fait par nom exact, et un nom ne se traduit pas."""
|
||||
name = language_name(language)
|
||||
return (
|
||||
"\n\nLANGUE DE SORTIE :\n"
|
||||
f"- Rédige TOUS les textes (description, player_narration, gm_notes, salles, PNJ) en {name}, "
|
||||
f"quelle que soit la langue du livre. Si le livre est dans une autre langue, TRADUIS ces textes "
|
||||
"fidèlement, sans les résumer davantage.\n"
|
||||
"- Garde TELS QUELS les noms propres (personnages, lieux, divinités, sorts, objets nommés) "
|
||||
"et les noms d'arcs, de chapitres, de scènes, de salles et de PNJ (titres du livre)."
|
||||
)
|
||||
|
||||
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
||||
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Règles en deux langues : détection de la langue d'un livre de règles et traduction de
|
||||
ses sections (titre + contenu markdown) vers l'autre langue de l'application.
|
||||
|
||||
L'extraction reste FIDÈLE au livre (langue d'origine) ; la traduction produit la seconde
|
||||
version. Les noms propres (lieux, personnages, divinités, sorts, objets nommés) sont
|
||||
conservés tels quels. Un contenu long est traduit par morceaux coupés aux paragraphes,
|
||||
pour rester sous les limites de sortie des modèles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.core.language import language_name
|
||||
from app.domain.ports import LLMProvider
|
||||
|
||||
LANGUAGES = ("fr", "en")
|
||||
|
||||
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
|
||||
CHUNK_CHARS = 6000
|
||||
|
||||
_FR_WORDS = {"le", "la", "les", "des", "une", "est", "et", "du", "dans", "pour", "que", "qui",
|
||||
"sur", "avec", "vous", "votre", "sont", "pas", "par", "au", "aux", "ce", "cette", "il"}
|
||||
_EN_WORDS = {"the", "and", "of", "to", "is", "in", "you", "your", "for", "with", "that", "are",
|
||||
"on", "as", "be", "this", "it", "an", "by", "or", "can", "if", "each", "when"}
|
||||
|
||||
|
||||
def detect_language(text: str, default: str = "fr") -> str:
|
||||
"""Langue dominante (« fr » ou « en ») par comptage de mots-outils ; `default` si indécis."""
|
||||
words = re.findall(r"[a-zàâçéèêëîïôûùüÿœ']+", (text or "").lower())
|
||||
fr = sum(1 for w in words if w in _FR_WORDS)
|
||||
en = sum(1 for w in words if w in _EN_WORDS)
|
||||
if fr == en:
|
||||
return default if default in LANGUAGES else "fr"
|
||||
return "fr" if fr > en else "en"
|
||||
|
||||
|
||||
def other_languages(source: str) -> list[str]:
|
||||
return [lang for lang in LANGUAGES if lang != source]
|
||||
|
||||
|
||||
def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
|
||||
"""Coupe un markdown en morceaux ≤ max_chars, aux limites de paragraphes (puis de lignes)."""
|
||||
if len(text) <= max_chars:
|
||||
return [text]
|
||||
chunks: list[str] = []
|
||||
current = ""
|
||||
for para in re.split(r"(\n\s*\n)", text):
|
||||
if len(current) + len(para) <= max_chars:
|
||||
current += para
|
||||
continue
|
||||
if current.strip():
|
||||
chunks.append(current)
|
||||
current = ""
|
||||
while len(para) > max_chars: # paragraphe géant : coupe aux lignes, sinon brutalement
|
||||
cut = para.rfind("\n", 0, max_chars)
|
||||
cut = cut if cut > 0 else max_chars
|
||||
chunks.append(para[:cut])
|
||||
para = para[cut:]
|
||||
current = para
|
||||
if current.strip():
|
||||
chunks.append(current)
|
||||
return chunks
|
||||
|
||||
|
||||
def content_prompt(text: str, source: str, target: str) -> str:
|
||||
return (
|
||||
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
|
||||
f"vers la langue « {language_name(target)} ».\n\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\n"
|
||||
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
|
||||
"objets nommés.\n"
|
||||
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
|
||||
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
|
||||
"Extrait :\n"
|
||||
f"{text}"
|
||||
)
|
||||
|
||||
|
||||
def titles_prompt(titles: list[str], source: str, target: str) -> str:
|
||||
listing = "\n".join(f"- {t}" for t in titles)
|
||||
return (
|
||||
f"Traduis ces titres de sections d'un livre de règles de jeu de rôle de la langue "
|
||||
f"« {language_name(source)} » vers la langue « {language_name(target)} ». "
|
||||
"Garde les noms propres tels quels.\n"
|
||||
'Réponds UNIQUEMENT par un objet JSON : {"titles": {"titre d\'origine": "titre traduit", ...}}\n\n'
|
||||
f"{listing}"
|
||||
)
|
||||
|
||||
|
||||
class RulesTranslator:
|
||||
"""Traduit des sections de règles {titre: markdown} d'une langue vers une autre."""
|
||||
|
||||
def __init__(self, llm: LLMProvider) -> None:
|
||||
self._llm = llm
|
||||
|
||||
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
|
||||
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
|
||||
if not titles:
|
||||
return {}
|
||||
raw = await generate_with_retry(self._llm, titles_prompt(titles, source, target),
|
||||
output_format="json", temperature=0.2)
|
||||
parsed, _ = load_json_object(raw)
|
||||
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
||||
out: dict[str, str] = {}
|
||||
for title in titles:
|
||||
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||
return out
|
||||
|
||||
async def translate_content(self, text: str, source: str, target: str) -> str:
|
||||
"""Traduit un contenu markdown (morceau par morceau s'il est long)."""
|
||||
if not text or not text.strip():
|
||||
return text
|
||||
parts = []
|
||||
for chunk in split_markdown(text):
|
||||
if not chunk.strip():
|
||||
parts.append(chunk)
|
||||
continue
|
||||
translated = await generate_with_retry(self._llm, content_prompt(chunk, source, target),
|
||||
temperature=0.2)
|
||||
parts.append(translated.strip())
|
||||
return "\n\n".join(p for p in parts if p.strip())
|
||||
|
||||
|
||||
def unique_titles(titles: dict[str, str]) -> dict[str, str]:
|
||||
"""Évite deux sections traduites sous le même titre (sinon l'une écraserait l'autre)."""
|
||||
seen: dict[str, int] = {}
|
||||
out: dict[str, str] = {}
|
||||
for original, translated in titles.items():
|
||||
count = seen.get(translated, 0)
|
||||
seen[translated] = count + 1
|
||||
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
||||
return out
|
||||
@@ -367,6 +367,10 @@ class RulesImportResult:
|
||||
sections: dict[str, str]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
# Règles en deux langues : {code langue → sections}. La langue d'origine du livre
|
||||
# (`source_language`) contient l'extraction fidèle ; l'autre, sa traduction.
|
||||
sections_by_language: dict[str, dict[str, str]] = field(default_factory=dict)
|
||||
source_language: str = ""
|
||||
|
||||
def to_markdown(self) -> str:
|
||||
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
||||
app = FastAPI(
|
||||
title="LoreMind Brain",
|
||||
description="Backend IA pour la génération de contenu narratif.",
|
||||
version="1.0.3",
|
||||
version="1.6.2-beta",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Méthodes guidées : prompt de propositions et nettoyage des réponses du modèle."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.api.routers.generation import GuidedFieldDTO, GuidedOptionDTO, _clean_guided_answers
|
||||
from app.application.prompts.guided_answers import guided_answers_prompt
|
||||
|
||||
|
||||
def _fields() -> dict[str, GuidedFieldDTO]:
|
||||
return {
|
||||
"title": GuidedFieldDTO(key="title", label="Nom de l'enquête"),
|
||||
"node1.nature": GuidedFieldDTO(key="node1.nature", label="Genre de scène", options=[
|
||||
GuidedOptionDTO(value="location", label="Un lieu"), GuidedOptionDTO(value="npc", label="Une personne")]),
|
||||
}
|
||||
|
||||
|
||||
def test_prompt_contains_idea_questions_choices_existing_answers_and_language():
|
||||
prompt = guided_answers_prompt(
|
||||
"Enquête en nœuds", "Trois pistes qui se recoupent.", "Une tour qui se rallume", "Campagne : Valfroide",
|
||||
[{"key": "title", "label": "Nom de l'enquête", "hint": "Ex. : L'héritage", "step": "Le mystère"},
|
||||
{"key": "node1.nature", "label": "Genre", "options": [{"value": "location", "label": "Un lieu"}]}],
|
||||
{"truth": "Le notaire est coupable", "empty": " "}, "en")
|
||||
|
||||
assert "Une tour qui se rallume" in prompt
|
||||
assert '"title" [Le mystère] : Nom de l\'enquête — Ex. : L\'héritage' in prompt
|
||||
assert 'UNE valeur parmi : "location" (Un lieu)' in prompt
|
||||
assert "Le notaire est coupable" in prompt
|
||||
assert '"empty"' not in prompt, "une réponse vide n'est pas rappelée"
|
||||
assert "Campagne : Valfroide" in prompt
|
||||
assert "anglais" in prompt
|
||||
|
||||
|
||||
def test_prompt_lists_the_method_steps_and_asks_to_follow_them():
|
||||
guide = ("Cinq temps dans un même lieu.\n\n"
|
||||
"- Salle 2 : l'épreuve : ici, l'épée ne suffit pas.\n"
|
||||
"- Salle 3 : le revers : les choses se compliquent.")
|
||||
p = guided_answers_prompt("Donjon en 5 salles", guide, "Une crypte", "", [{"key": "room2.name"}], {}, "fr")
|
||||
assert "telle que le MJ la suit à la main" in p
|
||||
assert "- Salle 2 : l'épreuve : ici, l'épée ne suffit pas." in p
|
||||
assert "rôle de SON étape" in p
|
||||
assert "Idée de départ du MJ : Une crypte" in p
|
||||
|
||||
|
||||
def test_prompt_without_idea_asks_for_an_original_adventure():
|
||||
prompt = guided_answers_prompt("Plan du méchant", "", " ", "", [{"key": "villain", "label": "Adversaire"}], {}, "fr")
|
||||
assert "propose une aventure originale" in prompt
|
||||
assert "français" in prompt
|
||||
|
||||
|
||||
def test_clean_keeps_requested_keys_and_valid_choices_only():
|
||||
out = _clean_guided_answers({
|
||||
"title": " L'héritage empoisonné ",
|
||||
"node1.nature": "npc",
|
||||
"unknown": "ignorée",
|
||||
"empty": "",
|
||||
}, _fields())
|
||||
assert out == {"title": "L'héritage empoisonné", "node1.nature": "npc"}
|
||||
|
||||
|
||||
def test_clean_rejects_an_invalid_choice_and_non_text_values():
|
||||
out = _clean_guided_answers({"node1.nature": "dragon", "title": ["liste"]}, _fields())
|
||||
assert out == {}
|
||||
assert _clean_guided_answers("pas un objet", _fields()) == {}
|
||||
@@ -100,6 +100,8 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||
("Traduis cet extrait", "spells"),
|
||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||
("BBB second", '{"Magie":"sorts"}'),
|
||||
])
|
||||
@@ -111,6 +113,25 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
||||
assert done["type"] == "done"
|
||||
assert done["sections"] == {"Magie": "sorts"}
|
||||
assert done["skipped"] == 1
|
||||
# Règles en deux langues : livre en français (« Texte du PDF. ») → traduction anglaise.
|
||||
assert done["source_language"] == "fr"
|
||||
assert done["sections_by_language"] == {"fr": {"Magie": "sorts"}, "en": {"Magic": "spells"}}
|
||||
assert any(e["type"] == "status" and "anglais" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_rules_stream_keeps_the_source_language_when_translation_fails(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["The rules of the game"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("HTTP 503 saturé")),
|
||||
("The rules of the game", '{"Combat":"Each round, you roll the dice."}'),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc("The rules of the game are simple and you can play.")))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["source_language"] == "en"
|
||||
assert done["sections_by_language"] == {"en": {"Combat": "Each round, you roll the dice."}}
|
||||
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
||||
@@ -155,3 +176,34 @@ async def test_campaign_stream_all_fail_emits_error(one_chunk, no_sleep):
|
||||
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
assert events[-1]["type"] == "error"
|
||||
|
||||
|
||||
class _RecordingLLM(ScriptedLLM):
|
||||
"""ScriptedLLM qui garde les prompts reçus."""
|
||||
|
||||
def __init__(self, responses: list) -> None:
|
||||
super().__init__(responses)
|
||||
self.prompts: list[str] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
return await super().generate(prompt, output_format=output_format, temperature=temperature)
|
||||
|
||||
|
||||
async def test_campaign_import_writes_in_the_interface_language_and_keeps_names():
|
||||
llm = _RecordingLLM([_TREE])
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf", language="en")]
|
||||
assert events[-1]["type"] == "done"
|
||||
prompt = llm.prompts[0]
|
||||
assert "LANGUE DE SORTIE" in prompt
|
||||
assert "en anglais" in prompt
|
||||
assert "noms propres" in prompt
|
||||
assert '"Main adventure"' in prompt, "arc par défaut dans la langue de l'interface"
|
||||
|
||||
|
||||
async def test_campaign_import_defaults_to_french():
|
||||
llm = _RecordingLLM([_TREE])
|
||||
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
||||
assert "en français" in llm.prompts[0]
|
||||
assert '"Aventure principale"' in llm.prompts[0]
|
||||
|
||||
@@ -110,3 +110,21 @@ async def test_rate_limit_respects_suggested_retry_after(slept):
|
||||
assert await generate_with_retry(llm, "p") == "ok"
|
||||
# min(8 + 2, 60) = 10
|
||||
assert slept == [10.0]
|
||||
|
||||
|
||||
async def test_tells_the_ui_when_the_next_attempt_starts(slept):
|
||||
import asyncio
|
||||
|
||||
from app.application.import_status import reset_status_queue, set_status_queue
|
||||
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
token = set_status_queue(queue)
|
||||
try:
|
||||
llm = FakeLLM([LLMProviderError("Erreur Mistral (ReadError) : ReadError"), "ok"])
|
||||
assert await generate_with_retry(llm, "p") == "ok"
|
||||
finally:
|
||||
reset_status_queue(token)
|
||||
messages = [queue.get_nowait() for _ in range(queue.qsize())]
|
||||
assert "nouvel essai dans 3s" in messages[0]
|
||||
# Sans ce second message, « nouvel essai dans 3s » restait affiché pendant tout l'essai suivant.
|
||||
assert messages[1] == "Nouvel essai en cours (tentative 2/3)…"
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.rules_translation import (
|
||||
RulesTranslator, detect_language, other_languages, split_markdown, unique_titles,
|
||||
)
|
||||
|
||||
|
||||
class EchoLLM:
|
||||
"""Traduit « en majuscules » et garde trace des prompts reçus."""
|
||||
|
||||
def __init__(self, titles_json: str = '{"titles": {}}') -> None:
|
||||
self.prompts: list[str] = []
|
||||
self._titles_json = titles_json
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
if "Traduis ces titres" in prompt:
|
||||
return self._titles_json
|
||||
return prompt.split("Extrait :\n", 1)[1].upper()
|
||||
|
||||
|
||||
def test_detect_language():
|
||||
assert detect_language("Le joueur lance les dés et la partie est terminée pour vous.") == "fr"
|
||||
assert detect_language("The player rolls the dice and the game is over for you.") == "en"
|
||||
assert detect_language("", default="en") == "en"
|
||||
assert other_languages("fr") == ["en"]
|
||||
assert other_languages("en") == ["fr"]
|
||||
|
||||
|
||||
def test_split_markdown_keeps_short_text_and_cuts_at_paragraphs():
|
||||
assert split_markdown("court") == ["court"]
|
||||
text = "\n\n".join(["a" * 40] * 10)
|
||||
chunks = split_markdown(text, max_chars=100)
|
||||
assert all(len(c) <= 100 for c in chunks)
|
||||
assert "".join(chunks).replace("\n", "") == text.replace("\n", "")
|
||||
|
||||
|
||||
def test_split_markdown_cuts_a_giant_paragraph():
|
||||
chunks = split_markdown("x" * 250, max_chars=100)
|
||||
assert [len(c) for c in chunks] == [100, 100, 50]
|
||||
|
||||
|
||||
async def test_translate_content_keeps_names_instruction_and_joins_chunks():
|
||||
llm = EchoLLM()
|
||||
out = await RulesTranslator(llm).translate_content("## Combat\n\nChaque round.", "fr", "en")
|
||||
assert out == "## COMBAT\n\nCHAQUE ROUND."
|
||||
assert "noms propres" in llm.prompts[0]
|
||||
assert "de la langue « français » vers la langue « anglais »" in llm.prompts[0]
|
||||
|
||||
|
||||
async def test_translate_titles_falls_back_to_the_original_title():
|
||||
llm = EchoLLM('{"titles": {"Combat": "Fighting"}}')
|
||||
out = await RulesTranslator(llm).translate_titles(["Combat", "Magie"], "fr", "en")
|
||||
assert out == {"Combat": "Fighting", "Magie": "Magie"}
|
||||
|
||||
|
||||
def test_unique_titles_avoids_collisions():
|
||||
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
||||
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
|
||||
+1
-26
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>1.0.3</version>
|
||||
<version>1.6.2-beta</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
@@ -137,31 +137,6 @@
|
||||
<version>5.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Nimbus JOSE+JWT — verification des JWT Ed25519 (EdDSA) emis par le relais
|
||||
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle.
|
||||
>= 10.0.2 : corrige CVE-2025-53864 (DoS par JSON profondement imbrique
|
||||
dans le claim set — surface critique : JWT colle par l'utilisateur). -->
|
||||
<dependency>
|
||||
<groupId>com.nimbusds</groupId>
|
||||
<artifactId>nimbus-jose-jwt</artifactId>
|
||||
<version>10.9.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.84</version>
|
||||
</dependency>
|
||||
<!-- Google Tink : runtime requis par com.nimbusds.jose.crypto.Ed25519Verifier
|
||||
(depuis Nimbus 9.x, la verification EdDSA delegue a Tink.subtle.Ed25519Verify).
|
||||
Tink n'est PAS une dependance transitive de nimbus-jose-jwt → il faut
|
||||
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify().
|
||||
>= 1.15 : embarque un protobuf-java corrige (CVE-2024-7254). -->
|
||||
<dependency>
|
||||
<groupId>com.google.crypto.tink</groupId>
|
||||
<artifactId>tink</artifactId>
|
||||
<version>1.21.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif :
|
||||
compatible distribution bureau locale via jpackage). Sert l'export PDF
|
||||
d'une campagne (livret). -->
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class CampaignContentSearchService {
|
||||
private final CampaignContentSearchRepository repository;
|
||||
|
||||
public CampaignContentSearchService(CampaignContentSearchRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public List<CampaignContentHit> search(String query) {
|
||||
String value = query == null ? "" : query.strip();
|
||||
return value.length() < 2 ? List.of() : repository.searchByName(value);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.loremind.application.campaigncontext;
|
||||
import com.loremind.application.playcontext.PlaythroughService;
|
||||
import com.loremind.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,86 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
|
||||
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* IA des méthodes guidées (Mentor d'écriture) : propose des réponses aux questions d'une
|
||||
* méthode à partir de l'idée de départ du MJ et de la campagne. Rien n'est enregistré : le
|
||||
* front remplit les champs vides et le MJ relit, corrige ou relance.
|
||||
*
|
||||
* <p>Garde-fous : nombre de questions et longueur des textes bornés (le prompt reste
|
||||
* raisonnable) ; en retour, seules les clés demandées sont gardées, et une question à choix
|
||||
* n'accepte qu'une des valeurs proposées.</p>
|
||||
*/
|
||||
@Service
|
||||
public class GuidedAssistService {
|
||||
|
||||
static final int MAX_QUESTIONS = 80;
|
||||
static final int MAX_TEXT = 4_000;
|
||||
|
||||
private final GuidedMethodAssistant assistant;
|
||||
private final CampaignContextFormatter contextFormatter;
|
||||
|
||||
public GuidedAssistService(GuidedMethodAssistant assistant, CampaignContextFormatter contextFormatter) {
|
||||
this.assistant = assistant;
|
||||
this.contextFormatter = contextFormatter;
|
||||
}
|
||||
|
||||
/** Demande à proposer des réponses. @throws IllegalArgumentException aucune question valide */
|
||||
public Map<String, String> suggest(String campaignId, String methodName, String principle, String idea,
|
||||
List<Question> questions, Map<String, String> existing) {
|
||||
List<Question> valid = questions == null ? List.of() : questions.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.filter(q -> q.key() != null && !q.key().isBlank())
|
||||
.limit(MAX_QUESTIONS)
|
||||
.toList();
|
||||
if (valid.isEmpty()) {
|
||||
throw new IllegalArgumentException("Aucune question à laquelle répondre.");
|
||||
}
|
||||
Map<String, String> answers = assistant.answer(cap(methodName), cap(principle), cap(idea),
|
||||
contextFormatter.format(campaignId), valid, capAll(existing));
|
||||
return keepValid(answers, valid);
|
||||
}
|
||||
|
||||
/** Clés demandées uniquement, valeurs non vides ; choix limités aux valeurs proposées. */
|
||||
static Map<String, String> keepValid(Map<String, String> answers, List<Question> questions) {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
if (answers == null) return out;
|
||||
Map<String, Question> byKey = questions.stream()
|
||||
.collect(Collectors.toMap(Question::key, q -> q, (a, b) -> a, LinkedHashMap::new));
|
||||
for (Map.Entry<String, String> e : answers.entrySet()) {
|
||||
Question q = byKey.get(e.getKey());
|
||||
String value = e.getValue() == null ? "" : e.getValue().trim();
|
||||
if (q == null || value.isEmpty()) continue;
|
||||
if (q.options() != null && !q.options().isEmpty()) {
|
||||
Set<String> allowed = q.options().stream().map(Choice::value).collect(Collectors.toSet());
|
||||
if (!allowed.contains(value)) continue;
|
||||
}
|
||||
out.put(q.key(), cap(value));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, String> capAll(Map<String, String> existing) {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
if (existing == null) return out;
|
||||
existing.forEach((k, v) -> {
|
||||
if (k != null && v != null && !v.isBlank()) out.put(k, cap(v.trim()));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String cap(String s) {
|
||||
if (s == null) return "";
|
||||
return s.length() > MAX_TEXT ? s.substring(0, MAX_TEXT) : s;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
|
||||
import java.util.List;
|
||||
@@ -20,6 +21,9 @@ import java.util.List;
|
||||
* @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,
|
||||
@@ -27,10 +31,44 @@ public record GuidedSkeleton(
|
||||
ChapterSpec chapter,
|
||||
List<SceneSpec> scenes,
|
||||
boolean linkSequentially,
|
||||
String linkLabel
|
||||
String linkLabel,
|
||||
List<LinkSpec> links,
|
||||
ClockSpec clock
|
||||
) {
|
||||
|
||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||
/** 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(
|
||||
@@ -38,7 +76,14 @@ public record GuidedSkeleton(
|
||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
||||
}
|
||||
|
||||
/** Ce qui a été créé, pour que le front ouvre directement le chapitre. */
|
||||
public record Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+69
-9
@@ -10,6 +10,10 @@ 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;
|
||||
|
||||
@@ -33,19 +37,25 @@ public class GuidedSkeletonService {
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,17 +65,19 @@ public class GuidedSkeletonService {
|
||||
@Transactional
|
||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||
validate(skeleton);
|
||||
List<GuidedSkeleton.SceneSpec> specs = skeleton.scenes().stream()
|
||||
.filter(s -> s != null && !isBlank(s.name()))
|
||||
.toList();
|
||||
|
||||
String arcId = resolveArc(campaignId, skeleton);
|
||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||
|
||||
// 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 : specs) {
|
||||
scenes.add(sceneService.createScene(Scene.builder()
|
||||
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))
|
||||
@@ -75,14 +87,61 @@ public class GuidedSkeletonService {
|
||||
.enemies(blankToNull(spec.enemies()))
|
||||
.chapterId(chapter.getId())
|
||||
.order(order++)
|
||||
.build()));
|
||||
.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());
|
||||
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) {
|
||||
@@ -132,6 +191,7 @@ public class GuidedSkeletonService {
|
||||
.description(blankToNull(spec.description()))
|
||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||
.gmNotes(blankToNull(spec.gmNotes()))
|
||||
.arcId(arcId)
|
||||
.order(nextOrder)
|
||||
.build());
|
||||
|
||||
@@ -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) */ }
|
||||
|
||||
+216
-10
@@ -4,6 +4,9 @@ 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;
|
||||
@@ -11,14 +14,21 @@ 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;
|
||||
@@ -44,8 +54,16 @@ public class WritingReviewService {
|
||||
|
||||
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
|
||||
static final int CORRIDOR_MIN_SCENES = 3;
|
||||
/** WRITE-003 : nombre minimal de chemins menant à une révélation (en deçà : un seul chemin). */
|
||||
static final int REVELATION_MIN_INCOMING = 2;
|
||||
/** WRITE-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). */
|
||||
@@ -76,17 +94,20 @@ public class WritingReviewService {
|
||||
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) {
|
||||
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. */
|
||||
@@ -107,6 +128,11 @@ public class WritingReviewService {
|
||||
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()))) {
|
||||
@@ -126,6 +152,7 @@ public class WritingReviewService {
|
||||
for (Scene scene : scenes) {
|
||||
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||
}
|
||||
reviewGraph(arc, chapter, scenes, treeRemarks);
|
||||
if (!scenes.isEmpty()) {
|
||||
lastChapterScenes = scenes;
|
||||
}
|
||||
@@ -148,6 +175,7 @@ public class WritingReviewService {
|
||||
|
||||
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
|
||||
remarks.addAll(treeRemarks);
|
||||
remarks.addAll(reviewNpcs(campaignId));
|
||||
return new WritingReviewReport(campaignId, remarks);
|
||||
}
|
||||
|
||||
@@ -175,6 +203,14 @@ public class WritingReviewService {
|
||||
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) {}
|
||||
@@ -215,6 +251,142 @@ public class WritingReviewService {
|
||||
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. */
|
||||
@@ -241,14 +413,21 @@ public class WritingReviewService {
|
||||
List<WritingRemark> out) {
|
||||
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||
long incoming = chapterScenes.stream()
|
||||
List<Scene> sources = chapterScenes.stream()
|
||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||
.flatMap(s -> s.getBranches().stream().map(SceneBranch::targetSceneId).distinct())
|
||||
.filter(scene.getId()::equals)
|
||||
.count();
|
||||
if (incoming < REVELATION_MIN_INCOMING) {
|
||||
.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(incoming))));
|
||||
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()))));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,7 +449,8 @@ public class WritingReviewService {
|
||||
|
||||
/** 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())) {
|
||||
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()));
|
||||
}
|
||||
@@ -288,8 +468,34 @@ public class WritingReviewService {
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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())
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.loremind.application.licensing;
|
||||
package com.loremind.application.channel;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
+6
-2
@@ -1,6 +1,7 @@
|
||||
package com.loremind.application.gamesystemcontext;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||
@@ -36,9 +37,11 @@ public class GameSystemContextBuilder {
|
||||
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
|
||||
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
private final CurrentLanguage currentLanguage;
|
||||
|
||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
|
||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository, CurrentLanguage currentLanguage) {
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
this.currentLanguage = currentLanguage;
|
||||
}
|
||||
|
||||
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
||||
@@ -48,7 +51,8 @@ public class GameSystemContextBuilder {
|
||||
}
|
||||
|
||||
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
||||
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown());
|
||||
// Règles dans la langue de l'interface (repli sur l'autre version si celle-ci est vide).
|
||||
Map<String, String> allSections = parseH2Sections(gs.rulesFor(currentLanguage.get()));
|
||||
Map<String, String> filtered = filterByIntent(allSections, intent);
|
||||
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ public class GameSystemService {
|
||||
String name,
|
||||
String description,
|
||||
String rulesMarkdown,
|
||||
String rulesMarkdownEn,
|
||||
List<TemplateField> characterTemplate,
|
||||
List<TemplateField> npcTemplate,
|
||||
List<TemplateField> enemyTemplate,
|
||||
@@ -72,6 +73,7 @@ public class GameSystemService {
|
||||
.name(data.name())
|
||||
.description(data.description())
|
||||
.rulesMarkdown(data.rulesMarkdown())
|
||||
.rulesMarkdownEn(data.rulesMarkdownEn())
|
||||
.foundryActorType(normalize(data.foundryActorType()))
|
||||
.author(normalize(data.author()))
|
||||
.isPublic(data.isPublic())
|
||||
@@ -96,6 +98,7 @@ public class GameSystemService {
|
||||
existing.setName(data.name());
|
||||
existing.setDescription(data.description());
|
||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||
existing.setRulesMarkdownEn(data.rulesMarkdownEn());
|
||||
existing.replaceCharacterTemplate(data.characterTemplate());
|
||||
existing.replaceNpcTemplate(data.npcTemplate());
|
||||
existing.replaceEnemyTemplate(data.enemyTemplate());
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
package com.loremind.application.licensing;
|
||||
|
||||
import com.loremind.domain.licensing.License;
|
||||
import com.loremind.domain.licensing.LicenseClaims;
|
||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
||||
import com.loremind.domain.licensing.LicenseStatus;
|
||||
import com.loremind.domain.licensing.RegistryCredentials;
|
||||
import com.loremind.domain.licensing.ports.JwtVerifier;
|
||||
import com.loremind.domain.licensing.ports.LicenseRelay;
|
||||
import com.loremind.domain.licensing.ports.LicenseRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Service application pour la gestion de la licence Patreon.
|
||||
* <p>
|
||||
* Responsabilites :
|
||||
* <ul>
|
||||
* <li>Installer un nouveau JWT recu du relais (apres OAuth utilisateur)</li>
|
||||
* <li>Calculer le {@link LicenseStatus} courant en respectant la grace period</li>
|
||||
* <li>Renouveler le JWT avant expiration en appelant le relais</li>
|
||||
* <li>Activer/desactiver le toggle "canal beta" cote utilisateur</li>
|
||||
* <li>Distribuer les credentials registry pour le pull beta</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Service
|
||||
public class LicenseService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(LicenseService.class);
|
||||
|
||||
private final LicenseRepository repository;
|
||||
private final JwtVerifier jwtVerifier;
|
||||
private final LicenseRelay relay;
|
||||
private final long gracePeriodSeconds;
|
||||
private final long refreshBeforeExpirySeconds;
|
||||
private final boolean licensingEnabled;
|
||||
|
||||
public LicenseService(
|
||||
LicenseRepository repository,
|
||||
JwtVerifier jwtVerifier,
|
||||
LicenseRelay relay,
|
||||
@Value("${licensing.grace-period-days:14}") int gracePeriodDays,
|
||||
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays,
|
||||
@Value("${licensing.enabled:true}") boolean licensingEnabled) {
|
||||
this.repository = repository;
|
||||
this.jwtVerifier = jwtVerifier;
|
||||
this.relay = relay;
|
||||
this.gracePeriodSeconds = gracePeriodDays * 86_400L;
|
||||
this.refreshBeforeExpirySeconds = refreshBeforeExpiryDays * 86_400L;
|
||||
this.licensingEnabled = licensingEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true si le licensing Patreon est actif : il faut a la fois que la
|
||||
* feature soit activee ({@code licensing.enabled}, faux en mode
|
||||
* bureau/local ou le gating par image Docker n'a aucun sens) ET que
|
||||
* le verifier soit configure (cle publique presente). Faux => l'UI
|
||||
* masque toute la section Patreon, le daemon de refresh est no-op,
|
||||
* et le canal beta est desactive.
|
||||
*/
|
||||
public boolean isLicensingEnabled() {
|
||||
return licensingEnabled && jwtVerifier.isConfigured();
|
||||
}
|
||||
|
||||
/**
|
||||
* Genere ou retourne l'instance_id stable de cette installation.
|
||||
* Stocke dans la licence elle-meme. Si pas de licence, en cree un volatil
|
||||
* (sera persiste a la prochaine connexion).
|
||||
*/
|
||||
public String getOrCreateInstanceId() {
|
||||
return repository.findCurrent()
|
||||
.map(License::getInstanceId)
|
||||
.orElseGet(() -> "li-" + UUID.randomUUID());
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit l'URL OAuth pour ouvrir dans le navigateur de l'utilisateur.
|
||||
*/
|
||||
public String buildConnectUrl() {
|
||||
return relay.buildConnectUrl(getOrCreateInstanceId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Installe un JWT recu du relais (l'utilisateur l'a colle dans l'UI ou
|
||||
* recu via deep-link). Verifie la signature, extrait les claims, persiste.
|
||||
*/
|
||||
public LicenseSnapshot installToken(String rawJwt) throws InstallException {
|
||||
if (!jwtVerifier.isConfigured()) {
|
||||
throw new InstallException("Licensing feature not enabled (no public key configured)");
|
||||
}
|
||||
LicenseClaims claims;
|
||||
try {
|
||||
claims = jwtVerifier.verify(rawJwt);
|
||||
} catch (JwtVerifier.JwtVerificationException e) {
|
||||
throw new InstallException("Invalid JWT: " + e.getMessage());
|
||||
}
|
||||
|
||||
Instant now = Instant.now();
|
||||
if (claims.expiresAt().isBefore(now)) {
|
||||
throw new InstallException("JWT already expired");
|
||||
}
|
||||
|
||||
Optional<License> existing = repository.findCurrent();
|
||||
License toSave = License.builder()
|
||||
.id("current")
|
||||
.rawJwt(rawJwt)
|
||||
.patreonUserId(claims.subject())
|
||||
.tierId(claims.tierId())
|
||||
.instanceId(claims.instanceId())
|
||||
.issuedAt(claims.issuedAt())
|
||||
.expiresAt(claims.expiresAt())
|
||||
.lastRefreshAttemptAt(now)
|
||||
.lastRefreshSucceeded(true)
|
||||
// Au premier install, on active le canal beta par defaut.
|
||||
// Sur reinstall apres deconnexion, on respecte la valeur precedente.
|
||||
.betaChannelEnabled(existing.map(License::isBetaChannelEnabled).orElse(true))
|
||||
.createdAt(existing.map(License::getCreatedAt).orElse(now))
|
||||
.build();
|
||||
|
||||
License saved = repository.save(toSave);
|
||||
log.info("Patreon license installed for user={} tier={} expires={}",
|
||||
saved.getPatreonUserId(), saved.getTierId(), saved.getExpiresAt());
|
||||
return snapshotOf(saved, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Etat courant de la licence pour exposition UI / decision technique.
|
||||
*/
|
||||
public LicenseSnapshot getCurrentSnapshot() {
|
||||
return repository.findCurrent()
|
||||
.map(l -> snapshotOf(l, Instant.now()))
|
||||
.orElseGet(LicenseSnapshot::none);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime la licence (deconnexion volontaire de Patreon par l'utilisateur).
|
||||
*/
|
||||
public void disconnect() {
|
||||
repository.deleteCurrent();
|
||||
log.info("Patreon license removed (user disconnect)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Active ou desactive le canal beta. Necessite une licence valide ou en grace.
|
||||
*/
|
||||
public LicenseSnapshot setBetaChannelEnabled(boolean enabled) {
|
||||
License current = repository.findCurrent()
|
||||
.orElseThrow(() -> new IllegalStateException("No license installed"));
|
||||
current.setBetaChannelEnabled(enabled);
|
||||
License saved = repository.save(current);
|
||||
return snapshotOf(saved, Instant.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tente un refresh si la licence est proche de l'expiration. Idempotent.
|
||||
* Appele par le daemon planifie + manuellement via l'UI ("Reessayer").
|
||||
*/
|
||||
public void refreshIfNeeded() {
|
||||
Optional<License> opt = repository.findCurrent();
|
||||
if (opt.isEmpty()) return;
|
||||
License current = opt.get();
|
||||
Instant now = Instant.now();
|
||||
long secondsUntilExpiry = Duration.between(now, current.getExpiresAt()).getSeconds();
|
||||
if (secondsUntilExpiry > refreshBeforeExpirySeconds) {
|
||||
return;
|
||||
}
|
||||
doRefresh(current, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Force un refresh immediat (bouton UI "Reessayer maintenant").
|
||||
*/
|
||||
public void forceRefresh() {
|
||||
repository.findCurrent().ifPresent(license -> doRefresh(license, Instant.now()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tente le refresh aupres du relais et persiste le resultat (succes ou echec) sur
|
||||
* la licence. Le succes/echec est lu depuis {@code lastRefreshSucceeded}, pas
|
||||
* depuis un retour de methode : le tentative est deja actee cote persistance.
|
||||
*/
|
||||
private void doRefresh(License current, Instant now) {
|
||||
log.info("Refreshing Patreon license (current expires {})", current.getExpiresAt());
|
||||
try {
|
||||
String newJwt = relay.refreshToken(current.getRawJwt());
|
||||
LicenseClaims claims = jwtVerifier.verify(newJwt);
|
||||
|
||||
current.setRawJwt(newJwt);
|
||||
current.setIssuedAt(claims.issuedAt());
|
||||
current.setExpiresAt(claims.expiresAt());
|
||||
current.setTierId(claims.tierId());
|
||||
current.setLastRefreshAttemptAt(now);
|
||||
current.setLastRefreshSucceeded(true);
|
||||
repository.save(current);
|
||||
log.info("License refreshed successfully (new expiry {})", claims.expiresAt());
|
||||
} catch (LicenseRelay.RelayException e) {
|
||||
current.setLastRefreshAttemptAt(now);
|
||||
current.setLastRefreshSucceeded(false);
|
||||
repository.save(current);
|
||||
if (e.getKind() == LicenseRelay.RelayErrorKind.REJECTED) {
|
||||
log.warn("Relay rejected refresh ({}): tier may have been cancelled", e.getMessage());
|
||||
} else {
|
||||
log.warn("Relay refresh transient failure ({}): {}", e.getKind(), e.getMessage());
|
||||
}
|
||||
} catch (JwtVerifier.JwtVerificationException e) {
|
||||
current.setLastRefreshAttemptAt(now);
|
||||
current.setLastRefreshSucceeded(false);
|
||||
repository.save(current);
|
||||
log.error("Relay returned a JWT that fails verification: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recupere les credentials registry pour pull du canal beta.
|
||||
* @return empty si pas de licence valide ou relais en echec
|
||||
*/
|
||||
public Optional<RegistryCredentials> fetchRegistryCredentials() {
|
||||
LicenseSnapshot snap = getCurrentSnapshot();
|
||||
if (snap.status() != LicenseStatus.VALID && snap.status() != LicenseStatus.GRACE) {
|
||||
return Optional.empty();
|
||||
}
|
||||
License current = repository.findCurrent().orElse(null);
|
||||
if (current == null) return Optional.empty();
|
||||
try {
|
||||
return Optional.of(relay.fetchRegistryCredentials(current.getRawJwt()));
|
||||
} catch (LicenseRelay.RelayException e) {
|
||||
log.warn("Cannot fetch registry credentials ({}): {}", e.getKind(), e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private LicenseSnapshot snapshotOf(License l, Instant now) {
|
||||
LicenseStatus status = computeStatus(l, now);
|
||||
return new LicenseSnapshot(
|
||||
status,
|
||||
l.getPatreonUserId(),
|
||||
l.getTierId(),
|
||||
l.getInstanceId(),
|
||||
l.getExpiresAt(),
|
||||
l.getLastRefreshAttemptAt(),
|
||||
l.isLastRefreshSucceeded(),
|
||||
l.isBetaChannelEnabled()
|
||||
);
|
||||
}
|
||||
|
||||
private LicenseStatus computeStatus(License l, Instant now) {
|
||||
if (l.getExpiresAt() == null) return LicenseStatus.NONE;
|
||||
if (now.isBefore(l.getExpiresAt())) return LicenseStatus.VALID;
|
||||
long secondsPastExpiry = Duration.between(l.getExpiresAt(), now).getSeconds();
|
||||
if (secondsPastExpiry <= gracePeriodSeconds) return LicenseStatus.GRACE;
|
||||
return LicenseStatus.EXPIRED;
|
||||
}
|
||||
|
||||
public static class InstallException extends Exception {
|
||||
public InstallException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,13 @@ import java.util.Locale;
|
||||
* @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,
|
||||
@@ -23,7 +29,12 @@ public record NetworkReadiness(
|
||||
List<String> publicNetworks,
|
||||
boolean firewallAllowed,
|
||||
boolean firewallBlocked,
|
||||
String program
|
||||
List<String> thirdPartyFirewalls,
|
||||
String program,
|
||||
String platform,
|
||||
String linuxFirewall,
|
||||
Boolean portOpen,
|
||||
String fixCommand
|
||||
) {
|
||||
|
||||
static final String PUBLIC = "Public";
|
||||
@@ -31,7 +42,10 @@ public record NetworkReadiness(
|
||||
|
||||
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
|
||||
if (snapshot == null || !snapshot.supported()) {
|
||||
return new NetworkReadiness(false, false, List.of(), false, false, null);
|
||||
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);
|
||||
@@ -46,8 +60,31 @@ public record NetworkReadiness(
|
||||
// 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();
|
||||
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, snapshot.program());
|
||||
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) ? */
|
||||
|
||||
@@ -216,6 +216,11 @@ public class RemoteAccessService {
|
||||
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();
|
||||
|
||||
@@ -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
@@ -0,0 +1,38 @@
|
||||
package com.loremind.domain.campaigncontext.ports;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Port de sortie (Mentor d'écriture) : demande à l'IA de proposer des réponses aux
|
||||
* questions d'une méthode guidée à partir de l'idée de départ du MJ. Implémenté par un
|
||||
* client du Brain. One-shot ; rien n'est enregistré (le MJ relit et corrige dans l'assistant).
|
||||
*/
|
||||
public interface GuidedMethodAssistant {
|
||||
|
||||
/** Choix possible d'une question à choix : valeur technique + libellé lisible. */
|
||||
record Choice(String value, String label) {}
|
||||
|
||||
/**
|
||||
* Une question de la méthode, décrite par le front (libellés dans la langue du MJ).
|
||||
*
|
||||
* @param key clé de réponse (ex. {@code node1.name})
|
||||
* @param label libellé de la question
|
||||
* @param hint aide (exemple de réponse attendue), optionnelle
|
||||
* @param step titre de l'étape, optionnel
|
||||
* @param options choix possibles (vide pour une question libre)
|
||||
*/
|
||||
record Question(String key, String label, String hint, String step, List<Choice> options) {}
|
||||
|
||||
/**
|
||||
* @param methodName nom de la méthode (« Enquête en nœuds »…)
|
||||
* @param principle principe de la méthode, suivi du rôle de chaque étape (comme dans l'assistant manuel)
|
||||
* @param idea idée de départ du MJ (peut être vide)
|
||||
* @param context contexte de la campagne (nom, description, système)
|
||||
* @param questions questions auxquelles répondre
|
||||
* @param existing réponses déjà écrites par le MJ (à respecter)
|
||||
* @return une réponse proposée par clé (clés demandées uniquement)
|
||||
*/
|
||||
Map<String, String> answer(String methodName, String principle, String idea, String context,
|
||||
List<Question> questions, Map<String, String> existing);
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
/**
|
||||
|
||||
@@ -35,6 +35,9 @@ public class GameSystem {
|
||||
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||
private String rulesMarkdown;
|
||||
|
||||
/** Version anglaise des règles ({@code rulesMarkdown} = version française). Nullable. */
|
||||
private String rulesMarkdownEn;
|
||||
|
||||
/**
|
||||
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
|
||||
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
|
||||
@@ -161,4 +164,15 @@ public class GameSystem {
|
||||
if (a == null || b == null) return a == null && b == null;
|
||||
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/**
|
||||
* Règles dans la langue demandée ({@code en} → anglais, sinon français), avec repli sur
|
||||
* l'autre version si celle-ci est vide : un système importé dans une seule langue reste lisible.
|
||||
*/
|
||||
public String rulesFor(String language) {
|
||||
boolean english = "en".equalsIgnoreCase(language);
|
||||
String preferred = english ? rulesMarkdownEn : rulesMarkdown;
|
||||
String fallback = english ? rulesMarkdown : rulesMarkdownEn;
|
||||
return preferred != null && !preferred.isBlank() ? preferred : fallback;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,5 +16,14 @@ import java.util.Map;
|
||||
public record RulesImportResult(
|
||||
Map<String, String> sections,
|
||||
int pageCount,
|
||||
int ocrPageCount) {
|
||||
int ocrPageCount,
|
||||
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
|
||||
Map<String, Map<String, String>> sectionsByLanguage,
|
||||
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
|
||||
String sourceLanguage) {
|
||||
|
||||
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
|
||||
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
|
||||
this(sections, pageCount, ocrPageCount, Map.of(), null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.loremind.domain.licensing;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Licence Patreon installee dans cette instance LoreMind.
|
||||
* <p>
|
||||
* Singleton (une seule licence par instance, identifiee logiquement par
|
||||
* {@code id = "current"}). Contient le JWT brut emis par le relais OAuth
|
||||
* + les claims extraits a la verification, plus l'etat operationnel
|
||||
* (derniere tentative de refresh, succes/echec).
|
||||
* <p>
|
||||
* <b>Note securite :</b> {@link #rawJwt} est stocke tel quel ; sa signature
|
||||
* Ed25519 est verifiee a chaque lecture. Pas besoin de chiffrement au repos
|
||||
* supplementaire — un attaquant qui a acces a la base a deja l'instance,
|
||||
* et le JWT ne donne aucun pouvoir au-dela du canal beta de cette instance.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class License {
|
||||
|
||||
private String id;
|
||||
|
||||
private String rawJwt;
|
||||
|
||||
private String patreonUserId;
|
||||
|
||||
private String tierId;
|
||||
|
||||
private String instanceId;
|
||||
|
||||
private Instant issuedAt;
|
||||
|
||||
private Instant expiresAt;
|
||||
|
||||
private Instant lastRefreshAttemptAt;
|
||||
|
||||
private boolean lastRefreshSucceeded;
|
||||
|
||||
private boolean betaChannelEnabled;
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
private Instant updatedAt;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.loremind.domain.licensing;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Claims extraits d'un JWT licence apres verification de signature.
|
||||
* Immuable.
|
||||
*/
|
||||
public record LicenseClaims(
|
||||
String subject,
|
||||
String tierId,
|
||||
String instanceId,
|
||||
Instant issuedAt,
|
||||
Instant expiresAt
|
||||
) {}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.loremind.domain.licensing;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Vue immuable de la licence pour exposition vers les couches superieures.
|
||||
* Decouple le domaine du DTO web et permet de calculer le {@link LicenseStatus}
|
||||
* a un instant donne sans muter l'entite.
|
||||
*/
|
||||
public record LicenseSnapshot(
|
||||
LicenseStatus status,
|
||||
String patreonUserId,
|
||||
String tierId,
|
||||
String instanceId,
|
||||
Instant expiresAt,
|
||||
Instant lastRefreshAttemptAt,
|
||||
boolean lastRefreshSucceeded,
|
||||
boolean betaChannelEnabled
|
||||
) {
|
||||
public static LicenseSnapshot none() {
|
||||
return new LicenseSnapshot(LicenseStatus.NONE, null, null, null, null, null, false, false);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.loremind.domain.licensing;
|
||||
|
||||
/**
|
||||
* Etat operationnel de la licence vis-a-vis de l'acces beta.
|
||||
* <p>
|
||||
* Calcule a partir de la presence de licence + son JWT exp + grace period.
|
||||
* <ul>
|
||||
* <li>{@link #NONE} : aucune licence installee</li>
|
||||
* <li>{@link #VALID} : JWT non expire, acces beta autorise</li>
|
||||
* <li>{@link #GRACE} : JWT expire mais dans la periode de tolerance ;
|
||||
* acces beta toujours autorise, l'UI doit avertir</li>
|
||||
* <li>{@link #EXPIRED} : au-dela de la grace period, acces beta refuse</li>
|
||||
* <li>{@link #UNVERIFIABLE} : JWT impossible a verifier (cle publique manquante,
|
||||
* signature invalide, claims malformes) — traite comme NONE pour la securite</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum LicenseStatus {
|
||||
NONE,
|
||||
VALID,
|
||||
GRACE,
|
||||
EXPIRED,
|
||||
UNVERIFIABLE
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.loremind.domain.licensing;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Credentials de pull pour un registry Docker, distribues par le relais
|
||||
* apres verification d'un JWT licence valide.
|
||||
* <p>
|
||||
* {@code expiresAt} peut etre {@code null} si le credential est statique
|
||||
* (cas du PAT GHCR partage en MVP) ; sinon, l'instance doit re-demander
|
||||
* de nouveaux credentials avant cette date.
|
||||
*/
|
||||
public record RegistryCredentials(
|
||||
String registry,
|
||||
String username,
|
||||
String password,
|
||||
Instant expiresAt
|
||||
) {}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.loremind.domain.licensing.ports;
|
||||
|
||||
import com.loremind.domain.licensing.RegistryCredentials;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Port de sortie : ecriture du docker config.json partage avec Watchtower.
|
||||
* <p>
|
||||
* Le fichier sert a Watchtower pour s'authentifier au registry prive (GHCR)
|
||||
* lors du pull des images du canal beta. Volume Docker {@code docker-config}
|
||||
* monte sur Core (en ecriture) et sur Watchtower (en lecture, via la variable
|
||||
* {@code DOCKER_CONFIG}).
|
||||
*/
|
||||
public interface DockerConfigWriter {
|
||||
|
||||
/**
|
||||
* Ecrit ou met a jour les credentials pour le registry indique.
|
||||
* Cree le fichier s'il n'existe pas, conserve les autres registries deja
|
||||
* presents (en theorie : aucun, mais defensif).
|
||||
*/
|
||||
void writeCredentials(RegistryCredentials credentials) throws IOException;
|
||||
|
||||
/**
|
||||
* Supprime le fichier de credentials. Appele quand la licence est invalidee
|
||||
* ou que le toggle beta passe a OFF.
|
||||
*/
|
||||
void clear() throws IOException;
|
||||
|
||||
/**
|
||||
* @return true si le fichier de creds existe actuellement.
|
||||
*/
|
||||
boolean isPresent();
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.loremind.domain.licensing.ports;
|
||||
|
||||
import com.loremind.domain.licensing.LicenseClaims;
|
||||
|
||||
/**
|
||||
* Port de sortie : verification de signature et extraction des claims
|
||||
* d'un JWT emis par le relais.
|
||||
* <p>
|
||||
* Implemente cote infrastructure avec la cle publique Ed25519 embarquee
|
||||
* (SPKI PEM via configuration {@code licensing.jwt.public-key}).
|
||||
*/
|
||||
public interface JwtVerifier {
|
||||
|
||||
/**
|
||||
* Verifie la signature, l'issuer, l'audience et l'expiration du JWT.
|
||||
* @throws JwtVerificationException si la signature est invalide ou les claims malformes
|
||||
*/
|
||||
LicenseClaims verify(String rawJwt) throws JwtVerificationException;
|
||||
|
||||
/**
|
||||
* @return true si la cle publique est configuree et utilisable.
|
||||
* Permet a l'application de masquer la feature licensing si pas configuree.
|
||||
*/
|
||||
boolean isConfigured();
|
||||
|
||||
class JwtVerificationException extends Exception {
|
||||
public JwtVerificationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
public JwtVerificationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.loremind.domain.licensing.ports;
|
||||
|
||||
import com.loremind.domain.licensing.RegistryCredentials;
|
||||
|
||||
/**
|
||||
* Port de sortie vers le service relais OAuth Patreon.
|
||||
* Encapsule les appels HTTP : refresh JWT et fetch registry credentials.
|
||||
*/
|
||||
public interface LicenseRelay {
|
||||
|
||||
/**
|
||||
* Demande au relais l'URL OAuth a ouvrir pour connecter le compte Patreon.
|
||||
*/
|
||||
String buildConnectUrl(String instanceId);
|
||||
|
||||
/**
|
||||
* Demande au relais de renouveler un JWT existant. Le relais re-verifie
|
||||
* le tier Patreon de l'utilisateur ; renvoie un nouveau JWT si toujours
|
||||
* actif, ou leve {@link RelayException} sinon.
|
||||
*/
|
||||
String refreshToken(String currentJwt) throws RelayException;
|
||||
|
||||
/**
|
||||
* Demande au relais les credentials de pull du registry beta.
|
||||
*/
|
||||
RegistryCredentials fetchRegistryCredentials(String currentJwt) throws RelayException;
|
||||
|
||||
/**
|
||||
* Erreurs distinctes emises par le relais. Permet au service application
|
||||
* de differencier "tier expire" (action utilisateur) de "relais down"
|
||||
* (action transitoire, garde la grace period).
|
||||
*/
|
||||
class RelayException extends Exception {
|
||||
private final RelayErrorKind kind;
|
||||
|
||||
public RelayException(RelayErrorKind kind, String message) {
|
||||
super(message);
|
||||
this.kind = kind;
|
||||
}
|
||||
|
||||
public RelayException(RelayErrorKind kind, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.kind = kind;
|
||||
}
|
||||
|
||||
public RelayErrorKind getKind() {
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
|
||||
enum RelayErrorKind {
|
||||
/** Le relais est joignable mais refuse : tier non actif, JWT trop ancien, etc. */
|
||||
REJECTED,
|
||||
/** Le relais a renvoye un JWT mais il est invalide / non parsable. */
|
||||
BAD_RESPONSE,
|
||||
/** Le relais est injoignable / 5xx / timeout. */
|
||||
TRANSIENT
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.loremind.domain.licensing.ports;
|
||||
|
||||
import com.loremind.domain.licensing.License;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Port de sortie pour la persistance de la licence installee.
|
||||
* <p>
|
||||
* Une seule licence par instance ({@code id = "current"} par convention).
|
||||
*/
|
||||
public interface LicenseRepository {
|
||||
|
||||
Optional<License> findCurrent();
|
||||
|
||||
License save(License license);
|
||||
|
||||
void deleteCurrent();
|
||||
}
|
||||
@@ -11,8 +11,31 @@ import java.util.List;
|
||||
* @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) {
|
||||
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) {}
|
||||
@@ -25,6 +48,6 @@ public record NetworkSnapshot(boolean supported, String program, List<Network> n
|
||||
public record FirewallRule(String action, String profile, String enabled) {}
|
||||
|
||||
public static NetworkSnapshot unsupported() {
|
||||
return new NetworkSnapshot(false, null, List.of(), List.of());
|
||||
return new NetworkSnapshot(false, null, List.of(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ 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. */
|
||||
NetworkSnapshot inspect();
|
||||
/** 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
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.loremind.domain.shared.ports;
|
||||
|
||||
/**
|
||||
* Port : langue de l'interface de l'utilisateur courant ({@code fr} ou {@code en}), pour les
|
||||
* contenus qui existent en deux langues (règles d'un système de jeu). Implémenté côté web.
|
||||
*/
|
||||
public interface CurrentLanguage {
|
||||
|
||||
/** Code court de la langue courante ({@code fr} par défaut). */
|
||||
String get();
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
@Value("${brain.base-url}") String baseUrl,
|
||||
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
|
||||
@Value("${brain.paths.import-campaign:/import/campaign/stream}") String importCampaignStreamPath) {
|
||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
|
||||
this.sse = new BrainSseImportSupport(objectMapper);
|
||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||
this.importCampaignStreamPath = importCampaignStreamPath;
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestClientResponseException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Adapter de sortie : propositions de réponses aux méthodes guidées via le Brain
|
||||
* ({@code POST /generate/guided-answers}, one-shot). La langue de l'interface est relayée par
|
||||
* l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
|
||||
*/
|
||||
@Component
|
||||
public class BrainGuidedAnswersClient implements GuidedMethodAssistant {
|
||||
|
||||
private static final String PATH = "/generate/guided-answers";
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
private final String baseUrl;
|
||||
|
||||
public BrainGuidedAnswersClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> answer(String methodName, String principle, String idea, String context,
|
||||
List<Question> questions, Map<String, String> existing) {
|
||||
Map<String, Object> req = new LinkedHashMap<>();
|
||||
req.put("method_name", nz(methodName));
|
||||
req.put("method_principle", nz(principle));
|
||||
req.put("idea", nz(idea));
|
||||
req.put("context", nz(context));
|
||||
req.put("fields", toPayload(questions));
|
||||
req.put("existing", existing == null ? Map.of() : existing);
|
||||
return parse(call(req));
|
||||
}
|
||||
|
||||
static List<Map<String, Object>> toPayload(List<Question> questions) {
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Question q : questions) {
|
||||
Map<String, Object> f = new LinkedHashMap<>();
|
||||
f.put("key", q.key());
|
||||
f.put("label", nz(q.label()).isEmpty() ? q.key() : q.label());
|
||||
f.put("hint", nz(q.hint()));
|
||||
f.put("step", nz(q.step()));
|
||||
List<Map<String, String>> options = new ArrayList<>();
|
||||
if (q.options() != null) {
|
||||
for (Choice c : q.options()) {
|
||||
if (c != null && c.value() != null) options.add(Map.of("value", c.value(), "label", nz(c.label())));
|
||||
}
|
||||
}
|
||||
f.put("options", options);
|
||||
out.add(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> call(Map<String, Object> req) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Map<String, Object> resp;
|
||||
try {
|
||||
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
|
||||
} catch (ResourceAccessException e) {
|
||||
throw new NarrativeAssistException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||
} catch (RestClientResponseException e) {
|
||||
throw new NarrativeAssistException(
|
||||
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||
} catch (Exception e) {
|
||||
throw new NarrativeAssistException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||
}
|
||||
if (resp == null) throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
|
||||
return resp;
|
||||
}
|
||||
|
||||
private static Map<String, String> parse(Map<String, Object> resp) {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
if (resp.get("answers") instanceof Map<?, ?> m) {
|
||||
m.forEach((k, v) -> {
|
||||
if (k != null && v != null) out.put(k.toString(), v.toString());
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String nz(String s) {
|
||||
return s == null ? "" : s;
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
@Value("${brain.paths.import-rules:/import/rules}") String importRulesPath,
|
||||
@Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
||||
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
|
||||
this.sse = new BrainSseImportSupport(objectMapper);
|
||||
this.baseUrl = baseUrl;
|
||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||
@@ -106,7 +106,9 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
return new RulesImportResult(
|
||||
Map.copyOf(response.getSections()),
|
||||
response.getPageCount(),
|
||||
response.getOcrPageCount());
|
||||
response.getOcrPageCount(),
|
||||
response.getSectionsByLanguage() != null ? response.getSectionsByLanguage() : Map.of(),
|
||||
response.getSourceLanguage());
|
||||
} catch (ResourceAccessException e) {
|
||||
throw new RulesImportException(
|
||||
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
||||
@@ -218,12 +220,23 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
callbacks.onDone().accept(new RulesImportResult(
|
||||
toStringMap(node.path("sections")),
|
||||
node.path("page_count").asInt(),
|
||||
node.path("ocr_page_count").asInt()));
|
||||
node.path("ocr_page_count").asInt(),
|
||||
toLanguageMap(node.path("sections_by_language")),
|
||||
node.path("source_language").asText(null)));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers -------------------------------------------------------------
|
||||
|
||||
/** {code langue → sections} : règles en deux langues (vide si le Brain ne les fournit pas). */
|
||||
private Map<String, Map<String, String>> toLanguageMap(JsonNode node) {
|
||||
Map<String, Map<String, String>> out = new java.util.LinkedHashMap<>();
|
||||
if (node != null && node.isObject()) {
|
||||
node.fields().forEachRemaining(e -> out.put(e.getKey(), toStringMap(e.getValue())));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<String> toStringList(JsonNode array) {
|
||||
List<String> out = new ArrayList<>();
|
||||
if (array != null && array.isArray()) {
|
||||
|
||||
@@ -23,4 +23,11 @@ class BrainRulesImportResponse {
|
||||
|
||||
@JsonProperty("ocr_page_count")
|
||||
private int ocrPageCount;
|
||||
|
||||
/** Règles en deux langues : {code langue → sections} (absent d'un Brain antérieur). */
|
||||
@JsonProperty("sections_by_language")
|
||||
private Map<String, Map<String, String>> sectionsByLanguage;
|
||||
|
||||
@JsonProperty("source_language")
|
||||
private String sourceLanguage;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.http.codec.ServerSentEvent;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.time.Duration;
|
||||
@@ -25,6 +26,21 @@ final class BrainSseImportSupport {
|
||||
/** Champ JSON standard des events SSE du Brain portant un message lisible. */
|
||||
private static final String MESSAGE_FIELD = "message";
|
||||
|
||||
/**
|
||||
* Taille max d'UN évènement SSE. L'évènement {@code done} porte tout le résultat de
|
||||
* l'import (règles d'un livre entier, en deux langues ; arbre complet d'une campagne) :
|
||||
* la limite par défaut de WebClient (256 Ko) faisait échouer l'import au tout dernier
|
||||
* moment (DataBufferLimitException), après des minutes d'analyse.
|
||||
*/
|
||||
static final int MAX_EVENT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** WebClient d'import : évènements volumineux acceptés (voir {@link #MAX_EVENT_BYTES}). */
|
||||
static WebClient importWebClient(WebClient.Builder builder, String baseUrl) {
|
||||
return builder.baseUrl(baseUrl)
|
||||
.codecs(c -> c.defaultCodecs().maxInMemorySize(MAX_EVENT_BYTES))
|
||||
.build();
|
||||
}
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
BrainSseImportSupport(ObjectMapper objectMapper) {
|
||||
|
||||
@@ -3,7 +3,9 @@ package com.loremind.infrastructure.desktop;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.file.Files;
|
||||
@@ -102,14 +104,20 @@ public final class DesktopSingleInstance {
|
||||
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
||||
}
|
||||
|
||||
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */
|
||||
/**
|
||||
* Ouvre le navigateur par defaut sur une URL quelconque : API standard de Java
|
||||
* (ShellExecute sous Windows), sinon commande du systeme. Plus de {@code rundll32
|
||||
* url.dll} : outil Windows tres detourne par les logiciels malveillants, que des
|
||||
* antivirus signalaient (Avast « IDP.Generic ») quand un programme peu connu le lance.
|
||||
*/
|
||||
public static void openUrl(String url) {
|
||||
if (browseWithJava(url)) return;
|
||||
try {
|
||||
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||
ProcessBuilder pb;
|
||||
if (os.contains("win")) {
|
||||
// rundll32 : ouverture d'URL fiable sans dependance graphique Java.
|
||||
pb = new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", url);
|
||||
// « start » de cmd ; le "" est le titre de fenetre attendu avant l'URL.
|
||||
pb = new ProcessBuilder("cmd", "/c", "start", "", url);
|
||||
} else if (os.contains("mac")) {
|
||||
pb = new ProcessBuilder("open", url);
|
||||
} else {
|
||||
@@ -122,6 +130,20 @@ public final class DesktopSingleInstance {
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link Desktop#browse} si disponible (jamais en headless) ; false = repli sur une commande. */
|
||||
private static boolean browseWithJava(String url) {
|
||||
try {
|
||||
if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
|
||||
return false;
|
||||
}
|
||||
Desktop.getDesktop().browse(URI.create(url));
|
||||
return true;
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.debug("[Desktop] Ouverture via Desktop.browse impossible ({}), repli sur une commande.", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */
|
||||
public static void openFolder(Path dir) {
|
||||
try {
|
||||
|
||||
@@ -31,6 +31,9 @@ import java.util.Optional;
|
||||
* <p>
|
||||
* {@code /releases/latest} ne renvoie que les releases stables (pas les
|
||||
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
|
||||
* Une version BETA (le canal beta est libre : chaque beta est publiee en
|
||||
* prerelease GitHub) interroge la liste complete des releases, pour etre
|
||||
* prevenue de la beta suivante comme de la version stable qui la remplace.
|
||||
*/
|
||||
@Service
|
||||
@Profile("local")
|
||||
@@ -73,17 +76,18 @@ public class DesktopUpdateService {
|
||||
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
|
||||
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
|
||||
|
||||
boolean beta = isPrerelease(currentVersion);
|
||||
ResponseEntity<JsonNode> resp = http.exchange(
|
||||
releasesApiUrl, HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
||||
JsonNode body = resp.getBody();
|
||||
if (body == null || body.path("tag_name").isMissingNode()) {
|
||||
beta ? allReleasesUrl(releasesApiUrl) : releasesApiUrl,
|
||||
HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
||||
JsonNode release = beta ? newestRelease(resp.getBody()) : resp.getBody();
|
||||
if (release == null || release.path("tag_name").isMissingNode()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String tag = body.path("tag_name").asText(""); // ex: "v0.15.0"
|
||||
String releaseUrl = body.path("html_url").asText(null); // page de la release
|
||||
String latest = tag.startsWith("v") ? tag.substring(1) : tag;
|
||||
String latest = version(release); // ex: "0.15.0"
|
||||
String releaseUrl = release.path("html_url").asText(null); // page de la release
|
||||
|
||||
if (!latest.isBlank() && compareSemver(currentVersion, latest) < 0) {
|
||||
if (!latest.isBlank() && (beta ? compareVersions(currentVersion, latest) : compareSemver(currentVersion, latest)) < 0) {
|
||||
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
|
||||
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
|
||||
}
|
||||
@@ -99,6 +103,66 @@ public class DesktopUpdateService {
|
||||
/** Infos d'une mise a jour disponible. */
|
||||
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
|
||||
|
||||
static boolean isPrerelease(String version) {
|
||||
return version.split("\\+", 2)[0].contains("-");
|
||||
}
|
||||
|
||||
/** {@code .../releases/latest} -> {@code .../releases?per_page=30} (prereleases incluses). */
|
||||
static String allReleasesUrl(String latestUrl) {
|
||||
String base = latestUrl.endsWith("/latest") ? latestUrl.substring(0, latestUrl.length() - "/latest".length()) : latestUrl;
|
||||
return base + "?per_page=30";
|
||||
}
|
||||
|
||||
private static String version(JsonNode release) {
|
||||
String tag = release.path("tag_name").asText("");
|
||||
return tag.startsWith("v") ? tag.substring(1) : tag;
|
||||
}
|
||||
|
||||
/** Release publiee la plus recente (stable ou beta), brouillons exclus. */
|
||||
@Nullable
|
||||
static JsonNode newestRelease(@Nullable JsonNode releases) {
|
||||
if (releases == null || !releases.isArray()) return null;
|
||||
JsonNode best = null;
|
||||
for (JsonNode r : releases) {
|
||||
if (r.path("draft").asBoolean(false) || version(r).isBlank()) continue;
|
||||
if (best == null || compareVersions(version(best), version(r)) < 0) best = r;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Comme {@link #compareSemver} mais tient compte du suffixe : a version egale,
|
||||
* la stable passe devant la beta (1.5.0-beta < 1.5.0), et deux betas se
|
||||
* comparent par leur numero (1.5.0-beta < 1.5.0-beta.2 < 1.5.0-beta.10).
|
||||
*/
|
||||
static int compareVersions(String a, String b) {
|
||||
int cmp = compareSemver(a, b);
|
||||
if (cmp != 0) return cmp;
|
||||
String sa = suffix(a);
|
||||
String sb = suffix(b);
|
||||
if (sa.isEmpty() || sb.isEmpty()) return Boolean.compare(sa.isEmpty(), sb.isEmpty());
|
||||
return compareSuffixes(sa, sb);
|
||||
}
|
||||
|
||||
private static String suffix(String version) {
|
||||
String noBuild = version.split("\\+", 2)[0];
|
||||
int dash = noBuild.indexOf('-');
|
||||
return dash < 0 ? "" : noBuild.substring(dash + 1);
|
||||
}
|
||||
|
||||
/** Compare des suffixes en traitant les nombres comme des nombres (beta.10 > beta.2). */
|
||||
private static int compareSuffixes(String a, String b) {
|
||||
String[] pa = a.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
|
||||
String[] pb = b.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
|
||||
for (int i = 0; i < Math.min(pa.length, pb.length); i++) {
|
||||
boolean na = Character.isDigit(pa[i].charAt(0));
|
||||
boolean nb = Character.isDigit(pb[i].charAt(0));
|
||||
int cmp = na && nb ? Long.compare(Long.parseLong(pa[i]), Long.parseLong(pb[i])) : pa[i].compareTo(pb[i]);
|
||||
if (cmp != 0) return cmp;
|
||||
}
|
||||
return Integer.compare(pa.length, pb.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
|
||||
* @return <0 si a<b, 0 si egales, >0 si a>b.
|
||||
|
||||
@@ -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, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
-26
@@ -6,8 +6,6 @@ import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -28,12 +26,19 @@ import java.util.concurrent.TimeUnit;
|
||||
* 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.
|
||||
* Les scripts sont passés EN CLAIR ({@code -Command}, une ligne) : un script encodé
|
||||
* ({@code -EncodedCommand}) accompagné de {@code -ExecutionPolicy Bypass} est la signature
|
||||
* typique des logiciels malveillants, et faisait réagir des antivirus (Avast « IDP.Generic »).
|
||||
* La politique d'exécution ne concerne que les fichiers .ps1 : inutile de la contourner.
|
||||
* La ligne de commande Windows est en UTF-16 : accents et noms de réseau passent tels quels.
|
||||
* Seule exception : le script relancé EN ADMINISTRATEUR (bouton « Autoriser »), encodé car
|
||||
* {@code Start-Process -ArgumentList} ne sait pas transmettre un script avec espaces et
|
||||
* guillemets ; il ne s'exécute que sur clic de l'utilisateur, derrière la confirmation UAC.
|
||||
* 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.
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WindowsHostNetworkAccess.class);
|
||||
@@ -52,7 +57,7 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
}
|
||||
|
||||
@Override
|
||||
public NetworkSnapshot inspect() {
|
||||
public NetworkSnapshot inspect(int port) {
|
||||
String program = currentProgram();
|
||||
if (!isWindows() || program == null) return NetworkSnapshot.unsupported();
|
||||
try {
|
||||
@@ -71,14 +76,8 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
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();
|
||||
int exit = runPowerShell(elevationScript(program), 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);
|
||||
@@ -105,19 +104,37 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
|
||||
// --- Scripts --------------------------------------------------------------------------
|
||||
|
||||
/** Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris). */
|
||||
/**
|
||||
* Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris).
|
||||
* Une seule ligne d'instructions séparées par « ; » : elle est passée telle quelle à {@code -Command}.
|
||||
*/
|
||||
static String inspectScript(String program) {
|
||||
return "$ErrorActionPreference = 'SilentlyContinue'\n"
|
||||
return "$ErrorActionPreference = 'SilentlyContinue'; "
|
||||
// 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"
|
||||
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
|
||||
+ "$p = '" + psQuote(program) + "'; "
|
||||
+ "$nets = @(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
|
||||
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } }); "
|
||||
+ "$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"
|
||||
+ "[pscustomobject]@{ networks = $nets; rules = $rules } | ConvertTo-Json -Depth 4 -Compress\n";
|
||||
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } }); "
|
||||
// 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' }); "
|
||||
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
|
||||
+ "ConvertTo-Json -Depth 4 -Compress";
|
||||
}
|
||||
|
||||
/**
|
||||
* Relance PowerShell EN ADMINISTRATEUR (confirmation UAC) avec {@link #allowScript}, et
|
||||
* renvoie son code de sortie ; refus de l'UAC → {@value #EXIT_CANCELLED}. Une seule ligne.
|
||||
*/
|
||||
static String elevationScript(String program) {
|
||||
return "try { $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
|
||||
+ "-ArgumentList @('-NoProfile','-NonInteractive','-EncodedCommand','"
|
||||
+ encode(allowScript(program)) + "'); exit $p.ExitCode } catch { exit " + EXIT_CANCELLED + " }";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,7 +167,11 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
for (JsonNode r : array(root.path("rules"))) {
|
||||
rules.add(new NetworkSnapshot.FirewallRule(text(r, "action"), text(r, "profile"), text(r, "enabled")));
|
||||
}
|
||||
return new NetworkSnapshot(true, program, networks, rules);
|
||||
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. */
|
||||
@@ -176,9 +197,9 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
|
||||
private record Result(int exitCode, String output) {}
|
||||
|
||||
/** {@code script} : une ligne, sans guillemet double (chaînes PowerShell entre apostrophes). */
|
||||
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
|
||||
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive",
|
||||
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
|
||||
Process process = new ProcessBuilder(command(script))
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
||||
.start();
|
||||
process.getOutputStream().close();
|
||||
@@ -197,6 +218,14 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
return new Result(process.exitValue(), output.join());
|
||||
}
|
||||
|
||||
/** Ligne de commande PowerShell : script en clair, ni encodage ni contournement de politique. */
|
||||
static List<String> command(String script) {
|
||||
if (script.indexOf('"') >= 0 || script.indexOf('\n') >= 0) {
|
||||
throw new IllegalArgumentException("Script PowerShell : une ligne, sans guillemet double");
|
||||
}
|
||||
return List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script);
|
||||
}
|
||||
|
||||
private static boolean isWindows() {
|
||||
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
|
||||
}
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
package com.loremind.infrastructure.licensing;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.loremind.domain.licensing.RegistryCredentials;
|
||||
import com.loremind.domain.licensing.ports.DockerConfigWriter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Implementation : ecriture du fichier {@code config.json} au format Docker
|
||||
* standard, dans un volume partage avec Watchtower.
|
||||
* <p>
|
||||
* Format produit :
|
||||
* <pre>{@code
|
||||
* {
|
||||
* "auths": {
|
||||
* "ghcr.io": {
|
||||
* "auth": "<base64(username:password)>"
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
@Component
|
||||
public class FileDockerConfigWriter implements DockerConfigWriter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FileDockerConfigWriter.class);
|
||||
|
||||
/** Cle racine du config.json Docker portant les registres authentifies. */
|
||||
private static final String AUTHS_KEY = "auths";
|
||||
|
||||
private final Path configPath;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public FileDockerConfigWriter(
|
||||
@Value("${licensing.docker-config-path:/shared/docker/config.json}") String pathStr) {
|
||||
this.configPath = Path.of(pathStr);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeCredentials(RegistryCredentials credentials) throws IOException {
|
||||
ensureParentDirectory();
|
||||
|
||||
ObjectNode root;
|
||||
if (Files.exists(configPath)) {
|
||||
try {
|
||||
JsonNode existing = mapper.readTree(configPath.toFile());
|
||||
root = existing.isObject() ? (ObjectNode) existing : mapper.createObjectNode();
|
||||
} catch (IOException e) {
|
||||
log.warn("Existing docker config unreadable, overwriting: {}", e.getMessage());
|
||||
root = mapper.createObjectNode();
|
||||
}
|
||||
} else {
|
||||
root = mapper.createObjectNode();
|
||||
}
|
||||
|
||||
ObjectNode auths = root.has(AUTHS_KEY) && root.get(AUTHS_KEY).isObject()
|
||||
? (ObjectNode) root.get(AUTHS_KEY)
|
||||
: root.putObject(AUTHS_KEY);
|
||||
|
||||
String b64 = Base64.getEncoder().encodeToString(
|
||||
(credentials.username() + ":" + credentials.password()).getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
ObjectNode entry = mapper.createObjectNode();
|
||||
entry.put("auth", b64);
|
||||
auths.set(credentials.registry(), entry);
|
||||
|
||||
Files.writeString(configPath, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root),
|
||||
StandardCharsets.UTF_8);
|
||||
applyRestrictivePermissions();
|
||||
log.info("Docker config written at {} for registry {}", configPath, credentials.registry());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() throws IOException {
|
||||
if (Files.exists(configPath)) {
|
||||
Files.delete(configPath);
|
||||
log.info("Docker config cleared at {}", configPath);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPresent() {
|
||||
return Files.exists(configPath);
|
||||
}
|
||||
|
||||
private void ensureParentDirectory() throws IOException {
|
||||
Path parent = configPath.getParent();
|
||||
if (parent != null && !Files.exists(parent)) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
}
|
||||
|
||||
/** 0600 sur POSIX. Sur Windows (dev), no-op silencieux. */
|
||||
private void applyRestrictivePermissions() {
|
||||
try {
|
||||
Files.setPosixFilePermissions(configPath, PosixFilePermissions.fromString("rw-------"));
|
||||
} catch (UnsupportedOperationException | IOException e) {
|
||||
// Windows / FS qui ne supporte pas POSIX => ignore (le conteneur tourne sous Linux en prod)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
package com.loremind.infrastructure.licensing;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.loremind.domain.licensing.RegistryCredentials;
|
||||
import com.loremind.domain.licensing.ports.LicenseRelay;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Client HTTP du relais OAuth Patreon (deploye sur Cloudflare Workers).
|
||||
* Voir {@code relay/} pour le code du relais.
|
||||
*/
|
||||
@Component
|
||||
public class HttpLicenseRelay implements LicenseRelay {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(HttpLicenseRelay.class);
|
||||
|
||||
private final RestTemplate http;
|
||||
private final String baseUrl;
|
||||
|
||||
public HttpLicenseRelay(
|
||||
RestTemplateBuilder builder,
|
||||
@Value("${licensing.relay.base-url:}") String baseUrl) {
|
||||
this.http = builder
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.readTimeout(Duration.ofSeconds(15))
|
||||
.build();
|
||||
this.baseUrl = stripTrailingSlash(baseUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String buildConnectUrl(String instanceId) {
|
||||
if (baseUrl.isBlank()) {
|
||||
throw new IllegalStateException("Licensing relay base URL not configured");
|
||||
}
|
||||
String encoded = URLEncoder.encode(instanceId, StandardCharsets.UTF_8);
|
||||
return baseUrl + "/oauth/start?instance_id=" + encoded;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String refreshToken(String currentJwt) throws RelayException {
|
||||
if (baseUrl.isBlank()) {
|
||||
throw new RelayException(RelayErrorKind.TRANSIENT, "relay not configured");
|
||||
}
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Map<String, String> body = Map.of("jwt", currentJwt);
|
||||
|
||||
ResponseEntity<JsonNode> resp;
|
||||
try {
|
||||
resp = http.exchange(
|
||||
baseUrl + "/token/refresh",
|
||||
HttpMethod.POST,
|
||||
new HttpEntity<>(body, headers),
|
||||
JsonNode.class);
|
||||
} catch (HttpClientErrorException e) {
|
||||
throw new RelayException(RelayErrorKind.REJECTED,
|
||||
"relay rejected refresh: " + e.getStatusCode() + " " + e.getStatusText());
|
||||
} catch (HttpServerErrorException e) {
|
||||
throw new RelayException(RelayErrorKind.TRANSIENT,
|
||||
"relay 5xx: " + e.getStatusCode());
|
||||
} catch (RestClientException e) {
|
||||
throw new RelayException(RelayErrorKind.TRANSIENT, "relay unreachable: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
JsonNode payload = resp.getBody();
|
||||
if (payload == null || !payload.hasNonNull("jwt")) {
|
||||
throw new RelayException(RelayErrorKind.BAD_RESPONSE, "missing jwt in refresh response");
|
||||
}
|
||||
return payload.get("jwt").asText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RegistryCredentials fetchRegistryCredentials(String currentJwt) throws RelayException {
|
||||
if (baseUrl.isBlank()) {
|
||||
throw new RelayException(RelayErrorKind.TRANSIENT, "relay not configured");
|
||||
}
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Map<String, String> body = Map.of("jwt", currentJwt);
|
||||
|
||||
ResponseEntity<JsonNode> resp;
|
||||
try {
|
||||
resp = http.exchange(
|
||||
baseUrl + "/registry/credentials",
|
||||
HttpMethod.POST,
|
||||
new HttpEntity<>(body, headers),
|
||||
JsonNode.class);
|
||||
} catch (HttpClientErrorException e) {
|
||||
throw new RelayException(RelayErrorKind.REJECTED,
|
||||
"relay rejected creds: " + e.getStatusCode() + " " + e.getStatusText());
|
||||
} catch (HttpServerErrorException e) {
|
||||
throw new RelayException(RelayErrorKind.TRANSIENT,
|
||||
"relay 5xx: " + e.getStatusCode());
|
||||
} catch (RestClientException e) {
|
||||
throw new RelayException(RelayErrorKind.TRANSIENT, "relay unreachable: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
JsonNode payload = resp.getBody();
|
||||
if (payload == null
|
||||
|| !payload.hasNonNull("registry")
|
||||
|| !payload.hasNonNull("username")
|
||||
|| !payload.hasNonNull("password")) {
|
||||
throw new RelayException(RelayErrorKind.BAD_RESPONSE, "incomplete credentials response");
|
||||
}
|
||||
Instant expiresAt = null;
|
||||
if (payload.hasNonNull("expires_at")) {
|
||||
try {
|
||||
expiresAt = Instant.parse(payload.get("expires_at").asText());
|
||||
} catch (Exception e) {
|
||||
log.warn("Cannot parse expires_at from relay creds response: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
return new RegistryCredentials(
|
||||
payload.get("registry").asText(),
|
||||
payload.get("username").asText(),
|
||||
payload.get("password").asText(),
|
||||
expiresAt
|
||||
);
|
||||
}
|
||||
|
||||
private static String stripTrailingSlash(String s) {
|
||||
if (s == null) return "";
|
||||
String v = s.trim();
|
||||
if (v.endsWith("/")) v = v.substring(0, v.length() - 1);
|
||||
return v;
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package com.loremind.infrastructure.licensing;
|
||||
|
||||
import com.loremind.application.licensing.LicenseService;
|
||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
||||
import com.loremind.domain.licensing.LicenseStatus;
|
||||
import com.loremind.domain.licensing.RegistryCredentials;
|
||||
import com.loremind.domain.licensing.ports.DockerConfigWriter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Daemon planifie qui :
|
||||
* <ul>
|
||||
* <li>renouvelle le JWT licence via le relais avant expiration (J-2)</li>
|
||||
* <li>met a jour les credentials registry GHCR pour Watchtower
|
||||
* (volume partage docker-config) tant que le canal beta est ON</li>
|
||||
* <li>nettoie les credentials si la licence est invalidee ou le toggle OFF</li>
|
||||
* </ul>
|
||||
* Idempotent : peut tourner toutes les 6h sans risque, fait du no-op
|
||||
* la plupart du temps.
|
||||
*/
|
||||
@Component
|
||||
// Desactivable (ex: tests) : sans cette propriete (prod), le daemon tourne.
|
||||
@ConditionalOnProperty(name = "licensing.refresh.enabled", matchIfMissing = true)
|
||||
public class LicenseRefreshDaemon {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(LicenseRefreshDaemon.class);
|
||||
|
||||
/** 6 heures entre chaque cycle. Suffisant pour rattraper un J-2 sans surcharger. */
|
||||
private static final long FIXED_DELAY_MS = 6L * 60L * 60L * 1000L;
|
||||
/** Premier run apres 30s pour laisser le contexte Spring se stabiliser. */
|
||||
private static final long INITIAL_DELAY_MS = 30_000L;
|
||||
|
||||
private final LicenseService licenseService;
|
||||
private final DockerConfigWriter dockerConfigWriter;
|
||||
|
||||
public LicenseRefreshDaemon(LicenseService licenseService,
|
||||
DockerConfigWriter dockerConfigWriter) {
|
||||
this.licenseService = licenseService;
|
||||
this.dockerConfigWriter = dockerConfigWriter;
|
||||
}
|
||||
|
||||
@Scheduled(initialDelay = INITIAL_DELAY_MS, fixedDelay = FIXED_DELAY_MS)
|
||||
public void tick() {
|
||||
if (!licenseService.isLicensingEnabled()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
licenseService.refreshIfNeeded();
|
||||
syncDockerConfig();
|
||||
} catch (Exception e) {
|
||||
log.error("LicenseRefreshDaemon tick failed: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aligne le fichier docker config avec l'etat de la licence et le toggle :
|
||||
* <ul>
|
||||
* <li>VALID/GRACE + beta ON -> ecrit/refresh les creds</li>
|
||||
* <li>tout autre cas -> efface le fichier</li>
|
||||
* </ul>
|
||||
*/
|
||||
private void syncDockerConfig() {
|
||||
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
|
||||
boolean shouldHaveCreds = snap.betaChannelEnabled()
|
||||
&& (snap.status() == LicenseStatus.VALID || snap.status() == LicenseStatus.GRACE);
|
||||
|
||||
if (!shouldHaveCreds) {
|
||||
try {
|
||||
if (dockerConfigWriter.isPresent()) {
|
||||
dockerConfigWriter.clear();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Cannot clear docker config: {}", e.getMessage());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<RegistryCredentials> creds = licenseService.fetchRegistryCredentials();
|
||||
if (creds.isEmpty()) {
|
||||
log.warn("Beta enabled but cannot fetch registry credentials (relay down or rejected)");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
dockerConfigWriter.writeCredentials(creds.get());
|
||||
} catch (IOException e) {
|
||||
log.error("Cannot write docker config: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
package com.loremind.infrastructure.licensing;
|
||||
|
||||
import com.loremind.domain.licensing.LicenseClaims;
|
||||
import com.loremind.domain.licensing.ports.JwtVerifier;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jose.crypto.Ed25519Verifier;
|
||||
import com.nimbusds.jose.jwk.OctetKeyPair;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import org.bouncycastle.asn1.ASN1Primitive;
|
||||
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Verifie les JWT EdDSA/Ed25519 emis par le relais Patreon.
|
||||
* <p>
|
||||
* La cle publique est fournie en PEM SPKI via la propriete
|
||||
* {@code licensing.jwt.public-key} (env {@code LICENSING_JWT_PUBLIC_KEY}).
|
||||
* Si la cle est absente ou invalide, {@link #isConfigured()} retourne false
|
||||
* et {@link #verify} echoue systematiquement — la feature licensing est
|
||||
* desactivee silencieusement.
|
||||
*/
|
||||
@Component
|
||||
public class NimbusJwtVerifier implements JwtVerifier {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(NimbusJwtVerifier.class);
|
||||
|
||||
private final String expectedIssuer;
|
||||
private final String expectedAudience;
|
||||
private final OctetKeyPair publicKey;
|
||||
|
||||
public NimbusJwtVerifier(
|
||||
@Value("${licensing.jwt.public-key:}") String publicKeyPemFromEnv,
|
||||
@Value("${licensing.jwt.expected-issuer:loremind-auth}") String expectedIssuer,
|
||||
@Value("${licensing.jwt.expected-audience:loremind-instance}") String expectedAudience) {
|
||||
this.expectedIssuer = expectedIssuer;
|
||||
this.expectedAudience = expectedAudience;
|
||||
// Strategie : env var en priorite (rotation possible sans rebuild),
|
||||
// sinon ressource classpath embarquee dans le binaire.
|
||||
String pem = (publicKeyPemFromEnv != null && !publicKeyPemFromEnv.isBlank())
|
||||
? publicKeyPemFromEnv
|
||||
: loadEmbeddedKey();
|
||||
this.publicKey = parsePemSpki(pem);
|
||||
if (publicKey == null) {
|
||||
log.info("Licensing JWT verifier disabled (no public key found)");
|
||||
} else {
|
||||
String source = (publicKeyPemFromEnv != null && !publicKeyPemFromEnv.isBlank()) ? "env" : "embedded";
|
||||
log.info("Licensing JWT verifier enabled (issuer={}, audience={}, key source={})",
|
||||
expectedIssuer, expectedAudience, source);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge la cle publique embarquee dans le binaire (resource classpath).
|
||||
* Le fichier est un PEM SPKI standard, fourni a la build pour chaque
|
||||
* release. Si absent, la feature licensing est desactivee.
|
||||
*/
|
||||
private static String loadEmbeddedKey() {
|
||||
ClassPathResource resource = new ClassPathResource("licensing/jwt-public-key.pem");
|
||||
if (!resource.exists()) {
|
||||
return null;
|
||||
}
|
||||
try (InputStream in = resource.getInputStream()) {
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
log.warn("Cannot read embedded JWT public key: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConfigured() {
|
||||
return publicKey != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LicenseClaims verify(String rawJwt) throws JwtVerificationException {
|
||||
ensureConfigured();
|
||||
ensureNotBlank(rawJwt);
|
||||
|
||||
SignedJWT signed = parseJwt(rawJwt);
|
||||
ensureExpectedAlgorithm(signed);
|
||||
verifySignature(signed);
|
||||
|
||||
JWTClaimsSet claims = parseClaims(signed);
|
||||
ensureExpectedIssuer(claims);
|
||||
ensureExpectedAudience(claims);
|
||||
|
||||
return toLicenseClaims(claims);
|
||||
}
|
||||
|
||||
private void ensureConfigured() throws JwtVerificationException {
|
||||
if (publicKey == null) {
|
||||
throw new JwtVerificationException("JWT verifier not configured");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureNotBlank(String rawJwt) throws JwtVerificationException {
|
||||
if (rawJwt == null || rawJwt.isBlank()) {
|
||||
throw new JwtVerificationException("JWT is empty");
|
||||
}
|
||||
}
|
||||
|
||||
private static SignedJWT parseJwt(String rawJwt) throws JwtVerificationException {
|
||||
try {
|
||||
return SignedJWT.parse(rawJwt);
|
||||
} catch (ParseException e) {
|
||||
throw new JwtVerificationException("JWT parse error: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureExpectedAlgorithm(SignedJWT signed) throws JwtVerificationException {
|
||||
JWSAlgorithm alg = signed.getHeader().getAlgorithm();
|
||||
if (!JWSAlgorithm.EdDSA.equals(alg)) {
|
||||
throw new JwtVerificationException("Unexpected JWT algorithm: " + alg);
|
||||
}
|
||||
}
|
||||
|
||||
private void verifySignature(SignedJWT signed) throws JwtVerificationException {
|
||||
try {
|
||||
JWSVerifier verifier = new Ed25519Verifier(publicKey);
|
||||
if (!signed.verify(verifier)) {
|
||||
throw new JwtVerificationException("JWT signature invalid");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new JwtVerificationException("JWT signature verification failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static JWTClaimsSet parseClaims(SignedJWT signed) throws JwtVerificationException {
|
||||
try {
|
||||
return signed.getJWTClaimsSet();
|
||||
} catch (ParseException e) {
|
||||
throw new JwtVerificationException("JWT claims parse error", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureExpectedIssuer(JWTClaimsSet claims) throws JwtVerificationException {
|
||||
if (!expectedIssuer.equals(claims.getIssuer())) {
|
||||
throw new JwtVerificationException("JWT issuer mismatch: " + claims.getIssuer());
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureExpectedAudience(JWTClaimsSet claims) throws JwtVerificationException {
|
||||
if (claims.getAudience() == null || !claims.getAudience().contains(expectedAudience)) {
|
||||
throw new JwtVerificationException("JWT audience mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit les LicenseClaims depuis les claims validés (issuer/audience/signature).
|
||||
* Note : on ne refuse pas un JWT expiré ici. C'est au LicenseService de decider ce
|
||||
* qu'il fait d'un JWT expire (grace period, refresh, etc.). La verification de
|
||||
* signature reste valide tant que la cle existe.
|
||||
*/
|
||||
private static LicenseClaims toLicenseClaims(JWTClaimsSet claims) throws JwtVerificationException {
|
||||
// Nimbus n'expose exp/iat qu'en java.util.Date : converti en Instant SANS variable
|
||||
// Date intermediaire (aucune reference au type legacy dans cette classe).
|
||||
String sub = claims.getSubject();
|
||||
if (claims.getExpirationTime() == null || claims.getIssueTime() == null || sub == null) {
|
||||
throw new JwtVerificationException("JWT missing required claims");
|
||||
}
|
||||
Instant exp = claims.getExpirationTime().toInstant();
|
||||
Instant iat = claims.getIssueTime().toInstant();
|
||||
|
||||
String tierId;
|
||||
String instanceId;
|
||||
try {
|
||||
tierId = claims.getStringClaim("tier_id");
|
||||
instanceId = claims.getStringClaim("instance_id");
|
||||
} catch (ParseException e) {
|
||||
throw new JwtVerificationException("JWT custom claim parse error", e);
|
||||
}
|
||||
if (tierId == null || tierId.isBlank() || instanceId == null || instanceId.isBlank()) {
|
||||
throw new JwtVerificationException("JWT missing tier_id or instance_id");
|
||||
}
|
||||
|
||||
return new LicenseClaims(sub, tierId, instanceId, iat, exp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse une cle publique Ed25519 au format PEM SPKI vers un Nimbus
|
||||
* {@link OctetKeyPair} (forme JWK utilisee pour la verification).
|
||||
*/
|
||||
private static OctetKeyPair parsePemSpki(String pem) {
|
||||
if (pem == null || pem.isBlank()) return null;
|
||||
try {
|
||||
String base64 = pem
|
||||
.replace("-----BEGIN PUBLIC KEY-----", "")
|
||||
.replace("-----END PUBLIC KEY-----", "")
|
||||
.replaceAll("\\s+", "");
|
||||
byte[] der = Base64.getDecoder().decode(base64);
|
||||
SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(der));
|
||||
byte[] keyBytes = spki.getPublicKeyData().getOctets();
|
||||
String x = Base64.getUrlEncoder().withoutPadding().encodeToString(keyBytes);
|
||||
return new OctetKeyPair.Builder(com.nimbusds.jose.jwk.Curve.Ed25519, com.nimbusds.jose.util.Base64URL.from(x))
|
||||
.build();
|
||||
} catch (IOException | IllegalArgumentException e) {
|
||||
log.warn("Cannot parse licensing JWT public key: {}", e.getMessage());
|
||||
return 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());
|
||||
|
||||
+3
@@ -37,6 +37,9 @@ public class GameSystemJpaEntity {
|
||||
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
||||
private String rulesMarkdown;
|
||||
|
||||
@Column(name = "rules_markdown_en", columnDefinition = "TEXT")
|
||||
private String rulesMarkdownEn;
|
||||
|
||||
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
|
||||
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||
@Column(name = "character_template", columnDefinition = "TEXT")
|
||||
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Entite JPA pour la licence Patreon installee.
|
||||
* <p>
|
||||
* Singleton : une seule ligne par instance (id = "current"). Ce design permet
|
||||
* de ne jamais avoir de licence "fantome" en base et de simplifier les queries.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "licenses")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class LicenseJpaEntity {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
@Column(name = "raw_jwt", columnDefinition = "TEXT", nullable = false)
|
||||
private String rawJwt;
|
||||
|
||||
@Column(name = "patreon_user_id", nullable = false)
|
||||
private String patreonUserId;
|
||||
|
||||
@Column(name = "tier_id", nullable = false)
|
||||
private String tierId;
|
||||
|
||||
@Column(name = "instance_id", nullable = false)
|
||||
private String instanceId;
|
||||
|
||||
@Column(name = "issued_at", nullable = false)
|
||||
private Instant issuedAt;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
@Column(name = "last_refresh_attempt_at")
|
||||
private Instant lastRefreshAttemptAt;
|
||||
|
||||
@Column(name = "last_refresh_succeeded", nullable = false)
|
||||
private boolean lastRefreshSucceeded;
|
||||
|
||||
@Column(name = "beta_channel_enabled", nullable = false)
|
||||
private boolean betaChannelEnabled;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
Instant now = Instant.now();
|
||||
if (createdAt == null) createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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
@@ -1,9 +0,0 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.LicenseJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface LicenseJpaRepository extends JpaRepository<LicenseJpaEntity, String> {
|
||||
}
|
||||
+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
@@ -60,6 +60,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||
.name(e.getName())
|
||||
.description(e.getDescription())
|
||||
.rulesMarkdown(e.getRulesMarkdown())
|
||||
.rulesMarkdownEn(e.getRulesMarkdownEn())
|
||||
.characterTemplate(e.getCharacterTemplate() != null
|
||||
? new java.util.ArrayList<>(e.getCharacterTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
@@ -84,6 +85,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||
.name(g.getName())
|
||||
.description(g.getDescription())
|
||||
.rulesMarkdown(g.getRulesMarkdown())
|
||||
.rulesMarkdownEn(g.getRulesMarkdownEn())
|
||||
.characterTemplate(g.getCharacterTemplate() != null
|
||||
? new java.util.ArrayList<>(g.getCharacterTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.licensing.License;
|
||||
import com.loremind.domain.licensing.ports.LicenseRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.LicenseJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.LicenseJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class PostgresLicenseRepository implements LicenseRepository {
|
||||
|
||||
static final String CURRENT_ID = "current";
|
||||
|
||||
private final LicenseJpaRepository jpa;
|
||||
|
||||
public PostgresLicenseRepository(LicenseJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<License> findCurrent() {
|
||||
return jpa.findById(CURRENT_ID).map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public License save(License license) {
|
||||
LicenseJpaEntity entity = toEntity(license);
|
||||
if (entity.getCreatedAt() == null) {
|
||||
entity.setCreatedAt(Instant.now());
|
||||
}
|
||||
LicenseJpaEntity saved = jpa.save(entity);
|
||||
return toDomain(saved);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteCurrent() {
|
||||
jpa.deleteById(CURRENT_ID);
|
||||
}
|
||||
|
||||
private License toDomain(LicenseJpaEntity e) {
|
||||
return License.builder()
|
||||
.id(e.getId())
|
||||
.rawJwt(e.getRawJwt())
|
||||
.patreonUserId(e.getPatreonUserId())
|
||||
.tierId(e.getTierId())
|
||||
.instanceId(e.getInstanceId())
|
||||
.issuedAt(e.getIssuedAt())
|
||||
.expiresAt(e.getExpiresAt())
|
||||
.lastRefreshAttemptAt(e.getLastRefreshAttemptAt())
|
||||
.lastRefreshSucceeded(e.isLastRefreshSucceeded())
|
||||
.betaChannelEnabled(e.isBetaChannelEnabled())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.updatedAt(e.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
|
||||
private LicenseJpaEntity toEntity(License l) {
|
||||
return LicenseJpaEntity.builder()
|
||||
.id(CURRENT_ID)
|
||||
.rawJwt(l.getRawJwt())
|
||||
.patreonUserId(l.getPatreonUserId())
|
||||
.tierId(l.getTierId())
|
||||
.instanceId(l.getInstanceId())
|
||||
.issuedAt(l.getIssuedAt())
|
||||
.expiresAt(l.getExpiresAt())
|
||||
.lastRefreshAttemptAt(l.getLastRefreshAttemptAt())
|
||||
.lastRefreshSucceeded(l.isLastRefreshSucceeded())
|
||||
.betaChannelEnabled(l.isBetaChannelEnabled())
|
||||
.createdAt(l.getCreatedAt())
|
||||
.updatedAt(l.getUpdatedAt())
|
||||
.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())
|
||||
|
||||
+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())
|
||||
|
||||
@@ -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());
|
||||
@@ -572,7 +577,8 @@ public class ExportService {
|
||||
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
||||
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
||||
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic());
|
||||
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic(),
|
||||
e.getRulesMarkdownEn());
|
||||
}
|
||||
|
||||
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
||||
@@ -599,7 +605,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 +615,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 +644,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 +656,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) {
|
||||
|
||||
@@ -49,6 +49,7 @@ class LoreContentInserter {
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setRulesMarkdown(d.rulesMarkdown());
|
||||
e.setRulesMarkdownEn(d.rulesMarkdownEn());
|
||||
e.setCharacterTemplate(d.characterTemplate());
|
||||
e.setNpcTemplate(d.npcTemplate());
|
||||
e.setEnemyTemplate(d.enemyTemplate());
|
||||
|
||||
@@ -77,7 +77,9 @@ public record ContentExport(
|
||||
List<TemplateField> enemyTemplate,
|
||||
String foundryActorType,
|
||||
String author,
|
||||
boolean isPublic
|
||||
boolean isPublic,
|
||||
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
|
||||
String rulesMarkdownEn
|
||||
) {}
|
||||
|
||||
public record LoreDto(
|
||||
@@ -128,7 +130,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 +149,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 +202,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 +232,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+620
-164
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();
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.loremind.infrastructure.updates;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Retire les identifiants GHCR laisses par l'ancien canal beta Patreon.
|
||||
*
|
||||
* <p>Jusqu'a la 1.5, le Core ecrivait un {@code config.json} Docker (jeton GHCR recu
|
||||
* du relais Patreon) dans un volume partage avec Watchtower et le switcher. Le canal
|
||||
* beta est desormais libre et ses images publiques : ce jeton ne sert plus, et une
|
||||
* fois revoque il ferait ECHOUER les telechargements (un registry refuse des
|
||||
* identifiants invalides, meme pour une image publique). Le fichier n'a jamais
|
||||
* contenu que ces identifiants : on le supprime au demarrage.
|
||||
*
|
||||
* <p>No-op sur les installations recentes : le docker-compose.yml ne monte plus ce
|
||||
* volume ni ne definit {@code LICENSING_DOCKER_CONFIG_PATH}.
|
||||
*/
|
||||
@Component
|
||||
public class LegacyRegistryCredentialsCleanup implements ApplicationRunner {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(LegacyRegistryCredentialsCleanup.class);
|
||||
|
||||
private final String configPath;
|
||||
|
||||
public LegacyRegistryCredentialsCleanup(@Value("${LICENSING_DOCKER_CONFIG_PATH:}") String configPath) {
|
||||
this.configPath = configPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
cleanup();
|
||||
}
|
||||
|
||||
/** @return true si un ancien fichier d'identifiants a ete supprime */
|
||||
boolean cleanup() {
|
||||
if (configPath == null || configPath.isBlank()) return false;
|
||||
Path file = Path.of(configPath);
|
||||
try {
|
||||
if (Files.deleteIfExists(file)) {
|
||||
log.info("[Updates] Anciens identifiants GHCR du canal beta supprimes ({}).", file);
|
||||
return true;
|
||||
}
|
||||
} catch (IOException | SecurityException e) {
|
||||
log.warn("[Updates] Impossible de supprimer les anciens identifiants GHCR ({}) : {}", file, e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
package com.loremind.infrastructure.updates;
|
||||
|
||||
import com.loremind.application.licensing.LicenseService;
|
||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
||||
import com.loremind.domain.licensing.LicenseStatus;
|
||||
import com.loremind.domain.licensing.RegistryCredentials;
|
||||
import com.loremind.application.channel.ChannelSwitcherService;
|
||||
import com.loremind.application.channel.ChannelSwitcherService.Channel;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -24,10 +22,8 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Detection des mises a jour disponibles + declenchement via Watchtower.
|
||||
@@ -59,8 +55,9 @@ public class UpdateCheckService {
|
||||
private final List<String> images;
|
||||
private final String watchtowerUrl;
|
||||
private final String watchtowerToken;
|
||||
private final String betaRegistry;
|
||||
private final List<String> betaImages;
|
||||
private final LicenseService licenseService;
|
||||
private final ChannelSwitcherService channels;
|
||||
/** Version semver courante du binaire (ex: "0.8.0"). Source de verite. */
|
||||
private final String currentVersion;
|
||||
|
||||
@@ -70,8 +67,9 @@ public class UpdateCheckService {
|
||||
@Value("${update-check.images:}") String imagesCsv,
|
||||
@Value("${update-check.watchtower-url:http://watchtower:8080}") String watchtowerUrl,
|
||||
@Value("${update-check.watchtower-token:}") String watchtowerToken,
|
||||
@Value("${licensing.beta.images:}") String betaImagesCsv,
|
||||
LicenseService licenseService,
|
||||
@Value("${update-check.beta-registry:ghcr.io}") String betaRegistry,
|
||||
@Value("${update-check.beta-images:}") String betaImagesCsv,
|
||||
ChannelSwitcherService channels,
|
||||
@Nullable BuildProperties buildProperties) {
|
||||
this.http = builder
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
@@ -81,8 +79,9 @@ public class UpdateCheckService {
|
||||
this.images = parseImages(imagesCsv);
|
||||
this.watchtowerUrl = watchtowerUrl;
|
||||
this.watchtowerToken = watchtowerToken;
|
||||
this.betaRegistry = normalizeRegistry(betaRegistry);
|
||||
this.betaImages = parseImages(betaImagesCsv);
|
||||
this.licenseService = licenseService;
|
||||
this.channels = channels;
|
||||
this.currentVersion = buildProperties != null ? buildProperties.getVersion() : null;
|
||||
log.info("Update check init - registry={} images={} currentVersion={}",
|
||||
this.registry, this.images, this.currentVersion);
|
||||
@@ -119,33 +118,17 @@ public class UpdateCheckService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifie l'etat du canal beta (images privees GHCR) avec auth basique.
|
||||
* Verifie l'etat du canal beta quand l'instance y tourne. Les images beta sont
|
||||
* publiques (canal libre, plus de licence) : lecture anonyme du registry.
|
||||
*/
|
||||
public BetaStatus checkBeta() {
|
||||
if (!licenseService.isLicensingEnabled()) {
|
||||
return BetaStatus.disabled("licensing-not-configured");
|
||||
if (channels.getCurrentChannel() != Channel.BETA) {
|
||||
return BetaStatus.disabled("not-on-beta-channel");
|
||||
}
|
||||
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
|
||||
if (snap.status() != LicenseStatus.VALID && snap.status() != LicenseStatus.GRACE) {
|
||||
return BetaStatus.disabled("license-" + snap.status().name().toLowerCase());
|
||||
}
|
||||
if (!snap.betaChannelEnabled()) {
|
||||
return BetaStatus.disabled("beta-toggle-off");
|
||||
}
|
||||
if (betaImages.isEmpty()) {
|
||||
if (betaImages.isEmpty() || betaRegistry.isEmpty()) {
|
||||
return BetaStatus.disabled("no-beta-images-configured");
|
||||
}
|
||||
|
||||
Optional<RegistryCredentials> creds = licenseService.fetchRegistryCredentials();
|
||||
if (creds.isEmpty()) {
|
||||
return new BetaStatus(true, false, true, List.of(), Instant.now(), "relay-unavailable");
|
||||
}
|
||||
|
||||
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(
|
||||
(creds.get().username() + ":" + creds.get().password()).getBytes(StandardCharsets.UTF_8));
|
||||
String betaRegistry = normalizeRegistry(creds.get().registry());
|
||||
|
||||
ImagesEvaluation ev = evaluateImages(betaImages, betaRegistry, basicAuth);
|
||||
ImagesEvaluation ev = evaluateImages(betaImages, betaRegistry, null);
|
||||
return new BetaStatus(true, ev.anyUpdate(), ev.anyUnknown(),
|
||||
ev.statuses(), Instant.now(), null);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ import java.util.Map;
|
||||
* </ul>
|
||||
*
|
||||
* <p>Important : ne court-circuite PAS les try/catch locaux des controllers
|
||||
* (ex: LicenseController.install catche InstallException -> 400 lui-meme).
|
||||
* (ex: UpdatesController.switchChannel catche IOException -> 500 lui-meme).
|
||||
* Ce handler n'attrape QUE ce qui a echappe au catch local.
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user