Compare commits
15
Commits
v1.5.0-beta
...
v1.6.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f0766ccbe | ||
|
|
b9020cb46f | ||
|
|
10574ba0c5 | ||
|
|
ace2e486fc | ||
|
|
c008c22e09 | ||
|
|
bf606c23d1 | ||
|
|
1898e8b1ae | ||
|
|
e77ad85be9 | ||
|
|
11939fe39e | ||
|
|
8958822545 | ||
|
|
007bcce8a7 | ||
|
|
a985bbd018 | ||
|
|
1c9ac524db | ||
|
|
abf66733fe | ||
|
|
763219412b |
@@ -47,7 +47,7 @@ jobs:
|
|||||||
|
|
||||||
# Detection du canal :
|
# Detection du canal :
|
||||||
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
|
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
|
||||||
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR prives
|
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR publics
|
||||||
# loremind-beta-<component> ; backup Gitea avec :version)
|
# loremind-beta-<component> ; backup Gitea avec :version)
|
||||||
- name: Extract version & channel
|
- name: Extract version & channel
|
||||||
id: meta
|
id: meta
|
||||||
@@ -74,8 +74,8 @@ jobs:
|
|||||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||||
|
|
||||||
# Build & push canal BETA
|
# Build & push canal BETA
|
||||||
# GHCR : repos prives loremind-beta-<component> (gated par PAT distribue
|
# GHCR : repos PUBLICS loremind-beta-<component> (canal beta libre ;
|
||||||
# via le relais Patreon aux tiers Compagnon).
|
# le switcher bascule IMAGE_NAMESPACE vers ce prefixe).
|
||||||
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne
|
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne
|
||||||
# pas faire upgrader les installs branchees sur Gitea).
|
# pas faire upgrader les installs branchees sur Gitea).
|
||||||
- name: Build & push ${{ matrix.component }} (beta)
|
- name: Build & push ${{ matrix.component }} (beta)
|
||||||
|
|||||||
@@ -12,12 +12,10 @@ name: Desktop installers
|
|||||||
# inclus) pour que le tag declenche ce workflow.
|
# inclus) pour que le tag declenche ce workflow.
|
||||||
#
|
#
|
||||||
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
||||||
# Tag beta vX.Y.Z-beta* -> AUCUNE publication publique. Le .msi est depose en
|
# Tag beta vX.Y.Z-beta* -> GitHub Release PUBLIQUE marquee « pre-release » : le
|
||||||
# ARTEFACT PRIVE du run (telechargeable seulement par
|
# canal beta est libre. /releases/latest l'ignore, donc
|
||||||
# toi via l'onglet Actions) ; tu le joins ensuite a un
|
# seules les installations beta en sont prevenues
|
||||||
# post Patreon reserve a un palier. Patreon = la
|
# (cf. DesktopUpdateService).
|
||||||
# barriere d'acces (equivalent du registry prive +
|
|
||||||
# relais pour les images Docker beta).
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -106,6 +104,10 @@ jobs:
|
|||||||
windows:
|
windows:
|
||||||
needs: tests
|
needs: tests
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
|
# Reprises par le job `publish` (tag de la release, statut pre-release).
|
||||||
|
outputs:
|
||||||
|
tag: ${{ steps.ver.outputs.tag }}
|
||||||
|
isbeta: ${{ steps.ver.outputs.isbeta }}
|
||||||
steps:
|
steps:
|
||||||
# En declenchement manuel, on checkout le TAG correspondant a la version
|
# En declenchement manuel, on checkout le TAG correspondant a la version
|
||||||
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
||||||
@@ -169,33 +171,20 @@ jobs:
|
|||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||||
|
|
||||||
# STABLE uniquement : Release GitHub publique avec le .msi.
|
# Le .msi est passe au job `publish`, seul a creer la release.
|
||||||
# tag_name explicite : en declenchement manuel, github.ref est une branche,
|
- name: Keep installer for the release
|
||||||
# donc on cible le tag derive (la release est attachee au bon tag).
|
|
||||||
- name: Publish installer to GitHub Release (stable)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
tag_name: ${{ steps.ver.outputs.tag }}
|
|
||||||
files: core/target/dist-out/*.msi
|
|
||||||
fail_on_unmatched_files: true
|
|
||||||
generate_release_notes: true
|
|
||||||
|
|
||||||
# BETA uniquement : artefact PRIVE (pas de release publique). A recuperer
|
|
||||||
# via l'onglet Actions puis a joindre a un post Patreon gate par palier.
|
|
||||||
- name: Upload installer as private artifact (beta)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: loremind-beta-${{ steps.ver.outputs.version }}-msi
|
name: installer-windows
|
||||||
path: core/target/dist-out/*.msi
|
path: core/target/dist-out/*.msi
|
||||||
retention-days: 90
|
if-no-files-found: error
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
||||||
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
||||||
# Brain empaquete via python-build-standalone (pas de Python embeddable Linux
|
# Brain empaquete via python-build-standalone (pas de Python embeddable Linux
|
||||||
# officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de
|
# officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de
|
||||||
# publication que windows : stable -> release publique ; beta -> artefact prive.
|
# publication que windows : stable -> release publique ; beta -> pre-release.
|
||||||
linux:
|
linux:
|
||||||
needs: tests
|
needs: tests
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -242,21 +231,40 @@ jobs:
|
|||||||
GITHUB_TOKEN: ${{ github.token }}
|
GITHUB_TOKEN: ${{ github.token }}
|
||||||
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
||||||
|
|
||||||
# STABLE uniquement : attache l'AppImage a la release publique (meme tag que
|
# L'AppImage est passee au job `publish`, seul a creer la release.
|
||||||
# le .msi -> les deux installeurs sur la meme release).
|
- name: Keep AppImage for the release
|
||||||
- name: Publish AppImage to GitHub Release (stable)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
|
||||||
tag_name: ${{ steps.ver.outputs.tag }}
|
|
||||||
files: core/target/dist-out/DM_Loremind*.AppImage
|
|
||||||
fail_on_unmatched_files: true
|
|
||||||
|
|
||||||
# BETA uniquement : artefact PRIVE (pas de release publique).
|
|
||||||
- name: Upload AppImage as private artifact (beta)
|
|
||||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: loremind-beta-${{ steps.ver.outputs.version }}-appimage
|
name: installer-linux
|
||||||
path: core/target/dist-out/DM_Loremind*.AppImage
|
path: core/target/dist-out/DM_Loremind*.AppImage
|
||||||
retention-days: 90
|
if-no-files-found: error
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
|
# PUBLICATION : un seul job cree la release et y attache les deux installeurs.
|
||||||
|
# Quand windows et linux publiaient chacun de leur cote, ils tournaient en
|
||||||
|
# parallele et creaient DEUX releases pour le meme tag (une publiee, une en
|
||||||
|
# brouillon), l'un echouant sur « already_exists ». Rien n'est publie si l'un
|
||||||
|
# des deux builds echoue : une release a toujours ses deux installeurs.
|
||||||
|
# Relancer le workflow pour une version deja publiee met la release a jour et
|
||||||
|
# remplace les fichiers de meme nom (pas besoin de la supprimer).
|
||||||
|
publish:
|
||||||
|
needs: [windows, linux]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Get installers
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
pattern: installer-*
|
||||||
|
path: dist
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
# tag_name explicite : en declenchement manuel, github.ref est une branche.
|
||||||
|
# Une beta est publiee en pre-release (ignoree par /releases/latest).
|
||||||
|
- name: Publish GitHub Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ needs.windows.outputs.tag }}
|
||||||
|
files: dist/*
|
||||||
|
fail_on_unmatched_files: true
|
||||||
|
generate_release_notes: true
|
||||||
|
prerelease: ${{ needs.windows.outputs.isbeta == 'true' }}
|
||||||
|
|||||||
@@ -7,11 +7,6 @@
|
|||||||
brain/data/settings.json
|
brain/data/settings.json
|
||||||
*.key
|
*.key
|
||||||
*.pem
|
*.pem
|
||||||
# Exception : la cle PUBLIQUE JWT du relais Patreon est destinee a etre
|
|
||||||
# embarquee dans le binaire. Pas de risque a la committer (c'est une cle
|
|
||||||
# publique par construction). Sans cette exception, le module licensing
|
|
||||||
# est silencieusement desactive dans les builds CI.
|
|
||||||
!core/src/main/resources/licensing/jwt-public-key.pem
|
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Java / Spring Boot / Maven
|
# Java / Spring Boot / Maven
|
||||||
|
|||||||
+12
-2
@@ -7,7 +7,6 @@
|
|||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](https://loremind-docs.igmlcreation.fr/)
|
[](https://loremind-docs.igmlcreation.fr/)
|
||||||
[](https://loremind-demo.igmlcreation.fr/)
|
[](https://loremind-demo.igmlcreation.fr/)
|
||||||
[](https://www.patreon.com/c/IGMLCreation)
|
|
||||||
[](https://discord.gg/cPpFzCjEzQ)
|
[](https://discord.gg/cPpFzCjEzQ)
|
||||||
|
|
||||||
## Découvrir DM Loremind en vidéo
|
## Découvrir DM Loremind en vidéo
|
||||||
@@ -67,9 +66,20 @@ Quelques limites à connaître :
|
|||||||
|
|
||||||
DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||||
|
|
||||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
- **Canal bêta** — les nouveautés en avant-première, gratuites pour tous : bascule depuis les Paramètres (Docker) ou pré-version GitHub (bureau)
|
||||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||||
|
|
||||||
|
## Politique de signature du code (Code signing policy)
|
||||||
|
|
||||||
|
Signature de code gratuite fournie par [SignPath.io](https://about.signpath.io), certificat de [SignPath Foundation](https://signpath.org).
|
||||||
|
|
||||||
|
- **Signé** : les installeurs Windows (`.msi`) et le lanceur `DM Loremind.exe`, construits par GitHub Actions à partir de ce dépôt.
|
||||||
|
- **Auteurs et relecteurs** : [IGMLcreation](https://github.com/IGMLcreation)
|
||||||
|
- **Approbateurs** : [IGMLcreation](https://github.com/IGMLcreation) — chaque demande de signature est approuvée manuellement.
|
||||||
|
- **Confidentialité** : DM Loremind ne transmet aucune information à d'autres systèmes en réseau, sauf à la demande explicite de la personne qui l'utilise, l'installe ou l'exploite, et sauf la vérification des mises à jour, qui peut être désactivée. Voir la [politique de confidentialité](https://loremind-docs.igmlcreation.fr/docs/confidentialite).
|
||||||
|
|
||||||
|
Politique complète : [Politique de signature du code](https://loremind-docs.igmlcreation.fr/docs/signature-du-code).
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|
||||||
DM Loremind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
DM Loremind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](https://loremind-docs.igmlcreation.fr/en/)
|
[](https://loremind-docs.igmlcreation.fr/en/)
|
||||||
[](https://loremind-demo.igmlcreation.fr/)
|
[](https://loremind-demo.igmlcreation.fr/)
|
||||||
[](https://www.patreon.com/c/IGMLCreation)
|
|
||||||
[](https://discord.gg/cPpFzCjEzQ)
|
[](https://discord.gg/cPpFzCjEzQ)
|
||||||
|
|
||||||
## See DM Loremind in action
|
## See DM Loremind in action
|
||||||
@@ -67,9 +66,20 @@ A few limitations to be aware of:
|
|||||||
|
|
||||||
DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support:
|
DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support:
|
||||||
|
|
||||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — early access to features, roadmap voting, exclusive devlogs
|
- **Beta channel** — new features ahead of time, free for everyone: switch from Settings (Docker) or install a GitHub pre-release (desktop)
|
||||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
||||||
|
|
||||||
|
## Code signing policy
|
||||||
|
|
||||||
|
Free code signing provided by [SignPath.io](https://about.signpath.io), certificate by [SignPath Foundation](https://signpath.org).
|
||||||
|
|
||||||
|
- **Signed**: the Windows installers (`.msi`) and the `DM Loremind.exe` launcher, built by GitHub Actions from this repository.
|
||||||
|
- **Committers and reviewers**: [IGMLcreation](https://github.com/IGMLcreation)
|
||||||
|
- **Approvers**: [IGMLcreation](https://github.com/IGMLcreation) — each signing request is approved manually.
|
||||||
|
- **Privacy**: DM Loremind does not transfer any information to other networked systems unless specifically requested by the person using, installing or operating it, except for the update check, which can be turned off. See the [privacy policy](https://loremind-docs.igmlcreation.fr/en/docs/confidentialite).
|
||||||
|
|
||||||
|
Full policy: [Code signing policy](https://loremind-docs.igmlcreation.fr/en/docs/signature-du-code).
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
DM Loremind is distributed under the **[GNU AGPL v3](LICENSE)** license.
|
DM Loremind is distributed under the **[GNU AGPL v3](LICENSE)** license.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from app.application.generate_page import GeneratePageUseCase
|
|||||||
from app.application.llm_json import load_json_object
|
from app.application.llm_json import load_json_object
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.prompts import conversation_title as title_prompts
|
from app.application.prompts import conversation_title as title_prompts
|
||||||
|
from app.application.prompts import guided_answers as guided_answers_prompts
|
||||||
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
||||||
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
||||||
from app.application.prompts import session_recap as session_recap_prompts
|
from app.application.prompts import session_recap as session_recap_prompts
|
||||||
@@ -290,3 +291,82 @@ async def generate_session_recap(
|
|||||||
if not recap:
|
if not recap:
|
||||||
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
||||||
return SessionRecapResponseDTO(recap=recap)
|
return SessionRecapResponseDTO(recap=recap)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Méthodes guidées : proposer des réponses à partir d'une idée (Mentor d'écriture) ----
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedOptionDTO(BaseModel):
|
||||||
|
"""Choix possible d'une question à choix : valeur technique + libellé lisible."""
|
||||||
|
|
||||||
|
value: str
|
||||||
|
label: str = Field(default="")
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedFieldDTO(BaseModel):
|
||||||
|
"""Une question de la méthode guidée (décrite par le front, relayée par le Core)."""
|
||||||
|
|
||||||
|
key: str
|
||||||
|
label: str = Field(default="")
|
||||||
|
hint: str = Field(default="")
|
||||||
|
step: str = Field(default="")
|
||||||
|
options: list[GuidedOptionDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedAnswersRequestDTO(BaseModel):
|
||||||
|
method_name: str = Field(default="")
|
||||||
|
method_principle: str = Field(default="")
|
||||||
|
idea: str = Field(default="")
|
||||||
|
context: str = Field(default="")
|
||||||
|
fields: list[GuidedFieldDTO] = Field(default_factory=list)
|
||||||
|
existing: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedAnswersResponseDTO(BaseModel):
|
||||||
|
"""Une réponse proposée par clé (clés demandées uniquement, choix valides, non vides)."""
|
||||||
|
|
||||||
|
answers: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate/guided-answers", response_model=GuidedAnswersResponseDTO)
|
||||||
|
async def generate_guided_answers(
|
||||||
|
body: GuidedAnswersRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
|
) -> GuidedAnswersResponseDTO:
|
||||||
|
"""Propose des réponses aux questions d'une méthode guidée à partir de l'idée du MJ.
|
||||||
|
|
||||||
|
Rien n'est enregistré : le front remplit les champs vides, le MJ relit et corrige. Une
|
||||||
|
question à choix n'accepte qu'une des valeurs proposées ; le reste est ignoré.
|
||||||
|
"""
|
||||||
|
by_key = {f.key: f for f in body.fields if f.key}
|
||||||
|
prompt = guided_answers_prompts.guided_answers_prompt(
|
||||||
|
body.method_name, body.method_principle, body.idea, body.context,
|
||||||
|
[f.model_dump() for f in body.fields], body.existing, language)
|
||||||
|
try:
|
||||||
|
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
if not isinstance(parsed, dict):
|
||||||
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de réponses exploitables.")
|
||||||
|
return GuidedAnswersResponseDTO(answers=_clean_guided_answers(parsed.get("answers"), by_key))
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dict[str, str]:
|
||||||
|
"""Garde les clés demandées, non vides ; une question à choix n'accepte qu'une valeur proposée."""
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return out
|
||||||
|
for key, value in raw.items():
|
||||||
|
field = by_key.get(str(key))
|
||||||
|
if field is None or not isinstance(value, (str, int, float)):
|
||||||
|
continue
|
||||||
|
text = str(value).strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
if field.options and text not in {o.value for o in field.options}:
|
||||||
|
continue
|
||||||
|
out[field.key] = text
|
||||||
|
return out
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
|
|||||||
sections: dict[str, str]
|
sections: dict[str, str]
|
||||||
page_count: int
|
page_count: int
|
||||||
ocr_page_count: int
|
ocr_page_count: int
|
||||||
|
# Règles en deux langues : {code langue → sections} et langue d'origine du livre.
|
||||||
|
sections_by_language: dict[str, dict[str, str]] = {}
|
||||||
|
source_language: str = ""
|
||||||
|
|
||||||
|
|
||||||
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||||
@@ -70,6 +73,8 @@ async def import_rules(
|
|||||||
sections=result.sections,
|
sections=result.sections,
|
||||||
page_count=result.page_count,
|
page_count=result.page_count,
|
||||||
ocr_page_count=result.ocr_page_count,
|
ocr_page_count=result.ocr_page_count,
|
||||||
|
sections_by_language=result.sections_by_language,
|
||||||
|
source_language=result.source_language,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -115,6 +120,7 @@ async def import_rules_stream(
|
|||||||
@router.post("/import/campaign/stream")
|
@router.post("/import/campaign/stream")
|
||||||
async def import_campaign_stream(
|
async def import_campaign_stream(
|
||||||
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
) -> StreamingResponse:
|
) -> StreamingResponse:
|
||||||
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
||||||
@@ -131,7 +137,7 @@ async def import_campaign_stream(
|
|||||||
yield sse_event("error", {"message": upload_error})
|
yield sse_event("error", {"message": upload_error})
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
async for ev in use_case.stream(content):
|
async for ev in use_case.stream(content, language=language):
|
||||||
event_type = ev.pop("type")
|
event_type = ev.pop("type")
|
||||||
yield sse_event(event_type, ev)
|
yield sse_event(event_type, ev)
|
||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
|
|||||||
@@ -361,7 +361,7 @@ class ImportCampaignUseCase:
|
|||||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||||
self._map_concurrency = max(1, map_concurrency)
|
self._map_concurrency = max(1, map_concurrency)
|
||||||
|
|
||||||
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult:
|
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
||||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||||
doc = self._extractor.extract(pdf_bytes)
|
doc = self._extractor.extract(pdf_bytes)
|
||||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||||
@@ -371,7 +371,7 @@ class ImportCampaignUseCase:
|
|||||||
for start in range(0, total, self._map_concurrency):
|
for start in range(0, total, self._map_concurrency):
|
||||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||||
results = await asyncio.gather(*(
|
results = await asyncio.gather(*(
|
||||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||||
for i, c in wave
|
for i, c in wave
|
||||||
))
|
))
|
||||||
for res in results:
|
for res in results:
|
||||||
@@ -386,7 +386,7 @@ class ImportCampaignUseCase:
|
|||||||
npcs=merger.npcs(),
|
npcs=merger.npcs(),
|
||||||
)
|
)
|
||||||
|
|
||||||
async def stream(self, pdf_bytes: bytes):
|
async def stream(self, pdf_bytes: bytes, language: str = "fr"):
|
||||||
"""Variante streamée : yield des évènements d'avancement.
|
"""Variante streamée : yield des évènements d'avancement.
|
||||||
|
|
||||||
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
||||||
@@ -432,7 +432,7 @@ class ImportCampaignUseCase:
|
|||||||
for start in range(0, total, self._map_concurrency):
|
for start in range(0, total, self._map_concurrency):
|
||||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||||
gathered = asyncio.gather(
|
gathered = asyncio.gather(
|
||||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||||
for i, c in wave),
|
for i, c in wave),
|
||||||
return_exceptions=True,
|
return_exceptions=True,
|
||||||
)
|
)
|
||||||
@@ -553,21 +553,23 @@ class ImportCampaignUseCase:
|
|||||||
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
||||||
|
|
||||||
async def _map_chunk(
|
async def _map_chunk(
|
||||||
self, chunk: str, *, index: int, total: int, toc_block: str = ""
|
self, chunk: str, *, index: int, total: int, toc_block: str = "", language: str = "fr"
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
||||||
return await self._extract_payload(
|
return await self._extract_payload(
|
||||||
chunk, index=index, total=total, depth=0, toc_block=toc_block)
|
chunk, index=index, total=total, depth=0, toc_block=toc_block, language=language)
|
||||||
|
|
||||||
async def _extract_payload(
|
async def _extract_payload(
|
||||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = ""
|
self, text: str, *, index: int, total: int, depth: int, toc_block: str = "",
|
||||||
|
language: str = "fr",
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
||||||
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
||||||
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||||
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||||
prompt = (
|
prompt = (
|
||||||
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME)
|
prompts.MAP_SYSTEM.format(default_arc=prompts.default_arc_name(language))
|
||||||
|
+ prompts.language_block(language)
|
||||||
+ toc_section
|
+ toc_section
|
||||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||||
"Renvoie maintenant le JSON de l'arborescence."
|
"Renvoie maintenant le JSON de l'arborescence."
|
||||||
@@ -591,9 +593,9 @@ class ImportCampaignUseCase:
|
|||||||
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||||
"re-découpage en 2 moitiés plus digestes…")
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
a = await self._extract_payload(
|
||||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
b = await self._extract_payload(
|
b = await self._extract_payload(
|
||||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||||
payload, truncated = self._parse_payload(raw, index=index)
|
payload, truncated = self._parse_payload(raw, index=index)
|
||||||
|
|
||||||
@@ -607,9 +609,9 @@ class ImportCampaignUseCase:
|
|||||||
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||||
"re-découpage en 2 moitiés plus digestes…")
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
a = await self._extract_payload(
|
||||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
b = await self._extract_payload(
|
b = await self._extract_payload(
|
||||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||||
if truncated:
|
if truncated:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ from app.application.import_status import (
|
|||||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.prompts import import_rules as prompts
|
from app.application.prompts import import_rules as prompts
|
||||||
|
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
|
||||||
from app.application.streaming import with_heartbeat
|
from app.application.streaming import with_heartbeat
|
||||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||||
|
|
||||||
@@ -90,6 +91,9 @@ _ANCHORS_SCHEMA: dict = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
|
||||||
|
_DETECT_CHARS = 20_000
|
||||||
|
|
||||||
class _SectionMerger:
|
class _SectionMerger:
|
||||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||||
|
|
||||||
@@ -250,10 +254,25 @@ class ImportRulesUseCase:
|
|||||||
merger = _SectionMerger()
|
merger = _SectionMerger()
|
||||||
for i, chunk in enumerate(chunks):
|
for i, chunk in enumerate(chunks):
|
||||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||||
|
sections = merger.result()
|
||||||
|
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||||
|
by_language = {source: sections}
|
||||||
|
translator = RulesTranslator(self._llm)
|
||||||
|
for target in other_languages(source):
|
||||||
|
try:
|
||||||
|
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
|
||||||
|
by_language[target] = {
|
||||||
|
titles.get(title, title): await translator.translate_content(content, source, target)
|
||||||
|
for title, content in sections.items()
|
||||||
|
}
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||||
return RulesImportResult(
|
return RulesImportResult(
|
||||||
sections=merger.result(),
|
sections=sections,
|
||||||
page_count=doc.page_count,
|
page_count=doc.page_count,
|
||||||
ocr_page_count=doc.ocr_page_count,
|
ocr_page_count=doc.ocr_page_count,
|
||||||
|
sections_by_language=by_language,
|
||||||
|
source_language=source,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
||||||
@@ -344,14 +363,57 @@ class ImportRulesUseCase:
|
|||||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
|
||||||
|
# langue de l'application. Un échec de traduction n'annule pas l'import.
|
||||||
|
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||||
|
by_language: dict[str, dict[str, str]] = {source: sections}
|
||||||
|
for target in other_languages(source):
|
||||||
|
try:
|
||||||
|
async for ev in self._translate_events(sections, source, target):
|
||||||
|
if ev["type"] == "_translated":
|
||||||
|
by_language[target] = ev["sections"]
|
||||||
|
else:
|
||||||
|
yield ev
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||||
|
yield {"type": "status",
|
||||||
|
"message": f"Traduction ({language_name(target)}) impossible : {str(exc)[:200]}"}
|
||||||
|
|
||||||
yield {
|
yield {
|
||||||
"type": "done",
|
"type": "done",
|
||||||
"sections": sections,
|
"sections": sections,
|
||||||
|
"sections_by_language": by_language,
|
||||||
|
"source_language": source,
|
||||||
"page_count": doc.page_count,
|
"page_count": doc.page_count,
|
||||||
"ocr_page_count": doc.ocr_page_count,
|
"ocr_page_count": doc.ocr_page_count,
|
||||||
"skipped": skipped,
|
"skipped": skipped,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
|
||||||
|
"""Évènements d'avancement de la traduction ; le dernier est
|
||||||
|
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
|
||||||
|
translator = RulesTranslator(self._llm)
|
||||||
|
titles = list(sections)
|
||||||
|
total = len(titles)
|
||||||
|
label = language_name(target)
|
||||||
|
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
|
||||||
|
mapping: dict[str, str] = {}
|
||||||
|
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
|
||||||
|
if kind == "heartbeat":
|
||||||
|
yield {"type": "heartbeat", "current": 0, "total": total}
|
||||||
|
elif kind == "result":
|
||||||
|
mapping = unique_titles(payload)
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for i, title in enumerate(titles):
|
||||||
|
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
|
||||||
|
"current": i + 1, "total": total}
|
||||||
|
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
|
||||||
|
if kind == "heartbeat":
|
||||||
|
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||||
|
elif kind == "result":
|
||||||
|
out[mapping.get(title, title)] = payload
|
||||||
|
yield {"type": "_translated", "sections": out}
|
||||||
|
|
||||||
# --- MAP : un morceau → sections -----------------------------------------
|
# --- MAP : un morceau → sections -----------------------------------------
|
||||||
|
|
||||||
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
||||||
|
|||||||
@@ -113,5 +113,8 @@ async def generate_with_retry(
|
|||||||
+ str(exc)[:160]
|
+ str(exc)[:160]
|
||||||
)
|
)
|
||||||
await asyncio.sleep(wait)
|
await asyncio.sleep(wait)
|
||||||
|
# Le message « nouvel essai dans Ns » deviendrait faux : on dit que
|
||||||
|
# l'essai suivant est lancé (il peut durer plusieurs minutes).
|
||||||
|
notify_status(f"Nouvel essai en cours (tentative {attempt + 2}/{_ATTEMPTS})…")
|
||||||
assert last_error is not None
|
assert last_error is not None
|
||||||
raise last_error
|
raise last_error
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Prompt des méthodes guidées (Mentor d'écriture) : à partir de l'idée de départ du MJ,
|
||||||
|
proposer des réponses aux questions de la méthode (Donjon en 5 salles, Enquête en nœuds,
|
||||||
|
Plan du méchant…).
|
||||||
|
|
||||||
|
Générique : le front décrit la méthode (nom ; principe suivi du rôle de chaque étape, comme
|
||||||
|
dans l'assistant manuel) et ses questions (clé, libellé,
|
||||||
|
aide, étape, choix possibles) ; ce module ne fait que formuler le prompt. Les réponses
|
||||||
|
déjà écrites par le MJ sont fournies pour rester cohérent et ne jamais être contredites.
|
||||||
|
"""
|
||||||
|
from app.core.language import language_name
|
||||||
|
|
||||||
|
|
||||||
|
def _field_line(field: dict) -> str:
|
||||||
|
key = str(field.get("key") or "").strip()
|
||||||
|
label = str(field.get("label") or key).strip()
|
||||||
|
hint = str(field.get("hint") or "").strip()
|
||||||
|
step = str(field.get("step") or "").strip()
|
||||||
|
line = f'- "{key}"'
|
||||||
|
if step:
|
||||||
|
line += f" [{step}]"
|
||||||
|
line += f" : {label}"
|
||||||
|
if hint:
|
||||||
|
line += f" — {hint}"
|
||||||
|
options = field.get("options") or []
|
||||||
|
if options:
|
||||||
|
values = ", ".join(f'"{o.get("value")}" ({o.get("label")})' for o in options if o.get("value"))
|
||||||
|
line += f" — UNE valeur parmi : {values}"
|
||||||
|
return line
|
||||||
|
|
||||||
|
|
||||||
|
def guided_answers_prompt(method_name: str, method_principle: str, idea: str, context: str,
|
||||||
|
fields: list[dict], existing: dict[str, str], language: str) -> str:
|
||||||
|
"""Construit le prompt. `fields` = [{key, label, hint, step, options}] ; `existing` = réponses du MJ."""
|
||||||
|
fields_list = "\n".join(_field_line(f) for f in fields or [] if f.get("key"))
|
||||||
|
existing_lines = "\n".join(
|
||||||
|
f'- "{k}" : {v.strip()}' for k, v in (existing or {}).items() if isinstance(v, str) and v.strip())
|
||||||
|
existing_block = (
|
||||||
|
"\nCe que le MJ a DÉJÀ écrit (à respecter, ne le contredis jamais) :\n"
|
||||||
|
f"{existing_lines}\n" if existing_lines else ""
|
||||||
|
)
|
||||||
|
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context and context.strip() else ""
|
||||||
|
guide = method_principle.strip() if method_principle else ""
|
||||||
|
guide_block = (
|
||||||
|
"\nLa méthode, telle que le MJ la suit à la main (principe, puis rôle de chaque étape) :\n"
|
||||||
|
f"{guide}\n" if guide else ""
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
"Tu es un auteur expérimenté de scénarios de jeu de rôle, qui aide un MJ à écrire son aventure "
|
||||||
|
f"avec la méthode « {method_name.strip() or 'guidée'} ».\n"
|
||||||
|
f"{guide_block}\n"
|
||||||
|
f"Idée de départ du MJ : {idea.strip() or '(aucune : propose une aventure originale)'}\n"
|
||||||
|
f"{context_block}{existing_block}\n"
|
||||||
|
"Questions de la méthode auxquelles tu dois répondre (n'utilise QUE ces clés) :\n"
|
||||||
|
f"{fields_list}\n\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
|
'- Format exact : {"answers": {"cle": "réponse", ...}}\n'
|
||||||
|
"- N'inclus QUE des clés de la liste. Pour une question à choix, renvoie EXACTEMENT une des "
|
||||||
|
"valeurs proposées.\n"
|
||||||
|
"- Pars de l'idée du MJ et développe-la : garde son ton, ses lieux, ses personnages ; n'en change "
|
||||||
|
"pas le sujet.\n"
|
||||||
|
"- Respecte la méthode : chaque réponse remplit le rôle de SON étape, tel que décrit ci-dessus "
|
||||||
|
"(ex. une épreuve qui ne se règle pas par un combat, des pistes qui se recoupent). Ne mélange pas "
|
||||||
|
"les étapes.\n"
|
||||||
|
"- Toutes les réponses forment UNE aventure cohérente, concrète et jouable "
|
||||||
|
"(noms, lieux, motivations précises ; pas de généralités).\n"
|
||||||
|
"- Sois concis : un nom en quelques mots, une description en 2 à 4 phrases.\n"
|
||||||
|
"- Donne toujours aux joueurs de vrais choix et plusieurs façons de progresser.\n"
|
||||||
|
f"- Rédige les réponses en {language_name(language)}.\n"
|
||||||
|
"Renvoie maintenant le JSON."
|
||||||
|
)
|
||||||
@@ -1,7 +1,29 @@
|
|||||||
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
||||||
|
from app.core.language import language_name
|
||||||
|
|
||||||
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||||
DEFAULT_ARC_NAME = "Aventure principale"
|
DEFAULT_ARC_NAME = "Aventure principale"
|
||||||
|
DEFAULT_ARC_NAMES = {"fr": DEFAULT_ARC_NAME, "en": "Main adventure"}
|
||||||
|
|
||||||
|
|
||||||
|
def default_arc_name(language: str) -> str:
|
||||||
|
"""Nom de l'arc unique, dans la langue de l'interface."""
|
||||||
|
return DEFAULT_ARC_NAMES.get(language, DEFAULT_ARC_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
def language_block(language: str) -> str:
|
||||||
|
"""Consigne de langue : les textes sont écrits dans la langue de l'interface, quelle que
|
||||||
|
soit celle du livre (traduits fidèlement s'il le faut). Les TITRES et noms propres restent
|
||||||
|
ceux du livre : la fusion des morceaux se fait par nom exact, et un nom ne se traduit pas."""
|
||||||
|
name = language_name(language)
|
||||||
|
return (
|
||||||
|
"\n\nLANGUE DE SORTIE :\n"
|
||||||
|
f"- Rédige TOUS les textes (description, player_narration, gm_notes, salles, PNJ) en {name}, "
|
||||||
|
f"quelle que soit la langue du livre. Si le livre est dans une autre langue, TRADUIS ces textes "
|
||||||
|
"fidèlement, sans les résumer davantage.\n"
|
||||||
|
"- Garde TELS QUELS les noms propres (personnages, lieux, divinités, sorts, objets nommés) "
|
||||||
|
"et les noms d'arcs, de chapitres, de scènes, de salles et de PNJ (titres du livre)."
|
||||||
|
)
|
||||||
|
|
||||||
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
||||||
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""Règles en deux langues : détection de la langue d'un livre de règles et traduction de
|
||||||
|
ses sections (titre + contenu markdown) vers l'autre langue de l'application.
|
||||||
|
|
||||||
|
L'extraction reste FIDÈLE au livre (langue d'origine) ; la traduction produit la seconde
|
||||||
|
version. Les noms propres (lieux, personnages, divinités, sorts, objets nommés) sont
|
||||||
|
conservés tels quels. Un contenu long est traduit par morceaux coupés aux paragraphes,
|
||||||
|
pour rester sous les limites de sortie des modèles.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from app.application.llm_json import load_json_object
|
||||||
|
from app.application.llm_retry import generate_with_retry
|
||||||
|
from app.core.language import language_name
|
||||||
|
from app.domain.ports import LLMProvider
|
||||||
|
|
||||||
|
LANGUAGES = ("fr", "en")
|
||||||
|
|
||||||
|
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
|
||||||
|
CHUNK_CHARS = 6000
|
||||||
|
|
||||||
|
_FR_WORDS = {"le", "la", "les", "des", "une", "est", "et", "du", "dans", "pour", "que", "qui",
|
||||||
|
"sur", "avec", "vous", "votre", "sont", "pas", "par", "au", "aux", "ce", "cette", "il"}
|
||||||
|
_EN_WORDS = {"the", "and", "of", "to", "is", "in", "you", "your", "for", "with", "that", "are",
|
||||||
|
"on", "as", "be", "this", "it", "an", "by", "or", "can", "if", "each", "when"}
|
||||||
|
|
||||||
|
|
||||||
|
def detect_language(text: str, default: str = "fr") -> str:
|
||||||
|
"""Langue dominante (« fr » ou « en ») par comptage de mots-outils ; `default` si indécis."""
|
||||||
|
words = re.findall(r"[a-zàâçéèêëîïôûùüÿœ']+", (text or "").lower())
|
||||||
|
fr = sum(1 for w in words if w in _FR_WORDS)
|
||||||
|
en = sum(1 for w in words if w in _EN_WORDS)
|
||||||
|
if fr == en:
|
||||||
|
return default if default in LANGUAGES else "fr"
|
||||||
|
return "fr" if fr > en else "en"
|
||||||
|
|
||||||
|
|
||||||
|
def other_languages(source: str) -> list[str]:
|
||||||
|
return [lang for lang in LANGUAGES if lang != source]
|
||||||
|
|
||||||
|
|
||||||
|
def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
|
||||||
|
"""Coupe un markdown en morceaux ≤ max_chars, aux limites de paragraphes (puis de lignes)."""
|
||||||
|
if len(text) <= max_chars:
|
||||||
|
return [text]
|
||||||
|
chunks: list[str] = []
|
||||||
|
current = ""
|
||||||
|
for para in re.split(r"(\n\s*\n)", text):
|
||||||
|
if len(current) + len(para) <= max_chars:
|
||||||
|
current += para
|
||||||
|
continue
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current)
|
||||||
|
current = ""
|
||||||
|
while len(para) > max_chars: # paragraphe géant : coupe aux lignes, sinon brutalement
|
||||||
|
cut = para.rfind("\n", 0, max_chars)
|
||||||
|
cut = cut if cut > 0 else max_chars
|
||||||
|
chunks.append(para[:cut])
|
||||||
|
para = para[cut:]
|
||||||
|
current = para
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current)
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
|
||||||
|
def content_prompt(text: str, source: str, target: str) -> str:
|
||||||
|
return (
|
||||||
|
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
|
||||||
|
f"vers la langue « {language_name(target)} ».\n\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\n"
|
||||||
|
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
|
||||||
|
"objets nommés.\n"
|
||||||
|
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
|
||||||
|
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
|
||||||
|
"Extrait :\n"
|
||||||
|
f"{text}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def titles_prompt(titles: list[str], source: str, target: str) -> str:
|
||||||
|
listing = "\n".join(f"- {t}" for t in titles)
|
||||||
|
return (
|
||||||
|
f"Traduis ces titres de sections d'un livre de règles de jeu de rôle de la langue "
|
||||||
|
f"« {language_name(source)} » vers la langue « {language_name(target)} ». "
|
||||||
|
"Garde les noms propres tels quels.\n"
|
||||||
|
'Réponds UNIQUEMENT par un objet JSON : {"titles": {"titre d\'origine": "titre traduit", ...}}\n\n'
|
||||||
|
f"{listing}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RulesTranslator:
|
||||||
|
"""Traduit des sections de règles {titre: markdown} d'une langue vers une autre."""
|
||||||
|
|
||||||
|
def __init__(self, llm: LLMProvider) -> None:
|
||||||
|
self._llm = llm
|
||||||
|
|
||||||
|
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
|
||||||
|
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
|
||||||
|
if not titles:
|
||||||
|
return {}
|
||||||
|
raw = await generate_with_retry(self._llm, titles_prompt(titles, source, target),
|
||||||
|
output_format="json", temperature=0.2)
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for title in titles:
|
||||||
|
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||||
|
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||||
|
return out
|
||||||
|
|
||||||
|
async def translate_content(self, text: str, source: str, target: str) -> str:
|
||||||
|
"""Traduit un contenu markdown (morceau par morceau s'il est long)."""
|
||||||
|
if not text or not text.strip():
|
||||||
|
return text
|
||||||
|
parts = []
|
||||||
|
for chunk in split_markdown(text):
|
||||||
|
if not chunk.strip():
|
||||||
|
parts.append(chunk)
|
||||||
|
continue
|
||||||
|
translated = await generate_with_retry(self._llm, content_prompt(chunk, source, target),
|
||||||
|
temperature=0.2)
|
||||||
|
parts.append(translated.strip())
|
||||||
|
return "\n\n".join(p for p in parts if p.strip())
|
||||||
|
|
||||||
|
|
||||||
|
def unique_titles(titles: dict[str, str]) -> dict[str, str]:
|
||||||
|
"""Évite deux sections traduites sous le même titre (sinon l'une écraserait l'autre)."""
|
||||||
|
seen: dict[str, int] = {}
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for original, translated in titles.items():
|
||||||
|
count = seen.get(translated, 0)
|
||||||
|
seen[translated] = count + 1
|
||||||
|
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
||||||
|
return out
|
||||||
@@ -367,6 +367,10 @@ class RulesImportResult:
|
|||||||
sections: dict[str, str]
|
sections: dict[str, str]
|
||||||
page_count: int
|
page_count: int
|
||||||
ocr_page_count: int
|
ocr_page_count: int
|
||||||
|
# Règles en deux langues : {code langue → sections}. La langue d'origine du livre
|
||||||
|
# (`source_language`) contient l'extraction fidèle ; l'autre, sa traduction.
|
||||||
|
sections_by_language: dict[str, dict[str, str]] = field(default_factory=dict)
|
||||||
|
source_language: str = ""
|
||||||
|
|
||||||
def to_markdown(self) -> str:
|
def to_markdown(self) -> str:
|
||||||
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
||||||
|
|||||||
+1
-1
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="1.5.0-beta",
|
version="1.6.2",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Méthodes guidées : prompt de propositions et nettoyage des réponses du modèle."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.api.routers.generation import GuidedFieldDTO, GuidedOptionDTO, _clean_guided_answers
|
||||||
|
from app.application.prompts.guided_answers import guided_answers_prompt
|
||||||
|
|
||||||
|
|
||||||
|
def _fields() -> dict[str, GuidedFieldDTO]:
|
||||||
|
return {
|
||||||
|
"title": GuidedFieldDTO(key="title", label="Nom de l'enquête"),
|
||||||
|
"node1.nature": GuidedFieldDTO(key="node1.nature", label="Genre de scène", options=[
|
||||||
|
GuidedOptionDTO(value="location", label="Un lieu"), GuidedOptionDTO(value="npc", label="Une personne")]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_contains_idea_questions_choices_existing_answers_and_language():
|
||||||
|
prompt = guided_answers_prompt(
|
||||||
|
"Enquête en nœuds", "Trois pistes qui se recoupent.", "Une tour qui se rallume", "Campagne : Valfroide",
|
||||||
|
[{"key": "title", "label": "Nom de l'enquête", "hint": "Ex. : L'héritage", "step": "Le mystère"},
|
||||||
|
{"key": "node1.nature", "label": "Genre", "options": [{"value": "location", "label": "Un lieu"}]}],
|
||||||
|
{"truth": "Le notaire est coupable", "empty": " "}, "en")
|
||||||
|
|
||||||
|
assert "Une tour qui se rallume" in prompt
|
||||||
|
assert '"title" [Le mystère] : Nom de l\'enquête — Ex. : L\'héritage' in prompt
|
||||||
|
assert 'UNE valeur parmi : "location" (Un lieu)' in prompt
|
||||||
|
assert "Le notaire est coupable" in prompt
|
||||||
|
assert '"empty"' not in prompt, "une réponse vide n'est pas rappelée"
|
||||||
|
assert "Campagne : Valfroide" in prompt
|
||||||
|
assert "anglais" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_lists_the_method_steps_and_asks_to_follow_them():
|
||||||
|
guide = ("Cinq temps dans un même lieu.\n\n"
|
||||||
|
"- Salle 2 : l'épreuve : ici, l'épée ne suffit pas.\n"
|
||||||
|
"- Salle 3 : le revers : les choses se compliquent.")
|
||||||
|
p = guided_answers_prompt("Donjon en 5 salles", guide, "Une crypte", "", [{"key": "room2.name"}], {}, "fr")
|
||||||
|
assert "telle que le MJ la suit à la main" in p
|
||||||
|
assert "- Salle 2 : l'épreuve : ici, l'épée ne suffit pas." in p
|
||||||
|
assert "rôle de SON étape" in p
|
||||||
|
assert "Idée de départ du MJ : Une crypte" in p
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_without_idea_asks_for_an_original_adventure():
|
||||||
|
prompt = guided_answers_prompt("Plan du méchant", "", " ", "", [{"key": "villain", "label": "Adversaire"}], {}, "fr")
|
||||||
|
assert "propose une aventure originale" in prompt
|
||||||
|
assert "français" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_keeps_requested_keys_and_valid_choices_only():
|
||||||
|
out = _clean_guided_answers({
|
||||||
|
"title": " L'héritage empoisonné ",
|
||||||
|
"node1.nature": "npc",
|
||||||
|
"unknown": "ignorée",
|
||||||
|
"empty": "",
|
||||||
|
}, _fields())
|
||||||
|
assert out == {"title": "L'héritage empoisonné", "node1.nature": "npc"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_rejects_an_invalid_choice_and_non_text_values():
|
||||||
|
out = _clean_guided_answers({"node1.nature": "dragon", "title": ["liste"]}, _fields())
|
||||||
|
assert out == {}
|
||||||
|
assert _clean_guided_answers("pas un objet", _fields()) == {}
|
||||||
@@ -100,6 +100,8 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
|||||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||||
llm = ContentLLM([
|
llm = ContentLLM([
|
||||||
|
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||||
|
("Traduis cet extrait", "spells"),
|
||||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||||
("BBB second", '{"Magie":"sorts"}'),
|
("BBB second", '{"Magie":"sorts"}'),
|
||||||
])
|
])
|
||||||
@@ -111,6 +113,25 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
|||||||
assert done["type"] == "done"
|
assert done["type"] == "done"
|
||||||
assert done["sections"] == {"Magie": "sorts"}
|
assert done["sections"] == {"Magie": "sorts"}
|
||||||
assert done["skipped"] == 1
|
assert done["skipped"] == 1
|
||||||
|
# Règles en deux langues : livre en français (« Texte du PDF. ») → traduction anglaise.
|
||||||
|
assert done["source_language"] == "fr"
|
||||||
|
assert done["sections_by_language"] == {"fr": {"Magie": "sorts"}, "en": {"Magic": "spells"}}
|
||||||
|
assert any(e["type"] == "status" and "anglais" in e["message"] for e in events)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_rules_stream_keeps_the_source_language_when_translation_fails(monkeypatch, no_sleep):
|
||||||
|
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["The rules of the game"])
|
||||||
|
llm = ContentLLM([
|
||||||
|
("Traduis ces titres", LLMProviderError("HTTP 503 saturé")),
|
||||||
|
("The rules of the game", '{"Combat":"Each round, you roll the dice."}'),
|
||||||
|
])
|
||||||
|
uc = ImportRulesUseCase(llm, FakeExtractor(_doc("The rules of the game are simple and you can play.")))
|
||||||
|
events = [e async for e in uc.stream(b"pdf")]
|
||||||
|
done = events[-1]
|
||||||
|
assert done["type"] == "done"
|
||||||
|
assert done["source_language"] == "en"
|
||||||
|
assert done["sections_by_language"] == {"en": {"Combat": "Each round, you roll the dice."}}
|
||||||
|
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
||||||
|
|
||||||
|
|
||||||
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
||||||
@@ -155,3 +176,34 @@ async def test_campaign_stream_all_fail_emits_error(one_chunk, no_sleep):
|
|||||||
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
||||||
events = [e async for e in uc.stream(b"pdf")]
|
events = [e async for e in uc.stream(b"pdf")]
|
||||||
assert events[-1]["type"] == "error"
|
assert events[-1]["type"] == "error"
|
||||||
|
|
||||||
|
|
||||||
|
class _RecordingLLM(ScriptedLLM):
|
||||||
|
"""ScriptedLLM qui garde les prompts reçus."""
|
||||||
|
|
||||||
|
def __init__(self, responses: list) -> None:
|
||||||
|
super().__init__(responses)
|
||||||
|
self.prompts: list[str] = []
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompts.append(prompt)
|
||||||
|
return await super().generate(prompt, output_format=output_format, temperature=temperature)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_campaign_import_writes_in_the_interface_language_and_keeps_names():
|
||||||
|
llm = _RecordingLLM([_TREE])
|
||||||
|
uc = ImportCampaignUseCase(llm, FakeExtractor(_doc()))
|
||||||
|
events = [e async for e in uc.stream(b"pdf", language="en")]
|
||||||
|
assert events[-1]["type"] == "done"
|
||||||
|
prompt = llm.prompts[0]
|
||||||
|
assert "LANGUE DE SORTIE" in prompt
|
||||||
|
assert "en anglais" in prompt
|
||||||
|
assert "noms propres" in prompt
|
||||||
|
assert '"Main adventure"' in prompt, "arc par défaut dans la langue de l'interface"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_campaign_import_defaults_to_french():
|
||||||
|
llm = _RecordingLLM([_TREE])
|
||||||
|
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
||||||
|
assert "en français" in llm.prompts[0]
|
||||||
|
assert '"Aventure principale"' in llm.prompts[0]
|
||||||
|
|||||||
@@ -110,3 +110,21 @@ async def test_rate_limit_respects_suggested_retry_after(slept):
|
|||||||
assert await generate_with_retry(llm, "p") == "ok"
|
assert await generate_with_retry(llm, "p") == "ok"
|
||||||
# min(8 + 2, 60) = 10
|
# min(8 + 2, 60) = 10
|
||||||
assert slept == [10.0]
|
assert slept == [10.0]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_tells_the_ui_when_the_next_attempt_starts(slept):
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from app.application.import_status import reset_status_queue, set_status_queue
|
||||||
|
|
||||||
|
queue: asyncio.Queue = asyncio.Queue()
|
||||||
|
token = set_status_queue(queue)
|
||||||
|
try:
|
||||||
|
llm = FakeLLM([LLMProviderError("Erreur Mistral (ReadError) : ReadError"), "ok"])
|
||||||
|
assert await generate_with_retry(llm, "p") == "ok"
|
||||||
|
finally:
|
||||||
|
reset_status_queue(token)
|
||||||
|
messages = [queue.get_nowait() for _ in range(queue.qsize())]
|
||||||
|
assert "nouvel essai dans 3s" in messages[0]
|
||||||
|
# Sans ce second message, « nouvel essai dans 3s » restait affiché pendant tout l'essai suivant.
|
||||||
|
assert messages[1] == "Nouvel essai en cours (tentative 2/3)…"
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.application.rules_translation import (
|
||||||
|
RulesTranslator, detect_language, other_languages, split_markdown, unique_titles,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class EchoLLM:
|
||||||
|
"""Traduit « en majuscules » et garde trace des prompts reçus."""
|
||||||
|
|
||||||
|
def __init__(self, titles_json: str = '{"titles": {}}') -> None:
|
||||||
|
self.prompts: list[str] = []
|
||||||
|
self._titles_json = titles_json
|
||||||
|
|
||||||
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||||
|
self.prompts.append(prompt)
|
||||||
|
if "Traduis ces titres" in prompt:
|
||||||
|
return self._titles_json
|
||||||
|
return prompt.split("Extrait :\n", 1)[1].upper()
|
||||||
|
|
||||||
|
|
||||||
|
def test_detect_language():
|
||||||
|
assert detect_language("Le joueur lance les dés et la partie est terminée pour vous.") == "fr"
|
||||||
|
assert detect_language("The player rolls the dice and the game is over for you.") == "en"
|
||||||
|
assert detect_language("", default="en") == "en"
|
||||||
|
assert other_languages("fr") == ["en"]
|
||||||
|
assert other_languages("en") == ["fr"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_markdown_keeps_short_text_and_cuts_at_paragraphs():
|
||||||
|
assert split_markdown("court") == ["court"]
|
||||||
|
text = "\n\n".join(["a" * 40] * 10)
|
||||||
|
chunks = split_markdown(text, max_chars=100)
|
||||||
|
assert all(len(c) <= 100 for c in chunks)
|
||||||
|
assert "".join(chunks).replace("\n", "") == text.replace("\n", "")
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_markdown_cuts_a_giant_paragraph():
|
||||||
|
chunks = split_markdown("x" * 250, max_chars=100)
|
||||||
|
assert [len(c) for c in chunks] == [100, 100, 50]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_translate_content_keeps_names_instruction_and_joins_chunks():
|
||||||
|
llm = EchoLLM()
|
||||||
|
out = await RulesTranslator(llm).translate_content("## Combat\n\nChaque round.", "fr", "en")
|
||||||
|
assert out == "## COMBAT\n\nCHAQUE ROUND."
|
||||||
|
assert "noms propres" in llm.prompts[0]
|
||||||
|
assert "de la langue « français » vers la langue « anglais »" in llm.prompts[0]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_translate_titles_falls_back_to_the_original_title():
|
||||||
|
llm = EchoLLM('{"titles": {"Combat": "Fighting"}}')
|
||||||
|
out = await RulesTranslator(llm).translate_titles(["Combat", "Magie"], "fr", "en")
|
||||||
|
assert out == {"Combat": "Fighting", "Magie": "Magie"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_unique_titles_avoids_collisions():
|
||||||
|
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
||||||
|
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
|
||||||
+1
-26
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>1.5.0-beta</version>
|
<version>1.6.2</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
@@ -137,31 +137,6 @@
|
|||||||
<version>5.1.0</version>
|
<version>5.1.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Nimbus JOSE+JWT — verification des JWT Ed25519 (EdDSA) emis par le relais
|
|
||||||
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle.
|
|
||||||
>= 10.0.2 : corrige CVE-2025-53864 (DoS par JSON profondement imbrique
|
|
||||||
dans le claim set — surface critique : JWT colle par l'utilisateur). -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.nimbusds</groupId>
|
|
||||||
<artifactId>nimbus-jose-jwt</artifactId>
|
|
||||||
<version>10.9.1</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.bouncycastle</groupId>
|
|
||||||
<artifactId>bcprov-jdk18on</artifactId>
|
|
||||||
<version>1.84</version>
|
|
||||||
</dependency>
|
|
||||||
<!-- Google Tink : runtime requis par com.nimbusds.jose.crypto.Ed25519Verifier
|
|
||||||
(depuis Nimbus 9.x, la verification EdDSA delegue a Tink.subtle.Ed25519Verify).
|
|
||||||
Tink n'est PAS une dependance transitive de nimbus-jose-jwt → il faut
|
|
||||||
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify().
|
|
||||||
>= 1.15 : embarque un protobuf-java corrige (CVE-2024-7254). -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.crypto.tink</groupId>
|
|
||||||
<artifactId>tink</artifactId>
|
|
||||||
<version>1.21.0</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif :
|
<!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif :
|
||||||
compatible distribution bureau locale via jpackage). Sert l'export PDF
|
compatible distribution bureau locale via jpackage). Sert l'export PDF
|
||||||
d'une campagne (livret). -->
|
d'une campagne (livret). -->
|
||||||
|
|||||||
@@ -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
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.loremind.application.licensing;
|
package com.loremind.application.channel;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
+6
-2
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.application.gamesystemcontext;
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||||
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||||
@@ -36,9 +37,11 @@ public class GameSystemContextBuilder {
|
|||||||
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
|
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
|
||||||
|
|
||||||
private final GameSystemRepository gameSystemRepository;
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
private final CurrentLanguage currentLanguage;
|
||||||
|
|
||||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
|
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository, CurrentLanguage currentLanguage) {
|
||||||
this.gameSystemRepository = gameSystemRepository;
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
this.currentLanguage = currentLanguage;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
||||||
@@ -48,7 +51,8 @@ public class GameSystemContextBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
||||||
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown());
|
// Règles dans la langue de l'interface (repli sur l'autre version si celle-ci est vide).
|
||||||
|
Map<String, String> allSections = parseH2Sections(gs.rulesFor(currentLanguage.get()));
|
||||||
Map<String, String> filtered = filterByIntent(allSections, intent);
|
Map<String, String> filtered = filterByIntent(allSections, intent);
|
||||||
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ public class GameSystemService {
|
|||||||
String name,
|
String name,
|
||||||
String description,
|
String description,
|
||||||
String rulesMarkdown,
|
String rulesMarkdown,
|
||||||
|
String rulesMarkdownEn,
|
||||||
List<TemplateField> characterTemplate,
|
List<TemplateField> characterTemplate,
|
||||||
List<TemplateField> npcTemplate,
|
List<TemplateField> npcTemplate,
|
||||||
List<TemplateField> enemyTemplate,
|
List<TemplateField> enemyTemplate,
|
||||||
@@ -72,6 +73,7 @@ public class GameSystemService {
|
|||||||
.name(data.name())
|
.name(data.name())
|
||||||
.description(data.description())
|
.description(data.description())
|
||||||
.rulesMarkdown(data.rulesMarkdown())
|
.rulesMarkdown(data.rulesMarkdown())
|
||||||
|
.rulesMarkdownEn(data.rulesMarkdownEn())
|
||||||
.foundryActorType(normalize(data.foundryActorType()))
|
.foundryActorType(normalize(data.foundryActorType()))
|
||||||
.author(normalize(data.author()))
|
.author(normalize(data.author()))
|
||||||
.isPublic(data.isPublic())
|
.isPublic(data.isPublic())
|
||||||
@@ -96,6 +98,7 @@ public class GameSystemService {
|
|||||||
existing.setName(data.name());
|
existing.setName(data.name());
|
||||||
existing.setDescription(data.description());
|
existing.setDescription(data.description());
|
||||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||||
|
existing.setRulesMarkdownEn(data.rulesMarkdownEn());
|
||||||
existing.replaceCharacterTemplate(data.characterTemplate());
|
existing.replaceCharacterTemplate(data.characterTemplate());
|
||||||
existing.replaceNpcTemplate(data.npcTemplate());
|
existing.replaceNpcTemplate(data.npcTemplate());
|
||||||
existing.replaceEnemyTemplate(data.enemyTemplate());
|
existing.replaceEnemyTemplate(data.enemyTemplate());
|
||||||
|
|||||||
@@ -1,266 +0,0 @@
|
|||||||
package com.loremind.application.licensing;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.License;
|
|
||||||
import com.loremind.domain.licensing.LicenseClaims;
|
|
||||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
|
||||||
import com.loremind.domain.licensing.LicenseStatus;
|
|
||||||
import com.loremind.domain.licensing.RegistryCredentials;
|
|
||||||
import com.loremind.domain.licensing.ports.JwtVerifier;
|
|
||||||
import com.loremind.domain.licensing.ports.LicenseRelay;
|
|
||||||
import com.loremind.domain.licensing.ports.LicenseRepository;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Service application pour la gestion de la licence Patreon.
|
|
||||||
* <p>
|
|
||||||
* Responsabilites :
|
|
||||||
* <ul>
|
|
||||||
* <li>Installer un nouveau JWT recu du relais (apres OAuth utilisateur)</li>
|
|
||||||
* <li>Calculer le {@link LicenseStatus} courant en respectant la grace period</li>
|
|
||||||
* <li>Renouveler le JWT avant expiration en appelant le relais</li>
|
|
||||||
* <li>Activer/desactiver le toggle "canal beta" cote utilisateur</li>
|
|
||||||
* <li>Distribuer les credentials registry pour le pull beta</li>
|
|
||||||
* </ul>
|
|
||||||
*/
|
|
||||||
@Service
|
|
||||||
public class LicenseService {
|
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(LicenseService.class);
|
|
||||||
|
|
||||||
private final LicenseRepository repository;
|
|
||||||
private final JwtVerifier jwtVerifier;
|
|
||||||
private final LicenseRelay relay;
|
|
||||||
private final long gracePeriodSeconds;
|
|
||||||
private final long refreshBeforeExpirySeconds;
|
|
||||||
private final boolean licensingEnabled;
|
|
||||||
|
|
||||||
public LicenseService(
|
|
||||||
LicenseRepository repository,
|
|
||||||
JwtVerifier jwtVerifier,
|
|
||||||
LicenseRelay relay,
|
|
||||||
@Value("${licensing.grace-period-days:14}") int gracePeriodDays,
|
|
||||||
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays,
|
|
||||||
@Value("${licensing.enabled:true}") boolean licensingEnabled) {
|
|
||||||
this.repository = repository;
|
|
||||||
this.jwtVerifier = jwtVerifier;
|
|
||||||
this.relay = relay;
|
|
||||||
this.gracePeriodSeconds = gracePeriodDays * 86_400L;
|
|
||||||
this.refreshBeforeExpirySeconds = refreshBeforeExpiryDays * 86_400L;
|
|
||||||
this.licensingEnabled = licensingEnabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true si le licensing Patreon est actif : il faut a la fois que la
|
|
||||||
* feature soit activee ({@code licensing.enabled}, faux en mode
|
|
||||||
* bureau/local ou le gating par image Docker n'a aucun sens) ET que
|
|
||||||
* le verifier soit configure (cle publique presente). Faux => l'UI
|
|
||||||
* masque toute la section Patreon, le daemon de refresh est no-op,
|
|
||||||
* et le canal beta est desactive.
|
|
||||||
*/
|
|
||||||
public boolean isLicensingEnabled() {
|
|
||||||
return licensingEnabled && jwtVerifier.isConfigured();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Genere ou retourne l'instance_id stable de cette installation.
|
|
||||||
* Stocke dans la licence elle-meme. Si pas de licence, en cree un volatil
|
|
||||||
* (sera persiste a la prochaine connexion).
|
|
||||||
*/
|
|
||||||
public String getOrCreateInstanceId() {
|
|
||||||
return repository.findCurrent()
|
|
||||||
.map(License::getInstanceId)
|
|
||||||
.orElseGet(() -> "li-" + UUID.randomUUID());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Construit l'URL OAuth pour ouvrir dans le navigateur de l'utilisateur.
|
|
||||||
*/
|
|
||||||
public String buildConnectUrl() {
|
|
||||||
return relay.buildConnectUrl(getOrCreateInstanceId());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Installe un JWT recu du relais (l'utilisateur l'a colle dans l'UI ou
|
|
||||||
* recu via deep-link). Verifie la signature, extrait les claims, persiste.
|
|
||||||
*/
|
|
||||||
public LicenseSnapshot installToken(String rawJwt) throws InstallException {
|
|
||||||
if (!jwtVerifier.isConfigured()) {
|
|
||||||
throw new InstallException("Licensing feature not enabled (no public key configured)");
|
|
||||||
}
|
|
||||||
LicenseClaims claims;
|
|
||||||
try {
|
|
||||||
claims = jwtVerifier.verify(rawJwt);
|
|
||||||
} catch (JwtVerifier.JwtVerificationException e) {
|
|
||||||
throw new InstallException("Invalid JWT: " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
Instant now = Instant.now();
|
|
||||||
if (claims.expiresAt().isBefore(now)) {
|
|
||||||
throw new InstallException("JWT already expired");
|
|
||||||
}
|
|
||||||
|
|
||||||
Optional<License> existing = repository.findCurrent();
|
|
||||||
License toSave = License.builder()
|
|
||||||
.id("current")
|
|
||||||
.rawJwt(rawJwt)
|
|
||||||
.patreonUserId(claims.subject())
|
|
||||||
.tierId(claims.tierId())
|
|
||||||
.instanceId(claims.instanceId())
|
|
||||||
.issuedAt(claims.issuedAt())
|
|
||||||
.expiresAt(claims.expiresAt())
|
|
||||||
.lastRefreshAttemptAt(now)
|
|
||||||
.lastRefreshSucceeded(true)
|
|
||||||
// Au premier install, on active le canal beta par defaut.
|
|
||||||
// Sur reinstall apres deconnexion, on respecte la valeur precedente.
|
|
||||||
.betaChannelEnabled(existing.map(License::isBetaChannelEnabled).orElse(true))
|
|
||||||
.createdAt(existing.map(License::getCreatedAt).orElse(now))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
License saved = repository.save(toSave);
|
|
||||||
log.info("Patreon license installed for user={} tier={} expires={}",
|
|
||||||
saved.getPatreonUserId(), saved.getTierId(), saved.getExpiresAt());
|
|
||||||
return snapshotOf(saved, now);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Etat courant de la licence pour exposition UI / decision technique.
|
|
||||||
*/
|
|
||||||
public LicenseSnapshot getCurrentSnapshot() {
|
|
||||||
return repository.findCurrent()
|
|
||||||
.map(l -> snapshotOf(l, Instant.now()))
|
|
||||||
.orElseGet(LicenseSnapshot::none);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Supprime la licence (deconnexion volontaire de Patreon par l'utilisateur).
|
|
||||||
*/
|
|
||||||
public void disconnect() {
|
|
||||||
repository.deleteCurrent();
|
|
||||||
log.info("Patreon license removed (user disconnect)");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Active ou desactive le canal beta. Necessite une licence valide ou en grace.
|
|
||||||
*/
|
|
||||||
public LicenseSnapshot setBetaChannelEnabled(boolean enabled) {
|
|
||||||
License current = repository.findCurrent()
|
|
||||||
.orElseThrow(() -> new IllegalStateException("No license installed"));
|
|
||||||
current.setBetaChannelEnabled(enabled);
|
|
||||||
License saved = repository.save(current);
|
|
||||||
return snapshotOf(saved, Instant.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tente un refresh si la licence est proche de l'expiration. Idempotent.
|
|
||||||
* Appele par le daemon planifie + manuellement via l'UI ("Reessayer").
|
|
||||||
*/
|
|
||||||
public void refreshIfNeeded() {
|
|
||||||
Optional<License> opt = repository.findCurrent();
|
|
||||||
if (opt.isEmpty()) return;
|
|
||||||
License current = opt.get();
|
|
||||||
Instant now = Instant.now();
|
|
||||||
long secondsUntilExpiry = Duration.between(now, current.getExpiresAt()).getSeconds();
|
|
||||||
if (secondsUntilExpiry > refreshBeforeExpirySeconds) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
doRefresh(current, now);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Force un refresh immediat (bouton UI "Reessayer maintenant").
|
|
||||||
*/
|
|
||||||
public void forceRefresh() {
|
|
||||||
repository.findCurrent().ifPresent(license -> doRefresh(license, Instant.now()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tente le refresh aupres du relais et persiste le resultat (succes ou echec) sur
|
|
||||||
* la licence. Le succes/echec est lu depuis {@code lastRefreshSucceeded}, pas
|
|
||||||
* depuis un retour de methode : le tentative est deja actee cote persistance.
|
|
||||||
*/
|
|
||||||
private void doRefresh(License current, Instant now) {
|
|
||||||
log.info("Refreshing Patreon license (current expires {})", current.getExpiresAt());
|
|
||||||
try {
|
|
||||||
String newJwt = relay.refreshToken(current.getRawJwt());
|
|
||||||
LicenseClaims claims = jwtVerifier.verify(newJwt);
|
|
||||||
|
|
||||||
current.setRawJwt(newJwt);
|
|
||||||
current.setIssuedAt(claims.issuedAt());
|
|
||||||
current.setExpiresAt(claims.expiresAt());
|
|
||||||
current.setTierId(claims.tierId());
|
|
||||||
current.setLastRefreshAttemptAt(now);
|
|
||||||
current.setLastRefreshSucceeded(true);
|
|
||||||
repository.save(current);
|
|
||||||
log.info("License refreshed successfully (new expiry {})", claims.expiresAt());
|
|
||||||
} catch (LicenseRelay.RelayException e) {
|
|
||||||
current.setLastRefreshAttemptAt(now);
|
|
||||||
current.setLastRefreshSucceeded(false);
|
|
||||||
repository.save(current);
|
|
||||||
if (e.getKind() == LicenseRelay.RelayErrorKind.REJECTED) {
|
|
||||||
log.warn("Relay rejected refresh ({}): tier may have been cancelled", e.getMessage());
|
|
||||||
} else {
|
|
||||||
log.warn("Relay refresh transient failure ({}): {}", e.getKind(), e.getMessage());
|
|
||||||
}
|
|
||||||
} catch (JwtVerifier.JwtVerificationException e) {
|
|
||||||
current.setLastRefreshAttemptAt(now);
|
|
||||||
current.setLastRefreshSucceeded(false);
|
|
||||||
repository.save(current);
|
|
||||||
log.error("Relay returned a JWT that fails verification: {}", e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Recupere les credentials registry pour pull du canal beta.
|
|
||||||
* @return empty si pas de licence valide ou relais en echec
|
|
||||||
*/
|
|
||||||
public Optional<RegistryCredentials> fetchRegistryCredentials() {
|
|
||||||
LicenseSnapshot snap = getCurrentSnapshot();
|
|
||||||
if (snap.status() != LicenseStatus.VALID && snap.status() != LicenseStatus.GRACE) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
License current = repository.findCurrent().orElse(null);
|
|
||||||
if (current == null) return Optional.empty();
|
|
||||||
try {
|
|
||||||
return Optional.of(relay.fetchRegistryCredentials(current.getRawJwt()));
|
|
||||||
} catch (LicenseRelay.RelayException e) {
|
|
||||||
log.warn("Cannot fetch registry credentials ({}): {}", e.getKind(), e.getMessage());
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private LicenseSnapshot snapshotOf(License l, Instant now) {
|
|
||||||
LicenseStatus status = computeStatus(l, now);
|
|
||||||
return new LicenseSnapshot(
|
|
||||||
status,
|
|
||||||
l.getPatreonUserId(),
|
|
||||||
l.getTierId(),
|
|
||||||
l.getInstanceId(),
|
|
||||||
l.getExpiresAt(),
|
|
||||||
l.getLastRefreshAttemptAt(),
|
|
||||||
l.isLastRefreshSucceeded(),
|
|
||||||
l.isBetaChannelEnabled()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private LicenseStatus computeStatus(License l, Instant now) {
|
|
||||||
if (l.getExpiresAt() == null) return LicenseStatus.NONE;
|
|
||||||
if (now.isBefore(l.getExpiresAt())) return LicenseStatus.VALID;
|
|
||||||
long secondsPastExpiry = Duration.between(l.getExpiresAt(), now).getSeconds();
|
|
||||||
if (secondsPastExpiry <= gracePeriodSeconds) return LicenseStatus.GRACE;
|
|
||||||
return LicenseStatus.EXPIRED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class InstallException extends Exception {
|
|
||||||
public InstallException(String message) {
|
|
||||||
super(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+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);
|
||||||
|
}
|
||||||
@@ -35,6 +35,9 @@ public class GameSystem {
|
|||||||
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||||
private String rulesMarkdown;
|
private String rulesMarkdown;
|
||||||
|
|
||||||
|
/** Version anglaise des règles ({@code rulesMarkdown} = version française). Nullable. */
|
||||||
|
private String rulesMarkdownEn;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
|
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
|
||||||
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
|
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
|
||||||
@@ -161,4 +164,15 @@ public class GameSystem {
|
|||||||
if (a == null || b == null) return a == null && b == null;
|
if (a == null || b == null) return a == null && b == null;
|
||||||
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Règles dans la langue demandée ({@code en} → anglais, sinon français), avec repli sur
|
||||||
|
* l'autre version si celle-ci est vide : un système importé dans une seule langue reste lisible.
|
||||||
|
*/
|
||||||
|
public String rulesFor(String language) {
|
||||||
|
boolean english = "en".equalsIgnoreCase(language);
|
||||||
|
String preferred = english ? rulesMarkdownEn : rulesMarkdown;
|
||||||
|
String fallback = english ? rulesMarkdown : rulesMarkdownEn;
|
||||||
|
return preferred != null && !preferred.isBlank() ? preferred : fallback;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,5 +16,14 @@ import java.util.Map;
|
|||||||
public record RulesImportResult(
|
public record RulesImportResult(
|
||||||
Map<String, String> sections,
|
Map<String, String> sections,
|
||||||
int pageCount,
|
int pageCount,
|
||||||
int ocrPageCount) {
|
int ocrPageCount,
|
||||||
|
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
|
||||||
|
Map<String, Map<String, String>> sectionsByLanguage,
|
||||||
|
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
|
||||||
|
String sourceLanguage) {
|
||||||
|
|
||||||
|
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
|
||||||
|
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
|
||||||
|
this(sections, pageCount, ocrPageCount, Map.of(), null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import lombok.Builder;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Licence Patreon installee dans cette instance LoreMind.
|
|
||||||
* <p>
|
|
||||||
* Singleton (une seule licence par instance, identifiee logiquement par
|
|
||||||
* {@code id = "current"}). Contient le JWT brut emis par le relais OAuth
|
|
||||||
* + les claims extraits a la verification, plus l'etat operationnel
|
|
||||||
* (derniere tentative de refresh, succes/echec).
|
|
||||||
* <p>
|
|
||||||
* <b>Note securite :</b> {@link #rawJwt} est stocke tel quel ; sa signature
|
|
||||||
* Ed25519 est verifiee a chaque lecture. Pas besoin de chiffrement au repos
|
|
||||||
* supplementaire — un attaquant qui a acces a la base a deja l'instance,
|
|
||||||
* et le JWT ne donne aucun pouvoir au-dela du canal beta de cette instance.
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
public class License {
|
|
||||||
|
|
||||||
private String id;
|
|
||||||
|
|
||||||
private String rawJwt;
|
|
||||||
|
|
||||||
private String patreonUserId;
|
|
||||||
|
|
||||||
private String tierId;
|
|
||||||
|
|
||||||
private String instanceId;
|
|
||||||
|
|
||||||
private Instant issuedAt;
|
|
||||||
|
|
||||||
private Instant expiresAt;
|
|
||||||
|
|
||||||
private Instant lastRefreshAttemptAt;
|
|
||||||
|
|
||||||
private boolean lastRefreshSucceeded;
|
|
||||||
|
|
||||||
private boolean betaChannelEnabled;
|
|
||||||
|
|
||||||
private Instant createdAt;
|
|
||||||
|
|
||||||
private Instant updatedAt;
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Claims extraits d'un JWT licence apres verification de signature.
|
|
||||||
* Immuable.
|
|
||||||
*/
|
|
||||||
public record LicenseClaims(
|
|
||||||
String subject,
|
|
||||||
String tierId,
|
|
||||||
String instanceId,
|
|
||||||
Instant issuedAt,
|
|
||||||
Instant expiresAt
|
|
||||||
) {}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Vue immuable de la licence pour exposition vers les couches superieures.
|
|
||||||
* Decouple le domaine du DTO web et permet de calculer le {@link LicenseStatus}
|
|
||||||
* a un instant donne sans muter l'entite.
|
|
||||||
*/
|
|
||||||
public record LicenseSnapshot(
|
|
||||||
LicenseStatus status,
|
|
||||||
String patreonUserId,
|
|
||||||
String tierId,
|
|
||||||
String instanceId,
|
|
||||||
Instant expiresAt,
|
|
||||||
Instant lastRefreshAttemptAt,
|
|
||||||
boolean lastRefreshSucceeded,
|
|
||||||
boolean betaChannelEnabled
|
|
||||||
) {
|
|
||||||
public static LicenseSnapshot none() {
|
|
||||||
return new LicenseSnapshot(LicenseStatus.NONE, null, null, null, null, null, false, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Etat operationnel de la licence vis-a-vis de l'acces beta.
|
|
||||||
* <p>
|
|
||||||
* Calcule a partir de la presence de licence + son JWT exp + grace period.
|
|
||||||
* <ul>
|
|
||||||
* <li>{@link #NONE} : aucune licence installee</li>
|
|
||||||
* <li>{@link #VALID} : JWT non expire, acces beta autorise</li>
|
|
||||||
* <li>{@link #GRACE} : JWT expire mais dans la periode de tolerance ;
|
|
||||||
* acces beta toujours autorise, l'UI doit avertir</li>
|
|
||||||
* <li>{@link #EXPIRED} : au-dela de la grace period, acces beta refuse</li>
|
|
||||||
* <li>{@link #UNVERIFIABLE} : JWT impossible a verifier (cle publique manquante,
|
|
||||||
* signature invalide, claims malformes) — traite comme NONE pour la securite</li>
|
|
||||||
* </ul>
|
|
||||||
*/
|
|
||||||
public enum LicenseStatus {
|
|
||||||
NONE,
|
|
||||||
VALID,
|
|
||||||
GRACE,
|
|
||||||
EXPIRED,
|
|
||||||
UNVERIFIABLE
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package com.loremind.domain.licensing;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Credentials de pull pour un registry Docker, distribues par le relais
|
|
||||||
* apres verification d'un JWT licence valide.
|
|
||||||
* <p>
|
|
||||||
* {@code expiresAt} peut etre {@code null} si le credential est statique
|
|
||||||
* (cas du PAT GHCR partage en MVP) ; sinon, l'instance doit re-demander
|
|
||||||
* de nouveaux credentials avant cette date.
|
|
||||||
*/
|
|
||||||
public record RegistryCredentials(
|
|
||||||
String registry,
|
|
||||||
String username,
|
|
||||||
String password,
|
|
||||||
Instant expiresAt
|
|
||||||
) {}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.RegistryCredentials;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie : ecriture du docker config.json partage avec Watchtower.
|
|
||||||
* <p>
|
|
||||||
* Le fichier sert a Watchtower pour s'authentifier au registry prive (GHCR)
|
|
||||||
* lors du pull des images du canal beta. Volume Docker {@code docker-config}
|
|
||||||
* monte sur Core (en ecriture) et sur Watchtower (en lecture, via la variable
|
|
||||||
* {@code DOCKER_CONFIG}).
|
|
||||||
*/
|
|
||||||
public interface DockerConfigWriter {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ecrit ou met a jour les credentials pour le registry indique.
|
|
||||||
* Cree le fichier s'il n'existe pas, conserve les autres registries deja
|
|
||||||
* presents (en theorie : aucun, mais defensif).
|
|
||||||
*/
|
|
||||||
void writeCredentials(RegistryCredentials credentials) throws IOException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Supprime le fichier de credentials. Appele quand la licence est invalidee
|
|
||||||
* ou que le toggle beta passe a OFF.
|
|
||||||
*/
|
|
||||||
void clear() throws IOException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true si le fichier de creds existe actuellement.
|
|
||||||
*/
|
|
||||||
boolean isPresent();
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.LicenseClaims;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie : verification de signature et extraction des claims
|
|
||||||
* d'un JWT emis par le relais.
|
|
||||||
* <p>
|
|
||||||
* Implemente cote infrastructure avec la cle publique Ed25519 embarquee
|
|
||||||
* (SPKI PEM via configuration {@code licensing.jwt.public-key}).
|
|
||||||
*/
|
|
||||||
public interface JwtVerifier {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifie la signature, l'issuer, l'audience et l'expiration du JWT.
|
|
||||||
* @throws JwtVerificationException si la signature est invalide ou les claims malformes
|
|
||||||
*/
|
|
||||||
LicenseClaims verify(String rawJwt) throws JwtVerificationException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return true si la cle publique est configuree et utilisable.
|
|
||||||
* Permet a l'application de masquer la feature licensing si pas configuree.
|
|
||||||
*/
|
|
||||||
boolean isConfigured();
|
|
||||||
|
|
||||||
class JwtVerificationException extends Exception {
|
|
||||||
public JwtVerificationException(String message) {
|
|
||||||
super(message);
|
|
||||||
}
|
|
||||||
public JwtVerificationException(String message, Throwable cause) {
|
|
||||||
super(message, cause);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.RegistryCredentials;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie vers le service relais OAuth Patreon.
|
|
||||||
* Encapsule les appels HTTP : refresh JWT et fetch registry credentials.
|
|
||||||
*/
|
|
||||||
public interface LicenseRelay {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Demande au relais l'URL OAuth a ouvrir pour connecter le compte Patreon.
|
|
||||||
*/
|
|
||||||
String buildConnectUrl(String instanceId);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Demande au relais de renouveler un JWT existant. Le relais re-verifie
|
|
||||||
* le tier Patreon de l'utilisateur ; renvoie un nouveau JWT si toujours
|
|
||||||
* actif, ou leve {@link RelayException} sinon.
|
|
||||||
*/
|
|
||||||
String refreshToken(String currentJwt) throws RelayException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Demande au relais les credentials de pull du registry beta.
|
|
||||||
*/
|
|
||||||
RegistryCredentials fetchRegistryCredentials(String currentJwt) throws RelayException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Erreurs distinctes emises par le relais. Permet au service application
|
|
||||||
* de differencier "tier expire" (action utilisateur) de "relais down"
|
|
||||||
* (action transitoire, garde la grace period).
|
|
||||||
*/
|
|
||||||
class RelayException extends Exception {
|
|
||||||
private final RelayErrorKind kind;
|
|
||||||
|
|
||||||
public RelayException(RelayErrorKind kind, String message) {
|
|
||||||
super(message);
|
|
||||||
this.kind = kind;
|
|
||||||
}
|
|
||||||
|
|
||||||
public RelayException(RelayErrorKind kind, String message, Throwable cause) {
|
|
||||||
super(message, cause);
|
|
||||||
this.kind = kind;
|
|
||||||
}
|
|
||||||
|
|
||||||
public RelayErrorKind getKind() {
|
|
||||||
return kind;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum RelayErrorKind {
|
|
||||||
/** Le relais est joignable mais refuse : tier non actif, JWT trop ancien, etc. */
|
|
||||||
REJECTED,
|
|
||||||
/** Le relais a renvoye un JWT mais il est invalide / non parsable. */
|
|
||||||
BAD_RESPONSE,
|
|
||||||
/** Le relais est injoignable / 5xx / timeout. */
|
|
||||||
TRANSIENT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package com.loremind.domain.licensing.ports;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.License;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Port de sortie pour la persistance de la licence installee.
|
|
||||||
* <p>
|
|
||||||
* Une seule licence par instance ({@code id = "current"} par convention).
|
|
||||||
*/
|
|
||||||
public interface LicenseRepository {
|
|
||||||
|
|
||||||
Optional<License> findCurrent();
|
|
||||||
|
|
||||||
License save(License license);
|
|
||||||
|
|
||||||
void deleteCurrent();
|
|
||||||
}
|
|
||||||
@@ -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.base-url}") String baseUrl,
|
||||||
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
|
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
|
||||||
@Value("${brain.paths.import-campaign:/import/campaign/stream}") String importCampaignStreamPath) {
|
@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.sse = new BrainSseImportSupport(objectMapper);
|
||||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||||
this.importCampaignStreamPath = importCampaignStreamPath;
|
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:/import/rules}") String importRulesPath,
|
||||||
@Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) {
|
@Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) {
|
||||||
this.restTemplate = restTemplate;
|
this.restTemplate = restTemplate;
|
||||||
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
|
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
|
||||||
this.sse = new BrainSseImportSupport(objectMapper);
|
this.sse = new BrainSseImportSupport(objectMapper);
|
||||||
this.baseUrl = baseUrl;
|
this.baseUrl = baseUrl;
|
||||||
this.importTimeoutSeconds = importTimeoutSeconds;
|
this.importTimeoutSeconds = importTimeoutSeconds;
|
||||||
@@ -106,7 +106,9 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
return new RulesImportResult(
|
return new RulesImportResult(
|
||||||
Map.copyOf(response.getSections()),
|
Map.copyOf(response.getSections()),
|
||||||
response.getPageCount(),
|
response.getPageCount(),
|
||||||
response.getOcrPageCount());
|
response.getOcrPageCount(),
|
||||||
|
response.getSectionsByLanguage() != null ? response.getSectionsByLanguage() : Map.of(),
|
||||||
|
response.getSourceLanguage());
|
||||||
} catch (ResourceAccessException e) {
|
} catch (ResourceAccessException e) {
|
||||||
throw new RulesImportException(
|
throw new RulesImportException(
|
||||||
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
||||||
@@ -218,12 +220,23 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
callbacks.onDone().accept(new RulesImportResult(
|
callbacks.onDone().accept(new RulesImportResult(
|
||||||
toStringMap(node.path("sections")),
|
toStringMap(node.path("sections")),
|
||||||
node.path("page_count").asInt(),
|
node.path("page_count").asInt(),
|
||||||
node.path("ocr_page_count").asInt()));
|
node.path("ocr_page_count").asInt(),
|
||||||
|
toLanguageMap(node.path("sections_by_language")),
|
||||||
|
node.path("source_language").asText(null)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Helpers -------------------------------------------------------------
|
// --- Helpers -------------------------------------------------------------
|
||||||
|
|
||||||
|
/** {code langue → sections} : règles en deux langues (vide si le Brain ne les fournit pas). */
|
||||||
|
private Map<String, Map<String, String>> toLanguageMap(JsonNode node) {
|
||||||
|
Map<String, Map<String, String>> out = new java.util.LinkedHashMap<>();
|
||||||
|
if (node != null && node.isObject()) {
|
||||||
|
node.fields().forEachRemaining(e -> out.put(e.getKey(), toStringMap(e.getValue())));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
private List<String> toStringList(JsonNode array) {
|
private List<String> toStringList(JsonNode array) {
|
||||||
List<String> out = new ArrayList<>();
|
List<String> out = new ArrayList<>();
|
||||||
if (array != null && array.isArray()) {
|
if (array != null && array.isArray()) {
|
||||||
|
|||||||
@@ -23,4 +23,11 @@ class BrainRulesImportResponse {
|
|||||||
|
|
||||||
@JsonProperty("ocr_page_count")
|
@JsonProperty("ocr_page_count")
|
||||||
private int ocrPageCount;
|
private int ocrPageCount;
|
||||||
|
|
||||||
|
/** Règles en deux langues : {code langue → sections} (absent d'un Brain antérieur). */
|
||||||
|
@JsonProperty("sections_by_language")
|
||||||
|
private Map<String, Map<String, String>> sectionsByLanguage;
|
||||||
|
|
||||||
|
@JsonProperty("source_language")
|
||||||
|
private String sourceLanguage;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
|||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
import org.springframework.http.codec.ServerSentEvent;
|
import org.springframework.http.codec.ServerSentEvent;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
@@ -25,6 +26,21 @@ final class BrainSseImportSupport {
|
|||||||
/** Champ JSON standard des events SSE du Brain portant un message lisible. */
|
/** Champ JSON standard des events SSE du Brain portant un message lisible. */
|
||||||
private static final String MESSAGE_FIELD = "message";
|
private static final String MESSAGE_FIELD = "message";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Taille max d'UN évènement SSE. L'évènement {@code done} porte tout le résultat de
|
||||||
|
* l'import (règles d'un livre entier, en deux langues ; arbre complet d'une campagne) :
|
||||||
|
* la limite par défaut de WebClient (256 Ko) faisait échouer l'import au tout dernier
|
||||||
|
* moment (DataBufferLimitException), après des minutes d'analyse.
|
||||||
|
*/
|
||||||
|
static final int MAX_EVENT_BYTES = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
/** WebClient d'import : évènements volumineux acceptés (voir {@link #MAX_EVENT_BYTES}). */
|
||||||
|
static WebClient importWebClient(WebClient.Builder builder, String baseUrl) {
|
||||||
|
return builder.baseUrl(baseUrl)
|
||||||
|
.codecs(c -> c.defaultCodecs().maxInMemorySize(MAX_EVENT_BYTES))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
BrainSseImportSupport(ObjectMapper objectMapper) {
|
BrainSseImportSupport(ObjectMapper objectMapper) {
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package com.loremind.infrastructure.desktop;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.awt.Desktop;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
import java.nio.channels.FileChannel;
|
import java.nio.channels.FileChannel;
|
||||||
import java.nio.channels.FileLock;
|
import java.nio.channels.FileLock;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
@@ -102,14 +104,20 @@ public final class DesktopSingleInstance {
|
|||||||
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */
|
/**
|
||||||
|
* Ouvre le navigateur par defaut sur une URL quelconque : API standard de Java
|
||||||
|
* (ShellExecute sous Windows), sinon commande du systeme. Plus de {@code rundll32
|
||||||
|
* url.dll} : outil Windows tres detourne par les logiciels malveillants, que des
|
||||||
|
* antivirus signalaient (Avast « IDP.Generic ») quand un programme peu connu le lance.
|
||||||
|
*/
|
||||||
public static void openUrl(String url) {
|
public static void openUrl(String url) {
|
||||||
|
if (browseWithJava(url)) return;
|
||||||
try {
|
try {
|
||||||
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||||
ProcessBuilder pb;
|
ProcessBuilder pb;
|
||||||
if (os.contains("win")) {
|
if (os.contains("win")) {
|
||||||
// rundll32 : ouverture d'URL fiable sans dependance graphique Java.
|
// « start » de cmd ; le "" est le titre de fenetre attendu avant l'URL.
|
||||||
pb = new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", url);
|
pb = new ProcessBuilder("cmd", "/c", "start", "", url);
|
||||||
} else if (os.contains("mac")) {
|
} else if (os.contains("mac")) {
|
||||||
pb = new ProcessBuilder("open", url);
|
pb = new ProcessBuilder("open", url);
|
||||||
} else {
|
} else {
|
||||||
@@ -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. */
|
/** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */
|
||||||
public static void openFolder(Path dir) {
|
public static void openFolder(Path dir) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ import java.util.Optional;
|
|||||||
* <p>
|
* <p>
|
||||||
* {@code /releases/latest} ne renvoie que les releases stables (pas les
|
* {@code /releases/latest} ne renvoie que les releases stables (pas les
|
||||||
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
|
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
|
||||||
|
* Une version BETA (le canal beta est libre : chaque beta est publiee en
|
||||||
|
* prerelease GitHub) interroge la liste complete des releases, pour etre
|
||||||
|
* prevenue de la beta suivante comme de la version stable qui la remplace.
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
@Profile("local")
|
@Profile("local")
|
||||||
@@ -73,17 +76,18 @@ public class DesktopUpdateService {
|
|||||||
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
|
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
|
||||||
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
|
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
|
||||||
|
|
||||||
|
boolean beta = isPrerelease(currentVersion);
|
||||||
ResponseEntity<JsonNode> resp = http.exchange(
|
ResponseEntity<JsonNode> resp = http.exchange(
|
||||||
releasesApiUrl, HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
beta ? allReleasesUrl(releasesApiUrl) : releasesApiUrl,
|
||||||
JsonNode body = resp.getBody();
|
HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
||||||
if (body == null || body.path("tag_name").isMissingNode()) {
|
JsonNode release = beta ? newestRelease(resp.getBody()) : resp.getBody();
|
||||||
|
if (release == null || release.path("tag_name").isMissingNode()) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
String tag = body.path("tag_name").asText(""); // ex: "v0.15.0"
|
String latest = version(release); // ex: "0.15.0"
|
||||||
String releaseUrl = body.path("html_url").asText(null); // page de la release
|
String releaseUrl = release.path("html_url").asText(null); // page de la release
|
||||||
String latest = tag.startsWith("v") ? tag.substring(1) : tag;
|
|
||||||
|
|
||||||
if (!latest.isBlank() && compareSemver(currentVersion, latest) < 0) {
|
if (!latest.isBlank() && (beta ? compareVersions(currentVersion, latest) : compareSemver(currentVersion, latest)) < 0) {
|
||||||
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
|
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
|
||||||
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
|
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
|
||||||
}
|
}
|
||||||
@@ -99,6 +103,66 @@ public class DesktopUpdateService {
|
|||||||
/** Infos d'une mise a jour disponible. */
|
/** Infos d'une mise a jour disponible. */
|
||||||
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
|
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
|
||||||
|
|
||||||
|
static boolean isPrerelease(String version) {
|
||||||
|
return version.split("\\+", 2)[0].contains("-");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code .../releases/latest} -> {@code .../releases?per_page=30} (prereleases incluses). */
|
||||||
|
static String allReleasesUrl(String latestUrl) {
|
||||||
|
String base = latestUrl.endsWith("/latest") ? latestUrl.substring(0, latestUrl.length() - "/latest".length()) : latestUrl;
|
||||||
|
return base + "?per_page=30";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String version(JsonNode release) {
|
||||||
|
String tag = release.path("tag_name").asText("");
|
||||||
|
return tag.startsWith("v") ? tag.substring(1) : tag;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release publiee la plus recente (stable ou beta), brouillons exclus. */
|
||||||
|
@Nullable
|
||||||
|
static JsonNode newestRelease(@Nullable JsonNode releases) {
|
||||||
|
if (releases == null || !releases.isArray()) return null;
|
||||||
|
JsonNode best = null;
|
||||||
|
for (JsonNode r : releases) {
|
||||||
|
if (r.path("draft").asBoolean(false) || version(r).isBlank()) continue;
|
||||||
|
if (best == null || compareVersions(version(best), version(r)) < 0) best = r;
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Comme {@link #compareSemver} mais tient compte du suffixe : a version egale,
|
||||||
|
* la stable passe devant la beta (1.5.0-beta < 1.5.0), et deux betas se
|
||||||
|
* comparent par leur numero (1.5.0-beta < 1.5.0-beta.2 < 1.5.0-beta.10).
|
||||||
|
*/
|
||||||
|
static int compareVersions(String a, String b) {
|
||||||
|
int cmp = compareSemver(a, b);
|
||||||
|
if (cmp != 0) return cmp;
|
||||||
|
String sa = suffix(a);
|
||||||
|
String sb = suffix(b);
|
||||||
|
if (sa.isEmpty() || sb.isEmpty()) return Boolean.compare(sa.isEmpty(), sb.isEmpty());
|
||||||
|
return compareSuffixes(sa, sb);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String suffix(String version) {
|
||||||
|
String noBuild = version.split("\\+", 2)[0];
|
||||||
|
int dash = noBuild.indexOf('-');
|
||||||
|
return dash < 0 ? "" : noBuild.substring(dash + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compare des suffixes en traitant les nombres comme des nombres (beta.10 > beta.2). */
|
||||||
|
private static int compareSuffixes(String a, String b) {
|
||||||
|
String[] pa = a.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
|
||||||
|
String[] pb = b.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
|
||||||
|
for (int i = 0; i < Math.min(pa.length, pb.length); i++) {
|
||||||
|
boolean na = Character.isDigit(pa[i].charAt(0));
|
||||||
|
boolean nb = Character.isDigit(pb[i].charAt(0));
|
||||||
|
int cmp = na && nb ? Long.compare(Long.parseLong(pa[i]), Long.parseLong(pb[i])) : pa[i].compareTo(pb[i]);
|
||||||
|
if (cmp != 0) return cmp;
|
||||||
|
}
|
||||||
|
return Integer.compare(pa.length, pb.length);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
|
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
|
||||||
* @return <0 si a<b, 0 si egales, >0 si a>b.
|
* @return <0 si a<b, 0 si egales, >0 si a>b.
|
||||||
|
|||||||
+43
-21
@@ -26,9 +26,16 @@ import java.util.concurrent.TimeUnit;
|
|||||||
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
|
* 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).
|
* (réglage système, jamais modifié par l'application).
|
||||||
* <p>
|
* <p>
|
||||||
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
|
* Les scripts sont passés EN CLAIR ({@code -Command}, une ligne) : un script encodé
|
||||||
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
|
* ({@code -EncodedCommand}) accompagné de {@code -ExecutionPolicy Bypass} est la signature
|
||||||
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
|
* 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>
|
* <p>
|
||||||
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows.
|
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows.
|
||||||
*/
|
*/
|
||||||
@@ -69,14 +76,8 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
public FirewallFixOutcome allowThroughFirewall() {
|
public FirewallFixOutcome allowThroughFirewall() {
|
||||||
String program = currentProgram();
|
String program = currentProgram();
|
||||||
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
|
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 {
|
try {
|
||||||
int exit = runPowerShell(outer, ELEVATION_TIMEOUT_S).exitCode();
|
int exit = runPowerShell(elevationScript(program), ELEVATION_TIMEOUT_S).exitCode();
|
||||||
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
|
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
|
||||||
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
|
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
|
||||||
log.info("Accès distant : autorisation pare-feu → {}", outcome);
|
log.info("Accès distant : autorisation pare-feu → {}", outcome);
|
||||||
@@ -103,24 +104,37 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
|
|
||||||
// --- Scripts --------------------------------------------------------------------------
|
// --- 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) {
|
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.
|
// 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"
|
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
|
||||||
+ "$p = '" + psQuote(program) + "'\n"
|
+ "$p = '" + psQuote(program) + "'; "
|
||||||
+ "$nets =@(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
|
+ "$nets = @(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
|
||||||
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } })\n"
|
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } }); "
|
||||||
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
||||||
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
||||||
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
||||||
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\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) :
|
// 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.
|
// ils filtrent en plus de Windows, avec des règles qu'on ne peut pas lire.
|
||||||
+ "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | "
|
+ "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | "
|
||||||
+ "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' })\n"
|
+ "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' }); "
|
||||||
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
|
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
|
||||||
+ "ConvertTo-Json -Depth 4 -Compress\n";
|
+ "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 + " }";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -183,9 +197,9 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
|
|
||||||
private record Result(int exitCode, String output) {}
|
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 {
|
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
|
||||||
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive",
|
Process process = new ProcessBuilder(command(script))
|
||||||
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
|
|
||||||
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
||||||
.start();
|
.start();
|
||||||
process.getOutputStream().close();
|
process.getOutputStream().close();
|
||||||
@@ -204,6 +218,14 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
return new Result(process.exitValue(), output.join());
|
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() {
|
private static boolean isWindows() {
|
||||||
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
|
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
+3
@@ -37,6 +37,9 @@ public class GameSystemJpaEntity {
|
|||||||
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
||||||
private String rulesMarkdown;
|
private String rulesMarkdown;
|
||||||
|
|
||||||
|
@Column(name = "rules_markdown_en", columnDefinition = "TEXT")
|
||||||
|
private String rulesMarkdownEn;
|
||||||
|
|
||||||
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
|
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
|
||||||
@Convert(converter = TemplateFieldListJsonConverter.class)
|
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||||
@Column(name = "character_template", columnDefinition = "TEXT")
|
@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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-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> {
|
|
||||||
}
|
|
||||||
+2
@@ -60,6 +60,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.name(e.getName())
|
.name(e.getName())
|
||||||
.description(e.getDescription())
|
.description(e.getDescription())
|
||||||
.rulesMarkdown(e.getRulesMarkdown())
|
.rulesMarkdown(e.getRulesMarkdown())
|
||||||
|
.rulesMarkdownEn(e.getRulesMarkdownEn())
|
||||||
.characterTemplate(e.getCharacterTemplate() != null
|
.characterTemplate(e.getCharacterTemplate() != null
|
||||||
? new java.util.ArrayList<>(e.getCharacterTemplate())
|
? new java.util.ArrayList<>(e.getCharacterTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
@@ -84,6 +85,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.name(g.getName())
|
.name(g.getName())
|
||||||
.description(g.getDescription())
|
.description(g.getDescription())
|
||||||
.rulesMarkdown(g.getRulesMarkdown())
|
.rulesMarkdown(g.getRulesMarkdown())
|
||||||
|
.rulesMarkdownEn(g.getRulesMarkdownEn())
|
||||||
.characterTemplate(g.getCharacterTemplate() != null
|
.characterTemplate(g.getCharacterTemplate() != null
|
||||||
? new java.util.ArrayList<>(g.getCharacterTemplate())
|
? new java.util.ArrayList<>(g.getCharacterTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -577,7 +577,8 @@ public class ExportService {
|
|||||||
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
||||||
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
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) {
|
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ class LoreContentInserter {
|
|||||||
e.setName(d.name());
|
e.setName(d.name());
|
||||||
e.setDescription(d.description());
|
e.setDescription(d.description());
|
||||||
e.setRulesMarkdown(d.rulesMarkdown());
|
e.setRulesMarkdown(d.rulesMarkdown());
|
||||||
|
e.setRulesMarkdownEn(d.rulesMarkdownEn());
|
||||||
e.setCharacterTemplate(d.characterTemplate());
|
e.setCharacterTemplate(d.characterTemplate());
|
||||||
e.setNpcTemplate(d.npcTemplate());
|
e.setNpcTemplate(d.npcTemplate());
|
||||||
e.setEnemyTemplate(d.enemyTemplate());
|
e.setEnemyTemplate(d.enemyTemplate());
|
||||||
|
|||||||
@@ -77,7 +77,9 @@ public record ContentExport(
|
|||||||
List<TemplateField> enemyTemplate,
|
List<TemplateField> enemyTemplate,
|
||||||
String foundryActorType,
|
String foundryActorType,
|
||||||
String author,
|
String author,
|
||||||
boolean isPublic
|
boolean isPublic,
|
||||||
|
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
|
||||||
|
String rulesMarkdownEn
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record LoreDto(
|
public record LoreDto(
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
|||||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||||
import com.loremind.domain.campaigncontext.quest.Prerequisite;
|
import com.loremind.domain.campaigncontext.quest.Prerequisite;
|
||||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.domain.campaigncontext.structure.Room;
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
@@ -540,11 +541,12 @@ public class PdfExportService {
|
|||||||
List<ArcJpaEntity> arcs = st.visibleArcs;
|
List<ArcJpaEntity> arcs = st.visibleArcs;
|
||||||
if (arcs.isEmpty()) return;
|
if (arcs.isEmpty()) return;
|
||||||
|
|
||||||
// Mode plat (miroir de l'UI Niveau 0) : 1 arc d'UN SEUL chapitre → on masque les
|
// Mode plat (miroir de l'UI Niveau 0) : 1 arc linéaire d'UN SEUL chapitre, tous deux
|
||||||
// niveaux Arc/Chapitre et on présente les scènes À PLAT (cohérent avec la sidebar).
|
// VIDES (créés d'office) → on masque les niveaux Arc/Chapitre et on présente les
|
||||||
if (arcs.size() == 1) {
|
// scènes À PLAT. Un arc ou un chapitre écrit (méthode guidée…) garde ses en-têtes.
|
||||||
|
if (arcs.size() == 1 && arcs.get(0).getType() != ArcType.HUB) {
|
||||||
List<ChapterJpaEntity> only = st.chaptersByArc.get(arcs.get(0).getId());
|
List<ChapterJpaEntity> only = st.chaptersByArc.get(arcs.get(0).getId());
|
||||||
if (only.size() == 1) {
|
if (only.size() == 1 && isBare(arcs.get(0)) && isBare(only.get(0))) {
|
||||||
narrativeFlat(ctx, st, arcs.get(0), only.get(0));
|
narrativeFlat(ctx, st, arcs.get(0), only.get(0));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -561,6 +563,28 @@ public class PdfExportService {
|
|||||||
ctx.endColumns();
|
ctx.endColumns();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Aucun contenu d'ecriture dans l'arc (son nom ne compte pas : « Arc principal » est cree d'office). */
|
||||||
|
static boolean isBare(ArcJpaEntity arc) {
|
||||||
|
return allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(),
|
||||||
|
arc.getResolution(), arc.getGmNotes(), arc.getHiddenTruth(), arc.getHooks())
|
||||||
|
&& isEmpty(arc.getIllustrationImageIds());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aucun contenu d'ecriture dans le chapitre (son nom ne compte pas : « Chapitre 1 » est cree d'office). */
|
||||||
|
static boolean isBare(ChapterJpaEntity ch) {
|
||||||
|
return allBlank(ch.getDescription(), ch.getPlayerObjectives(), ch.getNarrativeStakes(), ch.getGmNotes())
|
||||||
|
&& isEmpty(ch.getIllustrationImageIds());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean allBlank(String... values) {
|
||||||
|
for (String v : values) if (notBlank(v)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isEmpty(List<String> list) {
|
||||||
|
return list == null || list.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
/** Arborescence des signets Arc -> Chapitre pour la partie narrative complete (mode non plat). */
|
/** Arborescence des signets Arc -> Chapitre pour la partie narrative complete (mode non plat). */
|
||||||
private void narrativeBookmarks(Ctx ctx, Structure st, List<ArcJpaEntity> arcs) {
|
private void narrativeBookmarks(Ctx ctx, Structure st, List<ArcJpaEntity> arcs) {
|
||||||
StringBuilder arcBms = new StringBuilder();
|
StringBuilder arcBms = new StringBuilder();
|
||||||
|
|||||||
+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;
|
package com.loremind.infrastructure.updates;
|
||||||
|
|
||||||
import com.loremind.application.licensing.LicenseService;
|
import com.loremind.application.channel.ChannelSwitcherService;
|
||||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
import com.loremind.application.channel.ChannelSwitcherService.Channel;
|
||||||
import com.loremind.domain.licensing.LicenseStatus;
|
|
||||||
import com.loremind.domain.licensing.RegistryCredentials;
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
@@ -24,10 +22,8 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Detection des mises a jour disponibles + declenchement via Watchtower.
|
* Detection des mises a jour disponibles + declenchement via Watchtower.
|
||||||
@@ -59,8 +55,9 @@ public class UpdateCheckService {
|
|||||||
private final List<String> images;
|
private final List<String> images;
|
||||||
private final String watchtowerUrl;
|
private final String watchtowerUrl;
|
||||||
private final String watchtowerToken;
|
private final String watchtowerToken;
|
||||||
|
private final String betaRegistry;
|
||||||
private final List<String> betaImages;
|
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. */
|
/** Version semver courante du binaire (ex: "0.8.0"). Source de verite. */
|
||||||
private final String currentVersion;
|
private final String currentVersion;
|
||||||
|
|
||||||
@@ -70,8 +67,9 @@ public class UpdateCheckService {
|
|||||||
@Value("${update-check.images:}") String imagesCsv,
|
@Value("${update-check.images:}") String imagesCsv,
|
||||||
@Value("${update-check.watchtower-url:http://watchtower:8080}") String watchtowerUrl,
|
@Value("${update-check.watchtower-url:http://watchtower:8080}") String watchtowerUrl,
|
||||||
@Value("${update-check.watchtower-token:}") String watchtowerToken,
|
@Value("${update-check.watchtower-token:}") String watchtowerToken,
|
||||||
@Value("${licensing.beta.images:}") String betaImagesCsv,
|
@Value("${update-check.beta-registry:ghcr.io}") String betaRegistry,
|
||||||
LicenseService licenseService,
|
@Value("${update-check.beta-images:}") String betaImagesCsv,
|
||||||
|
ChannelSwitcherService channels,
|
||||||
@Nullable BuildProperties buildProperties) {
|
@Nullable BuildProperties buildProperties) {
|
||||||
this.http = builder
|
this.http = builder
|
||||||
.connectTimeout(Duration.ofSeconds(5))
|
.connectTimeout(Duration.ofSeconds(5))
|
||||||
@@ -81,8 +79,9 @@ public class UpdateCheckService {
|
|||||||
this.images = parseImages(imagesCsv);
|
this.images = parseImages(imagesCsv);
|
||||||
this.watchtowerUrl = watchtowerUrl;
|
this.watchtowerUrl = watchtowerUrl;
|
||||||
this.watchtowerToken = watchtowerToken;
|
this.watchtowerToken = watchtowerToken;
|
||||||
|
this.betaRegistry = normalizeRegistry(betaRegistry);
|
||||||
this.betaImages = parseImages(betaImagesCsv);
|
this.betaImages = parseImages(betaImagesCsv);
|
||||||
this.licenseService = licenseService;
|
this.channels = channels;
|
||||||
this.currentVersion = buildProperties != null ? buildProperties.getVersion() : null;
|
this.currentVersion = buildProperties != null ? buildProperties.getVersion() : null;
|
||||||
log.info("Update check init - registry={} images={} currentVersion={}",
|
log.info("Update check init - registry={} images={} currentVersion={}",
|
||||||
this.registry, this.images, this.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() {
|
public BetaStatus checkBeta() {
|
||||||
if (!licenseService.isLicensingEnabled()) {
|
if (channels.getCurrentChannel() != Channel.BETA) {
|
||||||
return BetaStatus.disabled("licensing-not-configured");
|
return BetaStatus.disabled("not-on-beta-channel");
|
||||||
}
|
}
|
||||||
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
|
if (betaImages.isEmpty() || betaRegistry.isEmpty()) {
|
||||||
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()) {
|
|
||||||
return BetaStatus.disabled("no-beta-images-configured");
|
return BetaStatus.disabled("no-beta-images-configured");
|
||||||
}
|
}
|
||||||
|
ImagesEvaluation ev = evaluateImages(betaImages, betaRegistry, null);
|
||||||
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);
|
|
||||||
return new BetaStatus(true, ev.anyUpdate(), ev.anyUnknown(),
|
return new BetaStatus(true, ev.anyUpdate(), ev.anyUnknown(),
|
||||||
ev.statuses(), Instant.now(), null);
|
ev.statuses(), Instant.now(), null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ import java.util.Map;
|
|||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* <p>Important : ne court-circuite PAS les try/catch locaux des controllers
|
* <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.
|
* Ce handler n'attrape QUE ce qui a echappe au catch local.
|
||||||
*/
|
*/
|
||||||
@RestControllerAdvice
|
@RestControllerAdvice
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ public class RemoteAccessFilter extends OncePerRequestFilter {
|
|||||||
private static final List<String> PUBLIC_PATHS = List.of(
|
private static final List<String> PUBLIC_PATHS = List.of(
|
||||||
"/api/config", "/api/version", "/api/remote-access/pair", "/api/remote-access/session");
|
"/api/config", "/api/version", "/api/remote-access/pair", "/api/remote-access/session");
|
||||||
private static final List<String> LOCAL_ONLY_PREFIXES = List.of(
|
private static final List<String> LOCAL_ONLY_PREFIXES = List.of(
|
||||||
"/api/settings", "/api/admin", "/api/license");
|
"/api/settings", "/api/admin");
|
||||||
|
|
||||||
private final RemoteAccessService remoteAccessService;
|
private final RemoteAccessService remoteAccessService;
|
||||||
|
|
||||||
|
|||||||
@@ -85,7 +85,6 @@ public class SecurityConfig {
|
|||||||
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
||||||
.requestMatchers("/api/settings/**").hasRole(ROLE_ADMIN)
|
.requestMatchers("/api/settings/**").hasRole(ROLE_ADMIN)
|
||||||
.requestMatchers("/api/admin/**").hasRole(ROLE_ADMIN)
|
.requestMatchers("/api/admin/**").hasRole(ROLE_ADMIN)
|
||||||
.requestMatchers("/api/license/**").hasRole(ROLE_ADMIN)
|
|
||||||
.anyRequest().permitAll()
|
.anyRequest().permitAll()
|
||||||
)
|
)
|
||||||
.httpBasic(basic -> {});
|
.httpBasic(basic -> {});
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.core.task.TaskDecorator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Langue de l'utilisateur dans les tâches de fond : Spring Boot applique ce décorateur unique
|
||||||
|
* à l'exécuteur auto-configuré ({@code applicationTaskExecutor}) utilisé par les flux SSE.
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class UserLanguageConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public TaskDecorator userLanguageTaskDecorator() {
|
||||||
|
return new UserLanguageTaskDecorator();
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/** Langue courante lue dans {@link UserLanguageHolder} (requête HTTP, ou tâche de fond décorée). */
|
||||||
|
@Component
|
||||||
|
public class UserLanguageCurrentLanguage implements CurrentLanguage {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String get() {
|
||||||
|
return UserLanguageHolder.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import org.springframework.core.task.TaskDecorator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relaie la langue de l'utilisateur ({@link UserLanguageHolder}, un ThreadLocal) du thread
|
||||||
|
* de la requête HTTP vers le thread de fond qui exécute la tâche.
|
||||||
|
* <p>
|
||||||
|
* Sans lui, les traitements longs lancés dans {@code applicationTaskExecutor} (imports de PDF,
|
||||||
|
* ateliers, chat IA en streaming…) lisaient la valeur par défaut du ThreadLocal sur leur
|
||||||
|
* propre thread : le Brain rédigeait toujours en français, même avec l'interface en anglais.
|
||||||
|
* Spring Boot associe automatiquement ce décorateur à l'exécuteur auto-configuré.
|
||||||
|
*/
|
||||||
|
public class UserLanguageTaskDecorator implements TaskDecorator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Runnable decorate(Runnable runnable) {
|
||||||
|
String language = UserLanguageHolder.get(); // lu sur le thread de la requête
|
||||||
|
return () -> {
|
||||||
|
String previous = UserLanguageHolder.get();
|
||||||
|
UserLanguageHolder.set(language);
|
||||||
|
try {
|
||||||
|
runnable.run();
|
||||||
|
} finally {
|
||||||
|
// Threads réutilisés par le pool : on ne laisse pas la langue fuir vers la tâche suivante.
|
||||||
|
UserLanguageHolder.set(previous);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -257,6 +257,7 @@ public class GameSystemController {
|
|||||||
dto.getName(),
|
dto.getName(),
|
||||||
dto.getDescription(),
|
dto.getDescription(),
|
||||||
dto.getRulesMarkdown(),
|
dto.getRulesMarkdown(),
|
||||||
|
dto.getRulesMarkdownEn(),
|
||||||
templateFieldMapper.toDomainList(dto.getCharacterTemplate()),
|
templateFieldMapper.toDomainList(dto.getCharacterTemplate()),
|
||||||
templateFieldMapper.toDomainList(dto.getNpcTemplate()),
|
templateFieldMapper.toDomainList(dto.getNpcTemplate()),
|
||||||
templateFieldMapper.toDomainList(dto.getEnemyTemplate()),
|
templateFieldMapper.toDomainList(dto.getEnemyTemplate()),
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.campaigncontext.GuidedAssistService;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IA des méthodes guidées : propose des réponses aux questions d'une méthode à partir de
|
||||||
|
* l'idée de départ du MJ. Rien n'est enregistré.
|
||||||
|
*
|
||||||
|
* <p>{@code POST /api/campaigns/{campaignId}/guided-assist} → {@code {answers: {cle: valeur}}} ;
|
||||||
|
* 400 sans question, 404 campagne inconnue, 502 si l'IA est indisponible.</p>
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/campaigns/{campaignId}/guided-assist")
|
||||||
|
public class GuidedAssistController {
|
||||||
|
|
||||||
|
/** Corps : la méthode (nom, principe), l'idée, les questions et les réponses déjà écrites. */
|
||||||
|
public record SuggestRequest(String methodName, String principle, String idea,
|
||||||
|
List<Question> questions, Map<String, String> existing) {}
|
||||||
|
|
||||||
|
public record SuggestResponse(Map<String, String> answers) {}
|
||||||
|
|
||||||
|
private final GuidedAssistService service;
|
||||||
|
private final CampaignRepository campaignRepository;
|
||||||
|
|
||||||
|
public GuidedAssistController(GuidedAssistService service, CampaignRepository campaignRepository) {
|
||||||
|
this.service = service;
|
||||||
|
this.campaignRepository = campaignRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<SuggestResponse> suggest(@PathVariable String campaignId, @RequestBody SuggestRequest body) {
|
||||||
|
if (!campaignRepository.existsById(campaignId)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return ResponseEntity.ok(new SuggestResponse(service.suggest(campaignId, body.methodName(),
|
||||||
|
body.principle(), body.idea(), body.questions(), body.existing())));
|
||||||
|
} catch (NarrativeAssistException e) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
package com.loremind.infrastructure.web.controller;
|
|
||||||
|
|
||||||
import com.loremind.application.licensing.ChannelSwitcherService;
|
|
||||||
import com.loremind.application.licensing.LicenseService;
|
|
||||||
import com.loremind.application.licensing.LicenseService.InstallException;
|
|
||||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
|
||||||
import com.loremind.infrastructure.web.dto.licensing.ChannelStatusDTO;
|
|
||||||
import com.loremind.infrastructure.web.dto.licensing.LicenseStatusDTO;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Endpoints de gestion de la licence Patreon.
|
|
||||||
*
|
|
||||||
* <ul>
|
|
||||||
* <li>{@code GET /api/license} : etat courant (status, tier, expiration...)</li>
|
|
||||||
* <li>{@code GET /api/license/connect-url} : URL OAuth a ouvrir dans le navigateur</li>
|
|
||||||
* <li>{@code POST /api/license/install} : colle un JWT recu du relais</li>
|
|
||||||
* <li>{@code DELETE /api/license} : deconnecte Patreon (efface la licence)</li>
|
|
||||||
* <li>{@code POST /api/license/refresh} : force un refresh manuel</li>
|
|
||||||
* <li>{@code PUT /api/license/beta-channel} : active/desactive le canal beta</li>
|
|
||||||
* </ul>
|
|
||||||
*/
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/api/license")
|
|
||||||
public class LicenseController {
|
|
||||||
|
|
||||||
/** Clé du message d'erreur dans le body JSON — contrat lu par le frontend. */
|
|
||||||
private static final String ERROR_KEY = "error";
|
|
||||||
|
|
||||||
private final LicenseService licenseService;
|
|
||||||
private final ChannelSwitcherService channelSwitcher;
|
|
||||||
|
|
||||||
public LicenseController(LicenseService licenseService, ChannelSwitcherService channelSwitcher) {
|
|
||||||
this.licenseService = licenseService;
|
|
||||||
this.channelSwitcher = channelSwitcher;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping
|
|
||||||
public LicenseStatusDTO getStatus() {
|
|
||||||
boolean enabled = licenseService.isLicensingEnabled();
|
|
||||||
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
|
|
||||||
return LicenseStatusDTO.from(enabled, snap);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/connect-url")
|
|
||||||
public Map<String, String> getConnectUrl() {
|
|
||||||
return Map.of("url", licenseService.buildConnectUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/install")
|
|
||||||
public ResponseEntity<Object> install(@RequestBody InstallRequest request) {
|
|
||||||
if (request == null || request.jwt() == null || request.jwt().isBlank()) {
|
|
||||||
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing jwt"));
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
LicenseSnapshot snap = licenseService.installToken(request.jwt());
|
|
||||||
return ResponseEntity.ok(LicenseStatusDTO.from(true, snap));
|
|
||||||
} catch (InstallException e) {
|
|
||||||
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, e.getMessage()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping
|
|
||||||
public ResponseEntity<Void> disconnect() {
|
|
||||||
licenseService.disconnect();
|
|
||||||
return ResponseEntity.noContent().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/refresh")
|
|
||||||
public ResponseEntity<LicenseStatusDTO> refresh() {
|
|
||||||
licenseService.forceRefresh();
|
|
||||||
boolean enabled = licenseService.isLicensingEnabled();
|
|
||||||
return ResponseEntity.ok(LicenseStatusDTO.from(enabled, licenseService.getCurrentSnapshot()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping("/beta-channel")
|
|
||||||
public ResponseEntity<Object> setBetaChannel(@RequestBody BetaChannelRequest request) {
|
|
||||||
if (request == null) {
|
|
||||||
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing body"));
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
LicenseSnapshot snap = licenseService.setBetaChannelEnabled(request.enabled());
|
|
||||||
return ResponseEntity.ok(LicenseStatusDTO.from(true, snap));
|
|
||||||
} catch (IllegalStateException e) {
|
|
||||||
return ResponseEntity.status(409).body(Map.of(ERROR_KEY, e.getMessage()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Bascule de canal (stable <-> beta) via sidecar switcher ────────────
|
|
||||||
//
|
|
||||||
// Le flux :
|
|
||||||
// 1. UI POST /api/license/channel/switch { channel: "beta" }
|
|
||||||
// 2. Core valide la licence (refus si target=beta sans Patreon actif)
|
|
||||||
// 3. Core depose une commande dans le volume partage
|
|
||||||
// 4. Sidecar `switcher` la traite (sed .env, docker compose up -d)
|
|
||||||
// 5. UI poll GET /api/license/channel pour suivre le status
|
|
||||||
|
|
||||||
/** Etat courant : canal actuel + dispo du sidecar + dernier resultat. */
|
|
||||||
// S125 : faux positif — le flux numerote ci-dessus est de la prose explicative, pas du code mort.
|
|
||||||
@SuppressWarnings("java:S125")
|
|
||||||
@GetMapping("/channel")
|
|
||||||
public ChannelStatusDTO getChannel() {
|
|
||||||
return ChannelStatusDTO.from(channelSwitcher);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Declenche un switch de canal. Renvoie l'ID de la commande pour le polling. */
|
|
||||||
@PostMapping("/channel/switch")
|
|
||||||
public ResponseEntity<Object> switchChannel(@RequestBody ChannelSwitchRequest request) {
|
|
||||||
if (request == null || request.channel() == null) {
|
|
||||||
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing channel"));
|
|
||||||
}
|
|
||||||
|
|
||||||
ChannelSwitcherService.Channel target;
|
|
||||||
try {
|
|
||||||
target = ChannelSwitcherService.Channel.valueOf(request.channel().toUpperCase(Locale.ROOT));
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return ResponseEntity.badRequest().body(Map.of(
|
|
||||||
ERROR_KEY, "invalid channel (allowed: stable, beta)"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Garde : pas de switch vers beta sans licence Patreon valide.
|
|
||||||
// Le switcher ferait le boulot quoi qu'il arrive (il valide juste le
|
|
||||||
// format), donc c'est ici qu'on doit refuser cote metier.
|
|
||||||
// VALID + GRACE autorisent l'acces beta (cf. javadoc de LicenseStatus).
|
|
||||||
if (target == ChannelSwitcherService.Channel.BETA) {
|
|
||||||
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
|
|
||||||
com.loremind.domain.licensing.LicenseStatus s = (snap != null) ? snap.status() : null;
|
|
||||||
boolean allowed = s == com.loremind.domain.licensing.LicenseStatus.VALID
|
|
||||||
|| s == com.loremind.domain.licensing.LicenseStatus.GRACE;
|
|
||||||
if (!allowed) {
|
|
||||||
return ResponseEntity.status(403).body(Map.of(
|
|
||||||
ERROR_KEY, "Aucune licence Patreon active — impossible de basculer sur le canal beta."));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!channelSwitcher.isSwitcherAvailable()) {
|
|
||||||
return ResponseEntity.status(503).body(Map.of(
|
|
||||||
ERROR_KEY, "Sidecar switcher non disponible (mise a jour requise du docker-compose.yml)."));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
String id = channelSwitcher.requestSwitch(target);
|
|
||||||
return ResponseEntity.accepted().body(Map.of(
|
|
||||||
"id", id,
|
|
||||||
"channel", target.name().toLowerCase(Locale.ROOT)));
|
|
||||||
} catch (IOException e) {
|
|
||||||
return ResponseEntity.status(500).body(Map.of(
|
|
||||||
ERROR_KEY, "Impossible d'ecrire la commande de switch: " + e.getMessage()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public record InstallRequest(String jwt) {}
|
|
||||||
public record BetaChannelRequest(boolean enabled) {}
|
|
||||||
public record ChannelSwitchRequest(String channel) {}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.web.controller;
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.channel.ChannelSwitcherService;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService;
|
import com.loremind.infrastructure.updates.UpdateCheckService;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService.BetaStatus;
|
import com.loremind.infrastructure.updates.UpdateCheckService.BetaStatus;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus;
|
import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus;
|
||||||
@@ -10,10 +11,14 @@ import org.springframework.http.HttpStatus;
|
|||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
import com.loremind.infrastructure.web.dto.updates.ChannelStatusDTO;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,12 +35,18 @@ public class UpdatesController {
|
|||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(UpdatesController.class);
|
private static final Logger log = LoggerFactory.getLogger(UpdatesController.class);
|
||||||
|
|
||||||
|
/** Clé du message d'erreur dans le body JSON — contrat lu par le frontend. */
|
||||||
|
private static final String ERROR_KEY = "error";
|
||||||
|
|
||||||
private final UpdateCheckService updates;
|
private final UpdateCheckService updates;
|
||||||
|
private final ChannelSwitcherService channels;
|
||||||
private final boolean demoMode;
|
private final boolean demoMode;
|
||||||
|
|
||||||
public UpdatesController(UpdateCheckService updates,
|
public UpdatesController(UpdateCheckService updates,
|
||||||
|
ChannelSwitcherService channels,
|
||||||
@Value("${app.demo-mode:false}") boolean demoMode) {
|
@Value("${app.demo-mode:false}") boolean demoMode) {
|
||||||
this.updates = updates;
|
this.updates = updates;
|
||||||
|
this.channels = channels;
|
||||||
this.demoMode = demoMode;
|
this.demoMode = demoMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,6 +81,50 @@ public class UpdatesController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Bascule de canal stable <-> beta via le sidecar `switcher` ----------
|
||||||
|
//
|
||||||
|
// Le canal beta est libre : toute instance Docker peut y passer et en revenir.
|
||||||
|
// L'UI depose une commande (POST /channel/switch), le sidecar l'applique
|
||||||
|
// (IMAGE_NAMESPACE du .env + docker compose pull/up), l'UI suit le resultat
|
||||||
|
// via GET /channel.
|
||||||
|
|
||||||
|
/** Etat courant : canal actuel + dispo du sidecar + dernier resultat. */
|
||||||
|
@GetMapping("/channel")
|
||||||
|
public ChannelStatusDTO channel() {
|
||||||
|
guardDemoMode();
|
||||||
|
return ChannelStatusDTO.from(channels);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Declenche un switch de canal. Renvoie l'ID de la commande pour le polling. */
|
||||||
|
@PostMapping("/channel/switch")
|
||||||
|
public ResponseEntity<Object> switchChannel(@RequestBody ChannelSwitchRequest request) {
|
||||||
|
guardDemoMode();
|
||||||
|
if (request == null || request.channel() == null) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "missing channel"));
|
||||||
|
}
|
||||||
|
ChannelSwitcherService.Channel target;
|
||||||
|
try {
|
||||||
|
target = ChannelSwitcherService.Channel.valueOf(request.channel().toUpperCase(Locale.ROOT));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of(ERROR_KEY, "invalid channel (allowed: stable, beta)"));
|
||||||
|
}
|
||||||
|
if (!channels.isSwitcherAvailable()) {
|
||||||
|
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(Map.of(
|
||||||
|
ERROR_KEY, "Sidecar switcher non disponible (mise a jour requise du docker-compose.yml)."));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
String id = channels.requestSwitch(target);
|
||||||
|
return ResponseEntity.accepted().body(Map.of(
|
||||||
|
"id", id,
|
||||||
|
"channel", target.name().toLowerCase(Locale.ROOT)));
|
||||||
|
} catch (IOException e) {
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of(
|
||||||
|
ERROR_KEY, "Impossible d'ecrire la commande de switch: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record ChannelSwitchRequest(String channel) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* En mode demo, les instances ne doivent pas se mettre a jour ni meme
|
* En mode demo, les instances ne doivent pas se mettre a jour ni meme
|
||||||
* exposer leur statut (pas de surface d'attaque, et pas de redemarrage
|
* exposer leur statut (pas de surface d'attaque, et pas de redemarrage
|
||||||
|
|||||||
+2
@@ -17,6 +17,8 @@ public class GameSystemDTO {
|
|||||||
private String name;
|
private String name;
|
||||||
private String description;
|
private String description;
|
||||||
private String rulesMarkdown;
|
private String rulesMarkdown;
|
||||||
|
/** Version anglaise des règles (rulesMarkdown = version française). */
|
||||||
|
private String rulesMarkdownEn;
|
||||||
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
||||||
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
||||||
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
|
||||||
|
|||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
package com.loremind.infrastructure.web.dto.licensing;
|
|
||||||
|
|
||||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Vue serialisee de l'etat de la licence pour le frontend.
|
|
||||||
* Le {@code rawJwt} n'est volontairement JAMAIS expose.
|
|
||||||
*/
|
|
||||||
public record LicenseStatusDTO(
|
|
||||||
boolean enabled,
|
|
||||||
String status,
|
|
||||||
String patreonUserId,
|
|
||||||
String tierId,
|
|
||||||
String instanceId,
|
|
||||||
Instant expiresAt,
|
|
||||||
Instant lastRefreshAttemptAt,
|
|
||||||
Boolean lastRefreshSucceeded,
|
|
||||||
boolean betaChannelEnabled
|
|
||||||
) {
|
|
||||||
public static LicenseStatusDTO from(boolean enabled, LicenseSnapshot snap) {
|
|
||||||
return new LicenseStatusDTO(
|
|
||||||
enabled,
|
|
||||||
snap.status().name(),
|
|
||||||
snap.patreonUserId(),
|
|
||||||
snap.tierId(),
|
|
||||||
snap.instanceId(),
|
|
||||||
snap.expiresAt(),
|
|
||||||
snap.lastRefreshAttemptAt(),
|
|
||||||
snap.lastRefreshAttemptAt() != null ? snap.lastRefreshSucceeded() : null,
|
|
||||||
snap.betaChannelEnabled()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
package com.loremind.infrastructure.web.dto.licensing;
|
package com.loremind.infrastructure.web.dto.updates;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
import com.loremind.application.licensing.ChannelSwitcherService;
|
import com.loremind.application.channel.ChannelSwitcherService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Etat du canal courant + dernier resultat de switch.
|
* Etat du canal courant + dernier resultat de switch.
|
||||||
@@ -20,6 +20,7 @@ public class GameSystemMapper {
|
|||||||
dto.setName(g.getName());
|
dto.setName(g.getName());
|
||||||
dto.setDescription(g.getDescription());
|
dto.setDescription(g.getDescription());
|
||||||
dto.setRulesMarkdown(g.getRulesMarkdown());
|
dto.setRulesMarkdown(g.getRulesMarkdown());
|
||||||
|
dto.setRulesMarkdownEn(g.getRulesMarkdownEn());
|
||||||
dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate()));
|
dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate()));
|
||||||
dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate()));
|
dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate()));
|
||||||
dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate()));
|
dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate()));
|
||||||
@@ -36,6 +37,7 @@ public class GameSystemMapper {
|
|||||||
.name(dto.getName())
|
.name(dto.getName())
|
||||||
.description(dto.getDescription())
|
.description(dto.getDescription())
|
||||||
.rulesMarkdown(dto.getRulesMarkdown())
|
.rulesMarkdown(dto.getRulesMarkdown())
|
||||||
|
.rulesMarkdownEn(dto.getRulesMarkdownEn())
|
||||||
.characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate()))
|
.characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate()))
|
||||||
.npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate()))
|
.npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate()))
|
||||||
.enemyTemplate(fieldMapper.toDomainList(dto.getEnemyTemplate()))
|
.enemyTemplate(fieldMapper.toDomainList(dto.getEnemyTemplate()))
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
# vivent sous loremind.home (defaut : ~/.loremind).
|
# vivent sous loremind.home (defaut : ~/.loremind).
|
||||||
#
|
#
|
||||||
# Surcharge UNIQUEMENT ce qui differe du profil par defaut (application.properties) :
|
# Surcharge UNIQUEMENT ce qui differe du profil par defaut (application.properties) :
|
||||||
# le reste (timeouts, multipart, licensing...) est herite tel quel.
|
# le reste (timeouts, multipart...) est herite tel quel.
|
||||||
|
|
||||||
# --- Config utilisateur editable (port + identifiants admin) ----------------
|
# --- Config utilisateur editable (port + identifiants admin) ----------------
|
||||||
# Charge ~/.loremind/loremind.properties s'il existe (cree au 1er lancement par
|
# Charge ~/.loremind/loremind.properties s'il existe (cree au 1er lancement par
|
||||||
@@ -105,14 +105,6 @@ loremind.upload.max-file-size=2GB
|
|||||||
loremind.upload.max-request-size=2GB
|
loremind.upload.max-request-size=2GB
|
||||||
server.tomcat.max-swallow-size=-1
|
server.tomcat.max-swallow-size=-1
|
||||||
|
|
||||||
# --- Licensing / Patreon : desactive en mode bureau ------------------------
|
|
||||||
# Le gating par IMAGE Docker (canal beta tire d'un registry prive) n'a aucun
|
|
||||||
# sens hors Docker. On coupe toute la machinerie : daemon de refresh no-op,
|
|
||||||
# /api/license/* renvoie enabled=false, et l'UI masque la section Patreon.
|
|
||||||
# La distribution beta desktop se fait par installeur beta via Patreon, pas
|
|
||||||
# par une connexion in-app.
|
|
||||||
licensing.enabled=false
|
|
||||||
|
|
||||||
# --- Verification des mises a jour (bureau) --------------------------------
|
# --- Verification des mises a jour (bureau) --------------------------------
|
||||||
# Interroge l'API GitHub Releases (derniere release STABLE) au demarrage ; si
|
# Interroge l'API GitHub Releases (derniere release STABLE) au demarrage ; si
|
||||||
# une version plus recente existe, l'icone systray le signale (bulle + item
|
# une version plus recente existe, l'icone systray le signale (bulle + item
|
||||||
|
|||||||
@@ -104,36 +104,7 @@ update-check.images=${UPDATE_CHECK_IMAGES:}
|
|||||||
update-check.watchtower-url=${WATCHTOWER_URL:http://watchtower:8080}
|
update-check.watchtower-url=${WATCHTOWER_URL:http://watchtower:8080}
|
||||||
update-check.watchtower-token=${WATCHTOWER_TOKEN:}
|
update-check.watchtower-token=${WATCHTOWER_TOKEN:}
|
||||||
|
|
||||||
# ============================================================================
|
# Canal beta (libre) : images publiques verifiees quand l'instance tourne en beta.
|
||||||
# Licensing (canal beta gate par Patreon)
|
# LICENSING_BETA_IMAGES reste lu pour les .env d'avant la suppression de Patreon.
|
||||||
# ============================================================================
|
update-check.beta-registry=${UPDATE_CHECK_BETA_REGISTRY:ghcr.io}
|
||||||
# URL du relais OAuth Patreon (Cloudflare Workers). En prod : valeur par defaut.
|
update-check.beta-images=${UPDATE_CHECK_BETA_IMAGES:${LICENSING_BETA_IMAGES:igmlcreation/loremind-beta-core,igmlcreation/loremind-beta-brain,igmlcreation/loremind-beta-web}}
|
||||||
licensing.relay.base-url=${LICENSING_RELAY_BASE_URL:https://loremind-auth.igmlcreation.fr}
|
|
||||||
|
|
||||||
# Cle publique Ed25519 (PEM SPKI) qui verifie les JWT emis par le relais.
|
|
||||||
# En prod : chargee automatiquement depuis classpath:licensing/jwt-public-key.pem
|
|
||||||
# (embarquee dans le binaire). Cette propriete sert UNIQUEMENT a la rotation
|
|
||||||
# de cle ou aux tests : si LICENSING_JWT_PUBLIC_KEY est defini, il prevaut
|
|
||||||
# sur le fichier embarque.
|
|
||||||
licensing.jwt.public-key=${LICENSING_JWT_PUBLIC_KEY:}
|
|
||||||
licensing.jwt.expected-issuer=loremind-auth
|
|
||||||
licensing.jwt.expected-audience=loremind-instance
|
|
||||||
|
|
||||||
# Periode de tolerance apres expiration du JWT pendant laquelle l'instance
|
|
||||||
# garde l'acces beta meme si le relais est indisponible pour le refresh.
|
|
||||||
licensing.grace-period-days=14
|
|
||||||
# Avant J-N de l'expiration, le daemon tente un refresh.
|
|
||||||
licensing.refresh-before-expiry-days=2
|
|
||||||
|
|
||||||
# Identifiant stable de l'instance (UUID genere a la premiere connexion Patreon
|
|
||||||
# et conserve en base). Utilise dans le state OAuth + dans le JWT.
|
|
||||||
licensing.instance-id-file=${LICENSING_INSTANCE_ID_FILE:}
|
|
||||||
|
|
||||||
# Image beta : si la licence est valide ET le toggle canal beta active,
|
|
||||||
# UpdateCheckService check ces images en plus du canal stable.
|
|
||||||
licensing.beta.images=${LICENSING_BETA_IMAGES:igmlcreation/loremind-beta-core,igmlcreation/loremind-beta-brain,igmlcreation/loremind-beta-web}
|
|
||||||
|
|
||||||
# Chemin de sortie pour le docker config.json partage avec Watchtower.
|
|
||||||
# Volume Docker `docker-config` monte sur ce chemin dans Core, et sur
|
|
||||||
# `/shared/docker` dans Watchtower (DOCKER_CONFIG=/shared/docker).
|
|
||||||
licensing.docker-config-path=${LICENSING_DOCKER_CONFIG_PATH:/shared/docker/config.json}
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- Règles d'un système de jeu en deux langues : rules_markdown = version française,
|
||||||
|
-- rules_markdown_en = version anglaise (remplie à l'import d'un PDF par traduction).
|
||||||
|
ALTER TABLE game_systems ADD COLUMN rules_markdown_en TEXT;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- Le canal beta est libre : plus de licence Patreon, la table des licences ne sert plus.
|
||||||
|
DROP TABLE IF EXISTS licenses;
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
# Cle publique JWT du relais OAuth Patreon
|
|
||||||
|
|
||||||
Le fichier `jwt-public-key.pem` contient la **cle publique Ed25519** qui sert
|
|
||||||
a verifier la signature des JWT licence emis par le relais
|
|
||||||
(`loremind-auth.igmlcreation.fr`).
|
|
||||||
|
|
||||||
## Pourquoi ici ?
|
|
||||||
|
|
||||||
- C'est une **cle publique** : par nature non-secrete, elle peut etre committee
|
|
||||||
dans le repo public et embarquee dans le binaire distribue.
|
|
||||||
- Cela evite a chaque utilisateur final de devoir renseigner manuellement la
|
|
||||||
cle dans son `.env` au moment de l'installation.
|
|
||||||
- L'env `LICENSING_JWT_PUBLIC_KEY` peut surcharger cette valeur (utile pour
|
|
||||||
la rotation de cle sans rebuild ou pour les tests).
|
|
||||||
|
|
||||||
## Si le fichier est absent
|
|
||||||
|
|
||||||
La feature licensing est **desactivee silencieusement** : `LicenseService.isLicensingEnabled()`
|
|
||||||
renvoie `false`, et l'UI masque toute la section Patreon.
|
|
||||||
|
|
||||||
## Rotation de cle
|
|
||||||
|
|
||||||
1. Generer une nouvelle paire dans le relais : `npm run keys:generate`
|
|
||||||
2. Pousser la nouvelle cle privee : `wrangler secret put JWT_PRIVATE_KEY`
|
|
||||||
3. Remplacer `jwt-public-key.pem` ici avec la nouvelle cle publique
|
|
||||||
4. Rebuild + redeployer LoreMind (les anciens JWT seront refuses au prochain
|
|
||||||
refresh, l'utilisateur sera invite a reconnecter Patreon)
|
|
||||||
5. Optionnel : pendant la transition, supporter les deux cles en parallele
|
|
||||||
(pas implemente en MVP, peut etre ajoute si besoin operationnel)
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
-----BEGIN PUBLIC KEY-----
|
|
||||||
MCowBQYDK2VwAyEArbfaqBq54HJR1pKqliTShKrNIab32gpBwSTDw90I4wg=
|
|
||||||
-----END PUBLIC KEY-----
|
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
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.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/** IA des méthodes guidées : questions validées, contexte de campagne transmis, réponses filtrées. */
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class GuidedAssistServiceTest {
|
||||||
|
|
||||||
|
@Mock private GuidedMethodAssistant assistant;
|
||||||
|
@Mock private CampaignContextFormatter contextFormatter;
|
||||||
|
@InjectMocks private GuidedAssistService service;
|
||||||
|
|
||||||
|
private static final Question TITLE = new Question("title", "Nom de l'enquête", "Ex. : L'héritage", "Le mystère", List.of());
|
||||||
|
private static final Question NATURE = new Question("node1.nature", "Genre de scène", null, "Première piste",
|
||||||
|
List.of(new Choice("location", "Un lieu"), new Choice("npc", "Une personne")));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_sendsCampaignContextAndExistingAnswers_andFiltersTheResult() {
|
||||||
|
when(contextFormatter.format("c1")).thenReturn("Campagne : Valfroide");
|
||||||
|
when(assistant.answer(eq("Enquête en nœuds"), any(), eq("Une tour se rallume"), eq("Campagne : Valfroide"),
|
||||||
|
anyList(), anyMap())).thenReturn(Map.of(
|
||||||
|
"title", " L'héritage empoisonné ",
|
||||||
|
"node1.nature", "dragon", // choix invalide -> écarté
|
||||||
|
"invented", "clé inventée", // clé non demandée -> écartée
|
||||||
|
"node1.name", ""));
|
||||||
|
|
||||||
|
Map<String, String> out = service.suggest("c1", "Enquête en nœuds", "Trois pistes",
|
||||||
|
"Une tour se rallume", List.of(TITLE, NATURE), Map.of("truth", " Le notaire ", "blank", " "));
|
||||||
|
|
||||||
|
assertEquals(Map.of("title", "L'héritage empoisonné"), out);
|
||||||
|
verify(assistant).answer(any(), any(), any(), any(), eq(List.of(TITLE, NATURE)), eq(Map.of("truth", "Le notaire")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_keepsAValidChoice() {
|
||||||
|
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap())).thenReturn(Map.of("node1.nature", "npc"));
|
||||||
|
assertEquals(Map.of("node1.nature", "npc"), service.suggest("c1", "M", "", "", List.of(NATURE), null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_withoutAnyValidQuestion_isRejected() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée", List.of(), Map.of()));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée",
|
||||||
|
java.util.Arrays.asList(null, new Question(" ", "x", null, null, null)), Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -23,6 +23,9 @@ class GameSystemContextBuilderTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private GameSystemRepository gameSystemRepository;
|
private GameSystemRepository gameSystemRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private com.loremind.domain.shared.ports.CurrentLanguage currentLanguage;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private GameSystemContextBuilder builder;
|
private GameSystemContextBuilder builder;
|
||||||
|
|
||||||
@@ -71,4 +74,24 @@ class GameSystemContextBuilderTest {
|
|||||||
|
|
||||||
assertEquals("Règles de combat.", sections.get("Combat"));
|
assertEquals("Règles de combat.", sections.get("Combat"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void build_usesTheRulesOfTheInterfaceLanguage_withFallback() {
|
||||||
|
com.loremind.domain.gamesystemcontext.GameSystem gs = com.loremind.domain.gamesystemcontext.GameSystem.builder()
|
||||||
|
.id("gs").name("Nimble").rulesMarkdown("## Combat\nJet de d20").rulesMarkdownEn("## Fighting\nRoll a d20").build();
|
||||||
|
org.mockito.Mockito.when(gameSystemRepository.findById("gs")).thenReturn(java.util.Optional.of(gs));
|
||||||
|
|
||||||
|
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
|
||||||
|
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
|
||||||
|
.orElseThrow().toString().contains("Roll a d20"));
|
||||||
|
|
||||||
|
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("fr");
|
||||||
|
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
|
||||||
|
.orElseThrow().toString().contains("Jet de d20"));
|
||||||
|
|
||||||
|
gs.setRulesMarkdownEn(null); // pas de version anglaise : repli sur le français
|
||||||
|
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
|
||||||
|
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
|
||||||
|
.orElseThrow().toString().contains("Jet de d20"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -347,4 +347,65 @@ class BrainRulesImportClientTest {
|
|||||||
assertTrue(c.done.get().sections().isEmpty());
|
assertTrue(c.done.get().sections().isEmpty());
|
||||||
assertNull(c.error.get());
|
assertNull(c.error.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_done_carriesBothLanguages() {
|
||||||
|
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"d20\"},\"page_count\":2,\"ocr_page_count\":0,"
|
||||||
|
+ "\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\"d20\"},"
|
||||||
|
+ "\"en\":{\"Fighting\":\"d20 roll\"}}}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
ExchangeFunction ef = req -> Mono.just(
|
||||||
|
ClientResponse.create(HttpStatus.OK)
|
||||||
|
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
.body(sse)
|
||||||
|
.build());
|
||||||
|
client(ef).importRulesStreaming(
|
||||||
|
new byte[]{1}, "r.pdf",
|
||||||
|
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
|
||||||
|
c.done::set, c.error::set);
|
||||||
|
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertEquals("fr", c.done.get().sourceLanguage());
|
||||||
|
assertEquals(java.util.Map.of("Fighting", "d20 roll"), c.done.get().sectionsByLanguage().get("en"));
|
||||||
|
assertEquals(java.util.Map.of("Combat", "d20"), c.done.get().sectionsByLanguage().get("fr"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Livre entier en deux langues : l'évènement {@code done} dépasse largement les 256 Ko
|
||||||
|
* par défaut de WebClient. Vrai serveur HTTP local (une ExchangeFunction simulée ne
|
||||||
|
* passe pas par les codecs du client, donc ne verrait pas la limite).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void streaming_acceptsAVeryLargeDoneEvent() throws Exception {
|
||||||
|
String big = "x".repeat(600_000);
|
||||||
|
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"" + big + "\"},\"page_count\":300,"
|
||||||
|
+ "\"ocr_page_count\":0,\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\""
|
||||||
|
+ big + "\"},\"en\":{\"Fighting\":\"" + big + "\"}}}\n\n";
|
||||||
|
byte[] payload = sse.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||||
|
com.sun.net.httpserver.HttpServer server =
|
||||||
|
com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
server.createContext("/import/rules/stream", exchange -> {
|
||||||
|
exchange.getRequestBody().readAllBytes();
|
||||||
|
exchange.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE);
|
||||||
|
exchange.sendResponseHeaders(200, payload.length);
|
||||||
|
try (var out = exchange.getResponseBody()) {
|
||||||
|
out.write(payload);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
try {
|
||||||
|
String url = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||||
|
BrainRulesImportClient real = new BrainRulesImportClient(restTemplate, WebClient.builder(), objectMapper,
|
||||||
|
url, 30, "/import/rules", "/import/rules/stream");
|
||||||
|
Collector c = new Collector();
|
||||||
|
real.importRulesStreaming(new byte[]{1}, "r.pdf",
|
||||||
|
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add, c.done::set, c.error::set);
|
||||||
|
|
||||||
|
assertNull(c.error.get());
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertEquals(600_000, c.done.get().sectionsByLanguage().get("en").get("Fighting").length());
|
||||||
|
} finally {
|
||||||
|
server.stop(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.info.BuildProperties;
|
||||||
|
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mises a jour du bureau : la version stable suit {@code /releases/latest} ; une version
|
||||||
|
* beta (canal libre, publie en prerelease GitHub) suit la liste complete des releases.
|
||||||
|
*/
|
||||||
|
class DesktopUpdateServiceTest {
|
||||||
|
|
||||||
|
private static final String LATEST = "https://api.github.com/repos/IGMLcreation/LoreMind/releases/latest";
|
||||||
|
private static final String ALL = "https://api.github.com/repos/IGMLcreation/LoreMind/releases?per_page=30";
|
||||||
|
private static final ObjectMapper JSON = new ObjectMapper();
|
||||||
|
|
||||||
|
private static DesktopUpdateService service(String currentVersion, RestTemplate http) {
|
||||||
|
Properties p = new Properties();
|
||||||
|
p.setProperty("version", currentVersion);
|
||||||
|
DesktopUpdateService svc = new DesktopUpdateService(new RestTemplateBuilder(), true, LATEST, new BuildProperties(p));
|
||||||
|
ReflectionTestUtils.setField(svc, "http", http);
|
||||||
|
return svc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void reply(RestTemplate http, String url, String json) throws Exception {
|
||||||
|
JsonNode body = JSON.readTree(json);
|
||||||
|
when(http.exchange(eq(url), eq(HttpMethod.GET), any(), eq(JsonNode.class)))
|
||||||
|
.thenReturn(ResponseEntity.ok(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void stableVersion_followsTheLatestStableRelease() throws Exception {
|
||||||
|
RestTemplate http = mock(RestTemplate.class);
|
||||||
|
reply(http, LATEST, "{\"tag_name\":\"v1.6.0\",\"html_url\":\"https://x/1.6.0\"}");
|
||||||
|
|
||||||
|
Optional<DesktopUpdateService.UpdateInfo> info = service("1.5.0", http).checkForUpdate();
|
||||||
|
|
||||||
|
assertTrue(info.isPresent());
|
||||||
|
assertEquals("1.6.0", info.get().latestVersion());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void betaVersion_isToldAboutTheNextBeta() throws Exception {
|
||||||
|
RestTemplate http = mock(RestTemplate.class);
|
||||||
|
reply(http, ALL, "[{\"tag_name\":\"v1.5.0-beta.2\",\"prerelease\":true,\"html_url\":\"https://x/b2\"},"
|
||||||
|
+ "{\"tag_name\":\"v1.6.0-beta\",\"draft\":true},"
|
||||||
|
+ "{\"tag_name\":\"v1.4.0\",\"html_url\":\"https://x/1.4.0\"}]");
|
||||||
|
|
||||||
|
Optional<DesktopUpdateService.UpdateInfo> info = service("1.5.0-beta", http).checkForUpdate();
|
||||||
|
|
||||||
|
assertTrue(info.isPresent(), "beta.2 > beta ; le brouillon 1.6.0-beta est ignore");
|
||||||
|
assertEquals("1.5.0-beta.2", info.get().latestVersion());
|
||||||
|
assertEquals("https://x/b2", info.get().releaseUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void betaVersion_isToldWhenTheStableReleaseReplacesIt() throws Exception {
|
||||||
|
RestTemplate http = mock(RestTemplate.class);
|
||||||
|
reply(http, ALL, "[{\"tag_name\":\"v1.5.0\",\"html_url\":\"https://x/1.5.0\"},"
|
||||||
|
+ "{\"tag_name\":\"v1.5.0-beta\",\"prerelease\":true}]");
|
||||||
|
|
||||||
|
Optional<DesktopUpdateService.UpdateInfo> info = service("1.5.0-beta", http).checkForUpdate();
|
||||||
|
|
||||||
|
assertTrue(info.isPresent());
|
||||||
|
assertEquals("1.5.0", info.get().latestVersion());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void betaVersion_upToDate() throws Exception {
|
||||||
|
RestTemplate http = mock(RestTemplate.class);
|
||||||
|
reply(http, ALL, "[{\"tag_name\":\"v1.5.0-beta\",\"prerelease\":true},{\"tag_name\":\"v1.4.0\"}]");
|
||||||
|
|
||||||
|
assertFalse(service("1.5.0-beta", http).checkForUpdate().isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void compareVersions_ordersStableAfterBetaAndBetasByNumber() {
|
||||||
|
assertTrue(DesktopUpdateService.compareVersions("1.5.0-beta", "1.5.0") < 0);
|
||||||
|
assertTrue(DesktopUpdateService.compareVersions("1.5.0-beta", "1.5.0-beta.2") < 0);
|
||||||
|
assertTrue(DesktopUpdateService.compareVersions("1.5.0-beta.2", "1.5.0-beta.10") < 0);
|
||||||
|
assertTrue(DesktopUpdateService.compareVersions("1.6.0-beta", "1.5.0") > 0);
|
||||||
|
assertEquals(0, DesktopUpdateService.compareVersions("1.5.0", "1.5.0"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+32
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.condition.OS;
|
|||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
@@ -70,6 +71,37 @@ class WindowsHostNetworkAccessTest {
|
|||||||
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("SecurityCenter2"));
|
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("SecurityCenter2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void command_passesTheScriptInClear_withoutAntivirusRedFlags() {
|
||||||
|
String script = WindowsHostNetworkAccess.inspectScript("C:\\Users\\Jérôme\\DM Loremind.exe");
|
||||||
|
List<String> cmd = WindowsHostNetworkAccess.command(script);
|
||||||
|
|
||||||
|
assertEquals(List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script), cmd);
|
||||||
|
assertFalse(String.join(" ", cmd).contains("EncodedCommand"), "script lisible, pas encodé");
|
||||||
|
assertFalse(String.join(" ", cmd).contains("Bypass"), "la politique d'exécution ne concerne que les .ps1");
|
||||||
|
assertTrue(script.contains("'C:\\Users\\Jérôme\\DM Loremind.exe'"), "accents gardés tels quels (ligne de commande UTF-16)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void command_refusesMultilineOrDoubleQuotedScripts() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> WindowsHostNetworkAccess.command("a\nb"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> WindowsHostNetworkAccess.command("Write-Host \"x\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void elevation_runsTheAllowScriptAsAdmin_inOneLine() {
|
||||||
|
String path = "C:\\Users\\l'MJ\\DM Loremind.exe";
|
||||||
|
String elevation = WindowsHostNetworkAccess.elevationScript(path);
|
||||||
|
|
||||||
|
WindowsHostNetworkAccess.command(elevation); // une ligne, sans guillemet double
|
||||||
|
assertTrue(elevation.contains("-Verb RunAs"));
|
||||||
|
assertFalse(elevation.contains("Bypass"));
|
||||||
|
assertTrue(elevation.contains("catch { exit 1223 }"), "refus de l'UAC = annulation");
|
||||||
|
String encoded = elevation.replaceAll(".*'-EncodedCommand','([^']+)'.*", "$1");
|
||||||
|
assertEquals(WindowsHostNetworkAccess.allowScript(path),
|
||||||
|
new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_16LE));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void encode_isUtf16LeBase64_asExpectedByEncodedCommand() {
|
void encode_isUtf16LeBase64_asExpectedByEncodedCommand() {
|
||||||
String encoded = WindowsHostNetworkAccess.encode("é");
|
String encoded = WindowsHostNetworkAccess.encode("é");
|
||||||
|
|||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.*;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.*;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mode plat du livret : un seul arc d'un seul chapitre n'est présenté « à plat » que si
|
||||||
|
* ces deux conteneurs sont vides. Un chapitre écrit (méthode guidée…) garde ses en-têtes.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@Transactional
|
||||||
|
class PdfExportFlatModeTest {
|
||||||
|
|
||||||
|
@Autowired private PdfExportService service;
|
||||||
|
@Autowired private CampaignJpaRepository campaignRepo;
|
||||||
|
@Autowired private ArcJpaRepository arcRepo;
|
||||||
|
@Autowired private ChapterJpaRepository chapterRepo;
|
||||||
|
@Autowired private SceneJpaRepository sceneRepo;
|
||||||
|
|
||||||
|
private String campaign(String chapterGmNotes) {
|
||||||
|
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder().name("C").arcsCount(1).build());
|
||||||
|
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Arc principal").campaignId(camp.getId()).order(0).build());
|
||||||
|
ChapterJpaEntity ch = chapterRepo.save(ChapterJpaEntity.builder().name("L'héritage empoisonné")
|
||||||
|
.arcId(arc.getId()).order(0).gmNotes(chapterGmNotes).build());
|
||||||
|
sceneRepo.save(SceneJpaEntity.builder().name("L'arrestation").chapterId(ch.getId()).order(0).build());
|
||||||
|
return String.valueOf(camp.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bareArcAndChapter_areFlattened() {
|
||||||
|
String x = service.xhtml(campaign(null), PdfExportOptions.defaults());
|
||||||
|
assertTrue(x.contains("id=\"part-narrative\">Scènes</h1>"));
|
||||||
|
assertFalse(x.contains("L'héritage empoisonné</div>"), "en-tête de chapitre masqué");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void writtenChapter_keepsItsHeaders() {
|
||||||
|
String x = service.xhtml(campaign("Le notaire est coupable."), PdfExportOptions.defaults());
|
||||||
|
assertTrue(x.contains("id=\"part-narrative\">Structure narrative</h1>"));
|
||||||
|
assertTrue(x.contains("L'héritage empoisonné"), "le chapitre de la méthode guidée reste visible");
|
||||||
|
assertTrue(x.contains("Le notaire est coupable."));
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
package com.loremind.infrastructure.updates;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class LegacyRegistryCredentialsCleanupTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void removesTheOldGhcrCredentials(@TempDir Path dir) throws Exception {
|
||||||
|
Path config = dir.resolve("config.json");
|
||||||
|
Files.writeString(config, "{\"auths\":{\"ghcr.io\":{\"auth\":\"dXNlcjpwYXQ=\"}}}");
|
||||||
|
|
||||||
|
assertTrue(new LegacyRegistryCredentialsCleanup(config.toString()).cleanup());
|
||||||
|
assertFalse(Files.exists(config));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void doesNothingOnRecentInstalls(@TempDir Path dir) {
|
||||||
|
assertFalse(new LegacyRegistryCredentialsCleanup("").cleanup());
|
||||||
|
assertFalse(new LegacyRegistryCredentialsCleanup(dir.resolve("config.json").toString()).cleanup());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.updates;
|
package com.loremind.infrastructure.updates;
|
||||||
|
|
||||||
|
import com.loremind.application.channel.ChannelSwitcherService;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatus;
|
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatus;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatusKind;
|
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatusKind;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService.TagsListResponse;
|
import com.loremind.infrastructure.updates.UpdateCheckService.TagsListResponse;
|
||||||
@@ -7,6 +8,9 @@ import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus;
|
|||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.boot.info.BuildProperties;
|
import org.springframework.boot.info.BuildProperties;
|
||||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -41,20 +45,64 @@ class UpdateCheckServiceTest {
|
|||||||
p.setProperty("version", currentVersion);
|
p.setProperty("version", currentVersion);
|
||||||
bp = new BuildProperties(p);
|
bp = new BuildProperties(p);
|
||||||
}
|
}
|
||||||
// licenseService null : la beta est testee separement, ces tests
|
return newService(token, bp, ChannelSwitcherService.Channel.STABLE);
|
||||||
// couvrent uniquement le canal stable.
|
}
|
||||||
|
|
||||||
|
private static UpdateCheckService newService(String token, BuildProperties bp,
|
||||||
|
ChannelSwitcherService.Channel channel) {
|
||||||
|
ChannelSwitcherService channels = mock(ChannelSwitcherService.class);
|
||||||
|
when(channels.getCurrentChannel()).thenReturn(channel);
|
||||||
return new UpdateCheckService(
|
return new UpdateCheckService(
|
||||||
new RestTemplateBuilder(),
|
new RestTemplateBuilder(),
|
||||||
"ghcr.io",
|
"ghcr.io",
|
||||||
"igmlcreation/loremind-core,igmlcreation/loremind-brain",
|
"igmlcreation/loremind-core,igmlcreation/loremind-brain",
|
||||||
"http://watchtower:8080",
|
"http://watchtower:8080",
|
||||||
token,
|
token,
|
||||||
"",
|
"ghcr.io",
|
||||||
null,
|
"igmlcreation/loremind-beta-core",
|
||||||
|
channels,
|
||||||
bp
|
bp
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static BuildProperties version(String v) {
|
||||||
|
Properties p = new Properties();
|
||||||
|
p.setProperty("version", v);
|
||||||
|
return new BuildProperties(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Canal beta (libre : images publiques, lecture anonyme) ------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkBeta_disabledWhenNotOnBetaChannel() {
|
||||||
|
UpdateCheckService svc = newService("tok", version("1.4.0"), ChannelSwitcherService.Channel.STABLE);
|
||||||
|
RestTemplate http = stubHttp(svc);
|
||||||
|
|
||||||
|
UpdateCheckService.BetaStatus status = svc.checkBeta();
|
||||||
|
|
||||||
|
assertFalse(status.enabled());
|
||||||
|
assertEquals("not-on-beta-channel", status.disabledReason());
|
||||||
|
verifyNoInteractions(http);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkBeta_readsPublicBetaImagesWithoutCredentials() {
|
||||||
|
UpdateCheckService svc = newService("tok", version("1.5.0-beta"), ChannelSwitcherService.Channel.BETA);
|
||||||
|
RestTemplate http = stubHttp(svc);
|
||||||
|
stubTags(http, "igmlcreation/loremind-beta-core", List.of("beta", "1.5.0-beta", "1.6.0-beta"));
|
||||||
|
|
||||||
|
UpdateCheckService.BetaStatus status = svc.checkBeta();
|
||||||
|
|
||||||
|
assertTrue(status.enabled());
|
||||||
|
assertTrue(status.updateAvailable());
|
||||||
|
@SuppressWarnings("rawtypes")
|
||||||
|
ArgumentCaptor<HttpEntity> sent = ArgumentCaptor.forClass(HttpEntity.class);
|
||||||
|
verify(http).exchange(eq("https://ghcr.io/v2/igmlcreation/loremind-beta-core/tags/list"),
|
||||||
|
eq(HttpMethod.GET), sent.capture(), eq(TagsListResponse.class));
|
||||||
|
assertFalse(sent.getValue().getHeaders().containsKey(HttpHeaders.AUTHORIZATION),
|
||||||
|
"plus d'identifiants : les images beta sont publiques");
|
||||||
|
}
|
||||||
|
|
||||||
private static RestTemplate stubHttp(UpdateCheckService svc) {
|
private static RestTemplate stubHttp(UpdateCheckService svc) {
|
||||||
RestTemplate http = mock(RestTemplate.class);
|
RestTemplate http = mock(RestTemplate.class);
|
||||||
ReflectionTestUtils.setField(svc, "http", http);
|
ReflectionTestUtils.setField(svc, "http", http);
|
||||||
|
|||||||
+1
-1
@@ -90,7 +90,7 @@ class RemoteAccessFilterTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void lan_adminRoutes_areAlwaysForbidden_evenWhenPaired() throws Exception {
|
void lan_adminRoutes_areAlwaysForbidden_evenWhenPaired() throws Exception {
|
||||||
for (String path : new String[]{"/api/settings", "/api/settings/remote-access", "/api/admin/data/export", "/api/license"}) {
|
for (String path : new String[]{"/api/settings", "/api/settings/remote-access", "/api/admin/data/export", "/api/admin/updates/channel"}) {
|
||||||
Outcome outcome = run(LAN_PORT, path, "bon-jeton");
|
Outcome outcome = run(LAN_PORT, path, "bon-jeton");
|
||||||
assertFalse(outcome.passed(), path);
|
assertFalse(outcome.passed(), path);
|
||||||
assertEquals(403, outcome.status(), path);
|
assertEquals(403, outcome.status(), path);
|
||||||
|
|||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.core.task.TaskExecutor;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* La langue de l'interface suit les traitements de fond : sans ce relais, les imports de PDF
|
||||||
|
* et les flux IA lancés dans l'exécuteur partaient toujours en français.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
class UserLanguageTaskDecoratorTest {
|
||||||
|
|
||||||
|
@Autowired @Qualifier("applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void clear() {
|
||||||
|
UserLanguageHolder.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void applicationTaskExecutor_runsTasksInTheRequestLanguage() throws Exception {
|
||||||
|
UserLanguageHolder.set("en");
|
||||||
|
CompletableFuture<String> seen = new CompletableFuture<>();
|
||||||
|
taskExecutor.execute(() -> seen.complete(UserLanguageHolder.get()));
|
||||||
|
assertEquals("en", seen.get(5, TimeUnit.SECONDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decorator_restoresTheWorkerThreadLanguageAfterTheTask() {
|
||||||
|
UserLanguageHolder.set("en");
|
||||||
|
Runnable decorated = new UserLanguageTaskDecorator().decorate(() -> assertEquals("en", UserLanguageHolder.get()));
|
||||||
|
UserLanguageHolder.set("fr"); // le « thread de travail » avait une autre langue
|
||||||
|
decorated.run();
|
||||||
|
assertEquals("fr", UserLanguageHolder.get(), "pas de fuite vers la tâche suivante du pool");
|
||||||
|
}
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
@Transactional
|
||||||
|
class GuidedAssistControllerTest {
|
||||||
|
|
||||||
|
@Autowired private MockMvc mockMvc;
|
||||||
|
@Autowired private CampaignRepository campaignRepository;
|
||||||
|
@MockitoBean private GuidedMethodAssistant assistant;
|
||||||
|
|
||||||
|
private static final String BODY = """
|
||||||
|
{"methodName":"Enquête en nœuds","principle":"Trois pistes","idea":"Une tour se rallume",
|
||||||
|
"questions":[{"key":"title","label":"Nom","hint":"","step":"Le mystère","options":[]}],
|
||||||
|
"existing":{}}""";
|
||||||
|
|
||||||
|
private String campaignId() {
|
||||||
|
return campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_returnsTheFilteredAnswers() throws Exception {
|
||||||
|
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap()))
|
||||||
|
.thenReturn(Map.of("title", "L'héritage empoisonné", "other", "x"));
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(BODY))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.answers.title").value("L'héritage empoisonné"))
|
||||||
|
.andExpect(jsonPath("$.answers.other").doesNotExist());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_unknownCampaign_is404_andUnavailableAi_is502() throws Exception {
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", "999999999")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(BODY))
|
||||||
|
.andExpect(status().isNotFound());
|
||||||
|
|
||||||
|
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap()))
|
||||||
|
.thenThrow(new NarrativeAssistException("Le Brain est injoignable"));
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(BODY))
|
||||||
|
.andExpect(status().isBadGateway());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_withoutQuestions_is400() throws Exception {
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content("{\"idea\":\"x\",\"questions\":[]}"))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
}
|
||||||
|
}
|
||||||
-263
@@ -1,263 +0,0 @@
|
|||||||
package com.loremind.infrastructure.web.controller;
|
|
||||||
|
|
||||||
import com.loremind.application.licensing.ChannelSwitcherService;
|
|
||||||
import com.loremind.application.licensing.LicenseService;
|
|
||||||
import com.loremind.application.licensing.LicenseService.InstallException;
|
|
||||||
import com.loremind.domain.licensing.LicenseSnapshot;
|
|
||||||
import com.loremind.domain.licensing.LicenseStatus;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
|
||||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Base64;
|
|
||||||
|
|
||||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
|
||||||
import static org.mockito.Mockito.doThrow;
|
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tests d'integration pour {@link LicenseController} (gestion licence Patreon).
|
|
||||||
* <p>
|
|
||||||
* {@code /api/license/**} exige le role ADMIN (HTTP Basic) : chaque requete porte
|
|
||||||
* l'entete d'auth construite a partir des identifiants de test (cf.
|
|
||||||
* src/test/resources/application.properties). Sans cet entete, la securite
|
|
||||||
* renverrait 401.
|
|
||||||
* <p>
|
|
||||||
* Les deux services applicatifs sont mockes : {@link LicenseService} (qui appelle
|
|
||||||
* sinon le relais OAuth distant + verification JWT) et {@link ChannelSwitcherService}
|
|
||||||
* (qui ecrit sinon dans un volume partage avec le sidecar). Aucun acces reseau ni
|
|
||||||
* fichier reel.
|
|
||||||
*/
|
|
||||||
@SpringBootTest
|
|
||||||
@AutoConfigureMockMvc
|
|
||||||
class LicenseControllerTest {
|
|
||||||
|
|
||||||
/** Identifiants definis dans src/test/resources/application.properties. */
|
|
||||||
private static final String ADMIN_AUTH = "Basic " + Base64.getEncoder()
|
|
||||||
.encodeToString("test-admin:test-admin-password".getBytes(StandardCharsets.UTF_8));
|
|
||||||
|
|
||||||
/** Horodatage fixe : la valeur exacte n'importe pas, seule la sérialisation JSON est testée. */
|
|
||||||
private static final Instant FIXED_NOW = Instant.parse("2026-01-01T12:00:00Z");
|
|
||||||
|
|
||||||
@Autowired private MockMvc mockMvc;
|
|
||||||
|
|
||||||
@MockitoBean private LicenseService licenseService;
|
|
||||||
@MockitoBean private ChannelSwitcherService channelSwitcher;
|
|
||||||
|
|
||||||
private LicenseSnapshot validSnapshot() {
|
|
||||||
return new LicenseSnapshot(
|
|
||||||
LicenseStatus.VALID, "user-42", "tier-1", "li-xyz",
|
|
||||||
FIXED_NOW.plusSeconds(3600), FIXED_NOW, true, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
// Valeurs par defaut neutres ; chaque test surcharge ce dont il a besoin.
|
|
||||||
when(licenseService.isLicensingEnabled()).thenReturn(true);
|
|
||||||
when(licenseService.getCurrentSnapshot()).thenReturn(validSnapshot());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Securite ----------------------------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getStatus_returns401_withoutAuth() throws Exception {
|
|
||||||
mockMvc.perform(get("/api/license"))
|
|
||||||
.andExpect(status().isUnauthorized());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- GET /api/license --------------------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getStatus_returns200() throws Exception {
|
|
||||||
mockMvc.perform(get("/api/license").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$.enabled").value(true))
|
|
||||||
.andExpect(jsonPath("$.status").value("VALID"))
|
|
||||||
.andExpect(jsonPath("$.patreonUserId").value("user-42"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- GET /api/license/connect-url --------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getConnectUrl_returns200() throws Exception {
|
|
||||||
when(licenseService.buildConnectUrl()).thenReturn("https://relay/oauth?x=1");
|
|
||||||
mockMvc.perform(get("/api/license/connect-url").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$.url").value("https://relay/oauth?x=1"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- POST /api/license/install -----------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void install_returns200_onValidJwt() throws Exception {
|
|
||||||
when(licenseService.installToken("good-jwt")).thenReturn(validSnapshot());
|
|
||||||
mockMvc.perform(post("/api/license/install")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"jwt\":\"good-jwt\"}"))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$.status").value("VALID"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void install_returns400_whenJwtMissing() throws Exception {
|
|
||||||
mockMvc.perform(post("/api/license/install")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"jwt\":\"\"}"))
|
|
||||||
.andExpect(status().isBadRequest())
|
|
||||||
.andExpect(jsonPath("$.error").value("missing jwt"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void install_returns400_whenInstallFails() throws Exception {
|
|
||||||
when(licenseService.installToken("bad-jwt"))
|
|
||||||
.thenThrow(new InstallException("Invalid JWT: signature"));
|
|
||||||
mockMvc.perform(post("/api/license/install")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"jwt\":\"bad-jwt\"}"))
|
|
||||||
.andExpect(status().isBadRequest())
|
|
||||||
.andExpect(jsonPath("$.error").value("Invalid JWT: signature"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- DELETE /api/license -----------------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void disconnect_returns204() throws Exception {
|
|
||||||
mockMvc.perform(delete("/api/license").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
|
||||||
.andExpect(status().isNoContent());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- POST /api/license/refresh -----------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void refresh_returns200() throws Exception {
|
|
||||||
mockMvc.perform(post("/api/license/refresh").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$.status").value("VALID"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- PUT /api/license/beta-channel -------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setBetaChannel_returns200() throws Exception {
|
|
||||||
when(licenseService.setBetaChannelEnabled(false)).thenReturn(validSnapshot());
|
|
||||||
mockMvc.perform(put("/api/license/beta-channel")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"enabled\":false}"))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$.status").value("VALID"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void setBetaChannel_returns409_whenNoLicense() throws Exception {
|
|
||||||
when(licenseService.setBetaChannelEnabled(anyBoolean()))
|
|
||||||
.thenThrow(new IllegalStateException("No license installed"));
|
|
||||||
mockMvc.perform(put("/api/license/beta-channel")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"enabled\":true}"))
|
|
||||||
.andExpect(status().isConflict())
|
|
||||||
.andExpect(jsonPath("$.error").value("No license installed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- GET /api/license/channel ------------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getChannel_returns200() throws Exception {
|
|
||||||
when(channelSwitcher.getCurrentChannel()).thenReturn(ChannelSwitcherService.Channel.STABLE);
|
|
||||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
|
||||||
when(channelSwitcher.getLastResult()).thenReturn(null);
|
|
||||||
mockMvc.perform(get("/api/license/channel").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$.currentChannel").value("stable"))
|
|
||||||
.andExpect(jsonPath("$.switcherAvailable").value(true));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- POST /api/license/channel/switch ----------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void switchChannel_returns400_whenChannelMissing() throws Exception {
|
|
||||||
mockMvc.perform(post("/api/license/channel/switch")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{}"))
|
|
||||||
.andExpect(status().isBadRequest())
|
|
||||||
.andExpect(jsonPath("$.error").value("missing channel"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void switchChannel_returns400_whenChannelInvalid() throws Exception {
|
|
||||||
mockMvc.perform(post("/api/license/channel/switch")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"channel\":\"nightly\"}"))
|
|
||||||
.andExpect(status().isBadRequest());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void switchChannel_returns403_whenBetaWithoutLicense() throws Exception {
|
|
||||||
// Snapshot EXPIRED -> pas d'acces beta.
|
|
||||||
when(licenseService.getCurrentSnapshot()).thenReturn(new LicenseSnapshot(
|
|
||||||
LicenseStatus.EXPIRED, null, null, null, null, null, false, false));
|
|
||||||
mockMvc.perform(post("/api/license/channel/switch")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"channel\":\"beta\"}"))
|
|
||||||
.andExpect(status().isForbidden());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void switchChannel_returns503_whenSwitcherUnavailable() throws Exception {
|
|
||||||
// Licence VALID (autorise beta) mais sidecar absent.
|
|
||||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(false);
|
|
||||||
mockMvc.perform(post("/api/license/channel/switch")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"channel\":\"beta\"}"))
|
|
||||||
.andExpect(status().isServiceUnavailable());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void switchChannel_returns202_onSuccess() throws Exception {
|
|
||||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
|
||||||
when(channelSwitcher.requestSwitch(ChannelSwitcherService.Channel.STABLE))
|
|
||||||
.thenReturn("cmd-1");
|
|
||||||
mockMvc.perform(post("/api/license/channel/switch")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"channel\":\"stable\"}"))
|
|
||||||
.andExpect(status().isAccepted())
|
|
||||||
.andExpect(jsonPath("$.id").value("cmd-1"))
|
|
||||||
.andExpect(jsonPath("$.channel").value("stable"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void switchChannel_returns500_whenWriteFails() throws Exception {
|
|
||||||
when(channelSwitcher.isSwitcherAvailable()).thenReturn(true);
|
|
||||||
doThrow(new IOException("disk full"))
|
|
||||||
.when(channelSwitcher).requestSwitch(ChannelSwitcherService.Channel.STABLE);
|
|
||||||
mockMvc.perform(post("/api/license/channel/switch")
|
|
||||||
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content("{\"channel\":\"stable\"}"))
|
|
||||||
.andExpect(status().isInternalServerError());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+48
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.infrastructure.web.controller;
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.channel.ChannelSwitcherService;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService;
|
import com.loremind.infrastructure.updates.UpdateCheckService;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService.BetaStatus;
|
import com.loremind.infrastructure.updates.UpdateCheckService.BetaStatus;
|
||||||
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatus;
|
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatus;
|
||||||
@@ -11,6 +12,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock
|
|||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
@@ -45,6 +47,7 @@ class UpdatesControllerTest {
|
|||||||
|
|
||||||
@Autowired private MockMvc mockMvc;
|
@Autowired private MockMvc mockMvc;
|
||||||
@MockitoBean private UpdateCheckService updates;
|
@MockitoBean private UpdateCheckService updates;
|
||||||
|
@MockitoBean private ChannelSwitcherService channels;
|
||||||
|
|
||||||
private UpdateStatus sampleUpdate() {
|
private UpdateStatus sampleUpdate() {
|
||||||
return new UpdateStatus(true, true, false, "1.0.0",
|
return new UpdateStatus(true, true, false, "1.0.0",
|
||||||
@@ -56,6 +59,51 @@ class UpdatesControllerTest {
|
|||||||
return new BetaStatus(true, false, false, List.of(), FIXED_INSTANT, null);
|
return new BetaStatus(true, false, false, List.of(), FIXED_INSTANT, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Canal beta libre : bascule sans licence -------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void switchToBeta_isAcceptedWithoutAnyLicense() throws Exception {
|
||||||
|
when(channels.isSwitcherAvailable()).thenReturn(true);
|
||||||
|
when(channels.requestSwitch(ChannelSwitcherService.Channel.BETA))
|
||||||
|
.thenReturn("cmd-1");
|
||||||
|
mockMvc.perform(post("/api/admin/updates/channel/switch")
|
||||||
|
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("{\"channel\":\"beta\"}"))
|
||||||
|
.andExpect(status().isAccepted())
|
||||||
|
.andExpect(jsonPath("$.id").value("cmd-1"))
|
||||||
|
.andExpect(jsonPath("$.channel").value("beta"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void switchChannel_rejectsUnknownChannel() throws Exception {
|
||||||
|
mockMvc.perform(post("/api/admin/updates/channel/switch")
|
||||||
|
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("{\"channel\":\"nightly\"}"))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void switchChannel_503WhenSwitcherMissing() throws Exception {
|
||||||
|
when(channels.isSwitcherAvailable()).thenReturn(false);
|
||||||
|
mockMvc.perform(post("/api/admin/updates/channel/switch")
|
||||||
|
.header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("{\"channel\":\"beta\"}"))
|
||||||
|
.andExpect(status().isServiceUnavailable());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void channel_returnsCurrentChannel() throws Exception {
|
||||||
|
when(channels.getCurrentChannel()).thenReturn(ChannelSwitcherService.Channel.BETA);
|
||||||
|
when(channels.isSwitcherAvailable()).thenReturn(true);
|
||||||
|
mockMvc.perform(get("/api/admin/updates/channel").header(HttpHeaders.AUTHORIZATION, ADMIN_AUTH))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.currentChannel").value("beta"))
|
||||||
|
.andExpect(jsonPath("$.switcherAvailable").value(true));
|
||||||
|
}
|
||||||
|
|
||||||
// --- GET /check ---------------------------------------------------------
|
// --- GET /check ---------------------------------------------------------
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -43,11 +43,6 @@ minio.bucket=test-bucket
|
|||||||
# open-in-view fixe explicitement (defaut true) : supprime l'avertissement au boot.
|
# open-in-view fixe explicitement (defaut true) : supprime l'avertissement au boot.
|
||||||
spring.jpa.open-in-view=true
|
spring.jpa.open-in-view=true
|
||||||
|
|
||||||
# Le daemon de refresh de licence (@Scheduled) n'a rien a faire pendant les tests :
|
|
||||||
# son tick echouait en arriere-plan (table licenses droppee par le create-drop
|
|
||||||
# partage entre contextes) => stacktraces parasites. On le desactive ici.
|
|
||||||
licensing.refresh.enabled=false
|
|
||||||
|
|
||||||
# --- Sortie de test LISIBLE ---------------------------------------------------
|
# --- Sortie de test LISIBLE ---------------------------------------------------
|
||||||
# Pas de banniere Spring (repetee a chaque contexte), et seuls les WARN/ERROR
|
# Pas de banniere Spring (repetee a chaque contexte), et seuls les WARN/ERROR
|
||||||
# remontent : la masse d'INFO de demarrage (Spring/Hibernate/Hikari, "Started
|
# remontent : la masse d'INFO de demarrage (Spring/Hibernate/Hikari, "Started
|
||||||
|
|||||||
@@ -94,22 +94,10 @@ services:
|
|||||||
UPDATE_CHECK_TAG: ${TAG:-latest}
|
UPDATE_CHECK_TAG: ${TAG:-latest}
|
||||||
WATCHTOWER_URL: http://watchtower:8080
|
WATCHTOWER_URL: http://watchtower:8080
|
||||||
WATCHTOWER_TOKEN: ${WATCHTOWER_TOKEN:-}
|
WATCHTOWER_TOKEN: ${WATCHTOWER_TOKEN:-}
|
||||||
# Licensing : la cle publique JWT est embarquee dans le binaire
|
|
||||||
# (core/src/main/resources/licensing/jwt-public-key.pem).
|
|
||||||
# LICENSING_JWT_PUBLIC_KEY est un override optionnel (rotation de cle
|
|
||||||
# sans rebuild) - non defini par defaut.
|
|
||||||
LICENSING_JWT_PUBLIC_KEY: ${LICENSING_JWT_PUBLIC_KEY:-}
|
|
||||||
LICENSING_RELAY_BASE_URL: ${LICENSING_RELAY_BASE_URL:-https://loremind-auth.igmlcreation.fr}
|
|
||||||
# Chemin du docker config.json partage avec Watchtower
|
|
||||||
LICENSING_DOCKER_CONFIG_PATH: /shared/docker/config.json
|
|
||||||
# Chemin du repertoire partage avec le switcher (commande + resultat).
|
# Chemin du repertoire partage avec le switcher (commande + resultat).
|
||||||
# Doit matcher le volume `switcher-data` monte ci-dessous.
|
# Doit matcher le volume `switcher-data` monte ci-dessous.
|
||||||
SWITCHER_DATA_PATH: /shared/switcher
|
SWITCHER_DATA_PATH: /shared/switcher
|
||||||
volumes:
|
volumes:
|
||||||
# Volume partage avec Watchtower : Core ecrit les credentials registry
|
|
||||||
# GHCR (recus du relais) ici, Watchtower les utilise pour pull les images
|
|
||||||
# privees du canal beta. Pas de creds = no-op.
|
|
||||||
- docker-config:/shared/docker
|
|
||||||
# Volume partage avec le switcher : Core ecrit une commande de switch
|
# Volume partage avec le switcher : Core ecrit une commande de switch
|
||||||
# de canal ici (command.json), le switcher la traite et y depose son
|
# de canal ici (command.json), le switcher la traite et y depose son
|
||||||
# resultat (result.json). Cf. service `switcher` ci-dessous.
|
# resultat (result.json). Cf. service `switcher` ci-dessous.
|
||||||
@@ -202,10 +190,6 @@ services:
|
|||||||
- ${COMPOSE_PROJECT_DIR:-./}:/compose
|
- ${COMPOSE_PROJECT_DIR:-./}:/compose
|
||||||
# Volume partage avec le Core pour la commande + le resultat.
|
# Volume partage avec le Core pour la commande + le resultat.
|
||||||
- switcher-data:/data
|
- switcher-data:/data
|
||||||
# Volume partage avec le Core + Watchtower : contient config.json avec
|
|
||||||
# les creds GHCR (ecrits par le Core a partir du token Patreon).
|
|
||||||
# Indispensable pour pull les images privees du canal beta.
|
|
||||||
- docker-config:/shared/docker
|
|
||||||
environment:
|
environment:
|
||||||
# Repertoire interne ou trouver docker-compose.yml et .env. Bind au
|
# Repertoire interne ou trouver docker-compose.yml et .env. Bind au
|
||||||
# volume ci-dessus (COMPOSE_PROJECT_DIR = repertoire d'install du host).
|
# volume ci-dessus (COMPOSE_PROJECT_DIR = repertoire d'install du host).
|
||||||
@@ -214,9 +198,6 @@ services:
|
|||||||
# le MEME stack que celui qui tourne (sinon il creerait un duplicate).
|
# le MEME stack que celui qui tourne (sinon il creerait un duplicate).
|
||||||
# Doit matcher le `name:` (en V2.x) ou le nom du dossier du host.
|
# Doit matcher le `name:` (en V2.x) ou le nom du dossier du host.
|
||||||
COMPOSE_PROJECT_NAME: ${COMPOSE_PROJECT_NAME:-loremind}
|
COMPOSE_PROJECT_NAME: ${COMPOSE_PROJECT_NAME:-loremind}
|
||||||
# Indique au CLI Docker du switcher ou trouver config.json (auth GHCR
|
|
||||||
# pour les images privees beta). Meme mecanisme que sur Watchtower.
|
|
||||||
DOCKER_CONFIG: /shared/docker
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
# Mises a jour automatiques des images core/brain/web.
|
# Mises a jour automatiques des images core/brain/web.
|
||||||
@@ -234,14 +215,7 @@ services:
|
|||||||
profiles: ["autoupdate"]
|
profiles: ["autoupdate"]
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
# Volume partage avec Core : credentials registry GHCR (canal beta).
|
|
||||||
# Watchtower lit le config.json depuis DOCKER_CONFIG.
|
|
||||||
- docker-config:/shared/docker
|
|
||||||
environment:
|
environment:
|
||||||
# Indique a Watchtower (et au CLI Docker embarque) ou trouver le
|
|
||||||
# config.json. Active automatiquement l'auth GHCR pour les images
|
|
||||||
# du canal beta des que Core a ecrit le fichier.
|
|
||||||
DOCKER_CONFIG: /shared/docker
|
|
||||||
WATCHTOWER_LABEL_ENABLE: "true"
|
WATCHTOWER_LABEL_ENABLE: "true"
|
||||||
WATCHTOWER_CLEANUP: "true"
|
WATCHTOWER_CLEANUP: "true"
|
||||||
WATCHTOWER_INCLUDE_RESTARTING: "true"
|
WATCHTOWER_INCLUDE_RESTARTING: "true"
|
||||||
@@ -267,8 +241,5 @@ volumes:
|
|||||||
minio-data:
|
minio-data:
|
||||||
brain-data:
|
brain-data:
|
||||||
ollama-data:
|
ollama-data:
|
||||||
# Volume partage Core <-> Watchtower : config.json Docker pour
|
|
||||||
# l'authentification au registry prive GHCR (canal beta Patreon).
|
|
||||||
docker-config:
|
|
||||||
# Volume partage Core <-> Switcher : commande de bascule de canal + resultat.
|
# Volume partage Core <-> Switcher : commande de bascule de canal + resultat.
|
||||||
switcher-data:
|
switcher-data:
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "1.5.0-beta",
|
"version": "1.6.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "1.5.0-beta",
|
"version": "1.6.2",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular/animations": "^21.2.17",
|
"@angular/animations": "^21.2.17",
|
||||||
"@angular/cdk": "^21.2.14",
|
"@angular/cdk": "^21.2.14",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "1.5.0-beta",
|
"version": "1.6.2",
|
||||||
"description": "LoreMind Frontend - Angular",
|
"description": "LoreMind Frontend - Angular",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"ng": "ng",
|
"ng": "ng",
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { Npc } from '../services/npc.model';
|
|||||||
import { RandomTable } from '../services/random-table.model';
|
import { RandomTable } from '../services/random-table.model';
|
||||||
import { Enemy } from '../services/enemy.model';
|
import { Enemy } from '../services/enemy.model';
|
||||||
import { CampaignReadinessAssessment, ReadinessGap, ReadinessSeverity, ReadinessEntityType } from '../services/readiness.model';
|
import { CampaignReadinessAssessment, ReadinessGap, ReadinessSeverity, ReadinessEntityType } from '../services/readiness.model';
|
||||||
|
import { flatContainer } from './flat-structure';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper — charge l'arborescence complète d'une campagne (arcs -> chapitres -> scènes)
|
* Helper — charge l'arborescence complète d'une campagne (arcs -> chapitres -> scènes)
|
||||||
@@ -365,12 +366,13 @@ export function buildCampaignTree(
|
|||||||
// des scènes et l'ajout restent identiques (c'est le nœud chapitre, relabellisé
|
// des scènes et l'ajout restent identiques (c'est le nœud chapitre, relabellisé
|
||||||
// et remonté à la racine). Dès qu'un 2e arc OU un 2e chapitre existe, la
|
// et remonté à la racine). Dès qu'un 2e arc OU un 2e chapitre existe, la
|
||||||
// structure complète réapparaît automatiquement.
|
// structure complète réapparaît automatiquement.
|
||||||
const onlyArc = sortedArcs.length === 1 ? sortedArcs[0] : null;
|
// Mode plat seulement si l'arc et le chapitre uniques sont VIDES (cf. flatContainer) :
|
||||||
const onlyArcChapters = onlyArc ? (data.chaptersByArc[onlyArc.id!] ?? []) : [];
|
// un chapitre écrit par une méthode guidée doit rester visible.
|
||||||
|
const flat = flatContainer(sortedArcs, data.chaptersByArc);
|
||||||
|
const onlyArc = flat?.arc ?? null;
|
||||||
let narrationNodes: TreeItem[] = arcNodes;
|
let narrationNodes: TreeItem[] = arcNodes;
|
||||||
// Le mode plat ne s'applique PAS à un arc HUB (qui présente des quêtes, pas juste des scènes).
|
if (flat && onlyArc) {
|
||||||
if (onlyArc && onlyArc.type !== 'HUB' && onlyArcChapters.length === 1) {
|
const ch = flat.chapter;
|
||||||
const ch = onlyArcChapters[0];
|
|
||||||
const sortedScenes = [...(data.scenesByChapter[ch.id!] ?? [])].sort(byOrder);
|
const sortedScenes = [...(data.scenesByChapter[ch.id!] ?? [])].sort(byOrder);
|
||||||
const sceneItems: TreeItem[] = sortedScenes.map(sc => ({
|
const sceneItems: TreeItem[] = sortedScenes.map(sc => ({
|
||||||
id: `scene-${sc.id}`,
|
id: `scene-${sc.id}`,
|
||||||
|
|||||||
@@ -228,7 +228,7 @@
|
|||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@if (arcs.length > 0 && !showQuickAddScene) {
|
@if (arcs.length > 0 && !flatMode) {
|
||||||
<div class="arcs-grid" cdkDropList cdkDropListOrientation="mixed"
|
<div class="arcs-grid" cdkDropList cdkDropListOrientation="mixed"
|
||||||
(cdkDropListDropped)="dropArc($event)">
|
(cdkDropListDropped)="dropArc($event)">
|
||||||
@for (arc of arcs; track arc.id) {
|
@for (arc of arcs; track arc.id) {
|
||||||
@@ -242,7 +242,7 @@
|
|||||||
}
|
}
|
||||||
<!-- Mode plat (un seul arc d'un seul chapitre) : on masque la carte de
|
<!-- Mode plat (un seul arc d'un seul chapitre) : on masque la carte de
|
||||||
l'arc par défaut, comme dans la sidebar. Les scènes vivent dans le volet. -->
|
l'arc par défaut, comme dans la sidebar. Les scènes vivent dans le volet. -->
|
||||||
@if (arcs.length > 0 && showQuickAddScene) {
|
@if (arcs.length > 0 && flatMode) {
|
||||||
<div class="empty-state empty-state--compact">
|
<div class="empty-state empty-state--compact">
|
||||||
<p>{{ 'campaignDetail.flatModeHint' | translate }}</p>
|
<p>{{ 'campaignDetail.flatModeHint' | translate }}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user