Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0f2d1b1efe | |||
| 5ff05242a8 | |||
| b06c77a1eb | |||
| 03bc669efe | |||
| c3873ddd84 | |||
| d7ceeac1b0 | |||
| cdbd3cd9b4 | |||
| a708c74425 | |||
| 9ad7651c44 | |||
| 389392fd1d | |||
| aaebeaa547 | |||
| 03ee3855f5 | |||
| 94a39cf3b4 | |||
| efe6f6c2b0 | |||
| 73a9d15786 | |||
| dfe05cf2d2 | |||
| fcba907438 | |||
| 5739602702 | |||
| addf78f01d | |||
| 5e04e84ee4 | |||
| 8d5c2e2b7f | |||
| 788d2c12f2 | |||
| b25a9746cf |
@@ -6,8 +6,10 @@ on:
|
|||||||
- 'v*'
|
- 'v*'
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: git.igmlcreation.fr
|
GITEA_REGISTRY: git.igmlcreation.fr
|
||||||
REGISTRY_USER: ietm64
|
GITEA_REGISTRY_USER: ietm64
|
||||||
|
GHCR_REGISTRY: ghcr.io
|
||||||
|
GHCR_NAMESPACE: igmlcreation
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -26,19 +28,39 @@ jobs:
|
|||||||
- name: Login to Gitea Registry
|
- name: Login to Gitea Registry
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.GITEA_REGISTRY }}
|
||||||
username: ${{ env.REGISTRY_USER }}
|
username: ${{ env.GITEA_REGISTRY_USER }}
|
||||||
password: ${{ secrets.DOCKER_PAT }}
|
password: ${{ secrets.DOCKER_PAT }}
|
||||||
|
|
||||||
|
# Login to GHCR (GitHub Container Registry) pour distribuer les images
|
||||||
|
# publiquement aux utilisateurs finaux. Reputation domaine plus elevee
|
||||||
|
# que git.igmlcreation.fr (mieux pour les antivirus / SmartScreen).
|
||||||
|
- name: Login to GHCR
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.GHCR_REGISTRY }}
|
||||||
|
username: ${{ env.GHCR_NAMESPACE }}
|
||||||
|
password: ${{ secrets.GHCR_TOKEN }}
|
||||||
|
|
||||||
- name: Extract version
|
- name: Extract version
|
||||||
id: meta
|
id: meta
|
||||||
run: echo "version=${GITHUB_REF_NAME#v}" >> $GITHUB_OUTPUT
|
run: echo "version=${GITHUB_REF_NAME#v}" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
# Push vers les deux registries en un seul build (build-push-action
|
||||||
|
# accepte une liste de tags ; aucun build supplementaire necessaire).
|
||||||
|
# Naming :
|
||||||
|
# - Gitea : conserve l'ancien pattern ietm64/<component> pour ne pas
|
||||||
|
# casser les installs existantes qui ont REGISTRY=git.igmlcreation.fr
|
||||||
|
# dans leur .env.
|
||||||
|
# - GHCR : nouveau pattern igmlcreation/loremind-<component> qui evite
|
||||||
|
# la collision avec d'autres projets de l'org.
|
||||||
- name: Build & push ${{ matrix.component }}
|
- name: Build & push ${{ matrix.component }}
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
context: ./${{ matrix.component }}
|
context: ./${{ matrix.component }}
|
||||||
push: true
|
push: true
|
||||||
tags: |
|
tags: |
|
||||||
${{ env.REGISTRY }}/${{ env.REGISTRY_USER }}/${{ matrix.component }}:latest
|
${{ env.GITEA_REGISTRY }}/${{ env.GITEA_REGISTRY_USER }}/${{ matrix.component }}:latest
|
||||||
${{ env.REGISTRY }}/${{ env.REGISTRY_USER }}/${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
${{ env.GITEA_REGISTRY }}/${{ env.GITEA_REGISTRY_USER }}/${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||||
|
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:latest
|
||||||
|
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||||
|
|||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -91,8 +91,14 @@ Thumbs.db
|
|||||||
# Documentation hors-code (conservee hors du repo)
|
# Documentation hors-code (conservee hors du repo)
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
docs/
|
docs/
|
||||||
|
loremind-docs/
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Docker Compose override (dev uniquement, non-distribue aux end users)
|
# Docker Compose override (dev uniquement, non-distribue aux end users)
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
docker-compose.override.yml
|
docker-compose.override.yml
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Relais OAuth Patreon (repo Gitea separe, clone localement pour facilite)
|
||||||
|
# ============================================================================
|
||||||
|
relay/
|
||||||
|
|||||||
311
INSTALL.md
311
INSTALL.md
@@ -1,311 +0,0 @@
|
|||||||
# Installation de LoreMindMJ
|
|
||||||
|
|
||||||
Ce document decrit la procedure d'installation de LoreMindMJ. Temps estime :
|
|
||||||
5 a 10 minutes selon la qualite de la connexion reseau.
|
|
||||||
|
|
||||||
## 1. Prerequis
|
|
||||||
|
|
||||||
- **Docker Desktop** ([Windows](https://www.docker.com/products/docker-desktop/) /
|
|
||||||
[Mac](https://www.docker.com/products/docker-desktop/)) ou
|
|
||||||
**Docker Engine + Compose v2** (Linux). Verification :
|
|
||||||
```
|
|
||||||
docker --version
|
|
||||||
docker compose version
|
|
||||||
```
|
|
||||||
Compose v2 est requis : la commande est `docker compose`, non `docker-compose`.
|
|
||||||
|
|
||||||
- **Un fournisseur LLM**, au choix :
|
|
||||||
- **[Ollama](https://ollama.com/)** installe sur la machine hote (gratuit,
|
|
||||||
local, necessite environ 6 Go de RAM libre pour les modeles recommandes).
|
|
||||||
- **Une cle API [1min.ai](https://1min.ai)** (hebergement cloud, facturation
|
|
||||||
a l'usage, aucune installation supplementaire requise).
|
|
||||||
|
|
||||||
- Environ **2 Go d'espace disque** pour les images Docker, auxquels s'ajoute
|
|
||||||
la taille des modeles Ollama si l'option locale est retenue.
|
|
||||||
|
|
||||||
## 2. Recuperation des fichiers
|
|
||||||
|
|
||||||
Telecharger les deux fichiers suivants depuis la
|
|
||||||
[derniere release](https://git.igmlcreation.fr/ietm64/LoreMindMJ/releases) et
|
|
||||||
les placer dans un dossier dedie (par exemple `~/loremind/` ou
|
|
||||||
`C:\Programs\loremind\`) :
|
|
||||||
|
|
||||||
- `docker-compose.yml`
|
|
||||||
- `.env.example`
|
|
||||||
|
|
||||||
Le code source n'est pas necessaire : les images sont pre-construites et
|
|
||||||
publiees sur le registry Gitea `git.igmlcreation.fr` (non Docker Hub). Le
|
|
||||||
premier `docker compose pull` les telechargera automatiquement.
|
|
||||||
|
|
||||||
## 3. Configuration du fichier `.env`
|
|
||||||
|
|
||||||
Renommer `.env.example` en `.env` et l'ouvrir dans un editeur de texte. **Trois
|
|
||||||
variables sont obligatoires** ; sans elles, `docker compose up` refusera de
|
|
||||||
demarrer. Ce comportement est volontaire afin d'eviter tout deploiement
|
|
||||||
non-securise par defaut.
|
|
||||||
|
|
||||||
### `POSTGRES_PASSWORD`
|
|
||||||
|
|
||||||
Mot de passe de la base de donnees PostgreSQL. Choisir une valeur robuste.
|
|
||||||
Seuls les conteneurs utilisent cette valeur : il n'est pas necessaire de la
|
|
||||||
memoriser au-dela du fichier `.env`.
|
|
||||||
|
|
||||||
### `ADMIN_PASSWORD`
|
|
||||||
|
|
||||||
Protege l'ecran **Parametres** de l'application via HTTP Basic. Cette valeur
|
|
||||||
sera demandee par le navigateur lors de toute modification de la configuration
|
|
||||||
(changement de modele LLM, saisie de cle API, etc.). Le nom d'utilisateur par
|
|
||||||
defaut est `admin`, modifiable via la variable `ADMIN_USERNAME`.
|
|
||||||
|
|
||||||
### `BRAIN_INTERNAL_SECRET`
|
|
||||||
|
|
||||||
Secret partage entre le service Java (`core`) et le service Python (`brain`).
|
|
||||||
Empeche toute requete externe d'atteindre directement le service Brain.
|
|
||||||
Generer une valeur aleatoire de 64 caracteres hexadecimaux :
|
|
||||||
|
|
||||||
```
|
|
||||||
openssl rand -hex 32
|
|
||||||
```
|
|
||||||
|
|
||||||
Sous Windows sans `openssl`, utiliser PowerShell :
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
-join ((48..57) + (97..102) | Get-Random -Count 64 | % {[char]$_})
|
|
||||||
```
|
|
||||||
|
|
||||||
### Variables optionnelles
|
|
||||||
|
|
||||||
- `WEB_PORT` (defaut `8081`) : port d'ecoute de l'interface web.
|
|
||||||
- `ADMIN_USERNAME` (defaut `admin`) : identifiant de la popup Parametres.
|
|
||||||
- `LLM_PROVIDER` (defaut `ollama`) : choix du fournisseur LLM (voir
|
|
||||||
section 5).
|
|
||||||
|
|
||||||
Les autres variables (`MINIO_USER`/`MINIO_PASSWORD`, `POSTGRES_DB`,
|
|
||||||
`POSTGRES_USER`) disposent de valeurs par defaut adaptees a un deploiement
|
|
||||||
personnel et peuvent etre conservees en l'etat.
|
|
||||||
|
|
||||||
## 4. Lancement de la stack
|
|
||||||
|
|
||||||
Depuis le dossier contenant `docker-compose.yml` et `.env` :
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
Le premier demarrage telecharge les images (environ 1 a 2 Go au total) et
|
|
||||||
initialise la base. Compter 2 a 5 minutes selon la qualite de la connexion.
|
|
||||||
La progression peut etre suivie via :
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose logs -f
|
|
||||||
```
|
|
||||||
|
|
||||||
(`Ctrl+C` pour quitter l'affichage ; les services continuent de fonctionner
|
|
||||||
en arriere-plan.)
|
|
||||||
|
|
||||||
Une fois les services en etat `healthy`, ouvrir **http://localhost:8081**
|
|
||||||
dans un navigateur.
|
|
||||||
|
|
||||||
### Verification du fonctionnement
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose ps
|
|
||||||
```
|
|
||||||
|
|
||||||
Cinq conteneurs doivent apparaitre en etat `Up` ou `healthy` :
|
|
||||||
`loremind-postgres`, `loremind-minio`, `loremind-core`, `loremind-brain`,
|
|
||||||
`loremind-web`. Le conteneur `loremind-minio-init` s'arrete automatiquement
|
|
||||||
apres creation du bucket d'images : ce comportement est normal.
|
|
||||||
|
|
||||||
## 5. Configuration du fournisseur LLM
|
|
||||||
|
|
||||||
### Ollama (local, gratuit)
|
|
||||||
|
|
||||||
Installer Ollama sur la machine hote (pas dans Docker), puis telecharger un
|
|
||||||
modele :
|
|
||||||
|
|
||||||
```
|
|
||||||
ollama pull gemma4:26b
|
|
||||||
```
|
|
||||||
|
|
||||||
Dans `.env` :
|
|
||||||
|
|
||||||
```
|
|
||||||
LLM_PROVIDER=ollama
|
|
||||||
LLM_MODEL=gemma4:26b
|
|
||||||
OLLAMA_BASE_URL=http://host.docker.internal:11434
|
|
||||||
```
|
|
||||||
|
|
||||||
L'adresse `host.docker.internal` permet au conteneur `brain` d'atteindre
|
|
||||||
Ollama sur la machine hote. Cette resolution est native sous Docker Desktop
|
|
||||||
(Mac / Windows). Sous Linux, le fichier `docker-compose.yml` declare un
|
|
||||||
`extra_hosts` equivalent.
|
|
||||||
|
|
||||||
### 1min.ai (cloud, paye)
|
|
||||||
|
|
||||||
Dans `.env` :
|
|
||||||
|
|
||||||
```
|
|
||||||
LLM_PROVIDER=onemin
|
|
||||||
ONEMIN_API_KEY=sk-...
|
|
||||||
ONEMIN_MODEL=gpt-4o-mini
|
|
||||||
```
|
|
||||||
|
|
||||||
### Modification a chaud
|
|
||||||
|
|
||||||
Le fournisseur, le modele et la cle API peuvent etre modifies a chaud depuis
|
|
||||||
l'ecran **Parametres** de l'application. Les modifications sont persistees
|
|
||||||
dans un volume Docker et survivent aux redemarrages. Les variables d'env du
|
|
||||||
fichier `.env` sont uniquement utilisees comme valeurs initiales au premier
|
|
||||||
demarrage.
|
|
||||||
|
|
||||||
## 6. Mise a jour
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose pull
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
Les donnees (base PostgreSQL, images MinIO, configuration Brain) sont
|
|
||||||
stockees dans des volumes Docker et survivent aux mises a jour.
|
|
||||||
|
|
||||||
## 7. Sauvegarde
|
|
||||||
|
|
||||||
Les donnees sont reparties dans trois volumes Docker :
|
|
||||||
|
|
||||||
- `loremindmj_postgres-data` — ensemble des donnees applicatives (lores,
|
|
||||||
campagnes, pages, templates, branches narratives, etc.).
|
|
||||||
- `loremindmj_minio-data` — images uploadees.
|
|
||||||
- `loremindmj_brain-data` — parametres IA (fournisseur courant, cle API
|
|
||||||
1min.ai).
|
|
||||||
|
|
||||||
### Export SQL de la base
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose exec postgres pg_dump -U loremind loremind > backup.sql
|
|
||||||
```
|
|
||||||
|
|
||||||
### Sauvegarde complete des volumes
|
|
||||||
|
|
||||||
Arreter la stack au prealable afin de garantir la coherence des donnees :
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose stop
|
|
||||||
docker run --rm -v loremindmj_postgres-data:/data -v $(pwd):/backup alpine tar czf /backup/postgres-data.tar.gz -C /data .
|
|
||||||
docker run --rm -v loremindmj_minio-data:/data -v $(pwd):/backup alpine tar czf /backup/minio-data.tar.gz -C /data .
|
|
||||||
docker compose start
|
|
||||||
```
|
|
||||||
|
|
||||||
Sous Windows PowerShell, remplacer `$(pwd)` par `${PWD}`.
|
|
||||||
|
|
||||||
## 8. Resolution des problemes
|
|
||||||
|
|
||||||
### Port 8081 deja utilise
|
|
||||||
|
|
||||||
Modifier `WEB_PORT=8082` (ou toute autre valeur libre) dans `.env`, puis
|
|
||||||
relancer :
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
### Erreur "set POSTGRES_PASSWORD in .env" (ou variable equivalente) au lancement
|
|
||||||
|
|
||||||
Une des trois variables obligatoires de l'etape 3 est manquante. Verifier le
|
|
||||||
contenu du fichier `.env`.
|
|
||||||
|
|
||||||
### Popup "Ce site vous demande de vous connecter" sur l'ecran Parametres
|
|
||||||
|
|
||||||
Comportement attendu : il s'agit de l'authentification HTTP Basic. Utiliser
|
|
||||||
la valeur de `ADMIN_USERNAME` (par defaut `admin`) et celle de
|
|
||||||
`ADMIN_PASSWORD`.
|
|
||||||
|
|
||||||
### Erreurs `password authentication failed` en boucle dans les logs Postgres
|
|
||||||
|
|
||||||
Si la variable `POSTGRES_PASSWORD` a ete modifiee apres un premier lancement,
|
|
||||||
le volume Postgres conserve l'ancien mot de passe (initialise une seule fois).
|
|
||||||
Deux options :
|
|
||||||
|
|
||||||
- **Redemarrer avec un volume vierge** (entraine la perte des donnees) :
|
|
||||||
```
|
|
||||||
docker compose down -v
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
- **Modifier le mot de passe en base** sans toucher au volume :
|
|
||||||
```
|
|
||||||
docker compose exec postgres psql -U postgres
|
|
||||||
```
|
|
||||||
Puis dans le prompt `psql` :
|
|
||||||
```sql
|
|
||||||
ALTER USER loremind WITH PASSWORD 'valeur_exacte_du_env';
|
|
||||||
\q
|
|
||||||
```
|
|
||||||
Redemarrer ensuite le Core : `docker compose restart core`.
|
|
||||||
|
|
||||||
### Erreur "502 Bad Gateway" ou message d'erreur IA dans l'interface
|
|
||||||
|
|
||||||
Le service Brain ne parvient pas a contacter le fournisseur LLM. Verifier :
|
|
||||||
|
|
||||||
- **Ollama** : `ollama serve` est-il actif ? Le modele est-il telecharge
|
|
||||||
(`ollama list`) ? La valeur de `LLM_MODEL` correspond-elle exactement au
|
|
||||||
nom d'un modele liste ?
|
|
||||||
- **1min.ai** : la cle API est-elle valide ? Le modele existe-t-il ?
|
|
||||||
- Consulter les logs du Brain :
|
|
||||||
```
|
|
||||||
docker compose logs brain
|
|
||||||
```
|
|
||||||
|
|
||||||
### Un service ne demarre pas ou reste en etat `unhealthy`
|
|
||||||
|
|
||||||
Consulter les logs du service concerne :
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose logs <service>
|
|
||||||
```
|
|
||||||
|
|
||||||
Services disponibles : `postgres`, `minio`, `core`, `brain`, `web`.
|
|
||||||
|
|
||||||
### Redemarrage d'un service apres modification du `.env`
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose up -d <service>
|
|
||||||
```
|
|
||||||
|
|
||||||
Redemarrage complet : `docker compose restart`.
|
|
||||||
|
|
||||||
### Remise a zero complete (PERTE DES DONNEES)
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose down -v
|
|
||||||
```
|
|
||||||
|
|
||||||
L'option `-v` supprime les volumes. L'ensemble des lores, campagnes, images
|
|
||||||
et parametres est perdu de maniere definitive.
|
|
||||||
|
|
||||||
### "No such image" ou "pull access denied" au premier lancement
|
|
||||||
|
|
||||||
Le registry Gitea peut necessiter une authentification selon la visibilite
|
|
||||||
configuree pour les images. Contacter l'editeur du projet.
|
|
||||||
|
|
||||||
## 9. Exposition reseau des services
|
|
||||||
|
|
||||||
- **Interface web** : http://localhost:8081 (port configurable via
|
|
||||||
`WEB_PORT`).
|
|
||||||
- **PostgreSQL** : accessible uniquement via le reseau Docker interne, non
|
|
||||||
expose vers l'hote.
|
|
||||||
- **MinIO** : accessible uniquement via le reseau Docker interne. Les images
|
|
||||||
transitent par le reverse-proxy Java sur `/api/images/{id}/content`. Le
|
|
||||||
binding `127.0.0.1:9000/9001` defini dans `docker-compose.override.yml`
|
|
||||||
n'est actif qu'en developpement.
|
|
||||||
- **Brain Python** : accessible uniquement via le reseau Docker interne.
|
|
||||||
Toute requete doit porter l'en-tete `X-Internal-Secret`, injectee
|
|
||||||
automatiquement par le Core Java et jamais exposee au navigateur.
|
|
||||||
|
|
||||||
## 10. Desinstallation
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose down -v
|
|
||||||
docker image rm git.igmlcreation.fr/ietm64/core git.igmlcreation.fr/ietm64/brain git.igmlcreation.fr/ietm64/web
|
|
||||||
```
|
|
||||||
|
|
||||||
Supprimer ensuite le dossier contenant `docker-compose.yml` et `.env`.
|
|
||||||
70
README.md
70
README.md
@@ -1,69 +1,31 @@
|
|||||||
# LoreMind
|
# LoreMind
|
||||||
|
|
||||||
Application web d'aide aux Maîtres de Jeu (JDR) pour centraliser la gestion de l'univers (Lore) et le suivi des campagnes, avec un moteur IA intégré pour générer du contenu structuré.
|

|
||||||
|
|
||||||
|
Loremind est une application web angular auto-hébergable afin de venir en aide aux Maîtres de jeu qui souhaitent centraliser leur univers et leurs campagnes.
|
||||||
|
Cette dernière intègre un moteur IA qui va ingérer le contenu du lore et de la campagne afin de pouvoir répondre à des questions précises sur l'univers ou la campagne, mais également proposer des idées de création dans le contexte de la campagne et du lore.
|
||||||
|
Pour le moment seul Ollama est supporté pour la partie locale, il y-a également une intégration pour 1min.ai. Plus tard, d'autres moteurs seront supportés.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
La documentation complète est accessible sur le site [loremind-docs](https://loremind-docs.igmlcreation.fr/)
|
||||||
|
|
||||||
|
Pour l'installation, consultez le guide dans cette dernière .
|
||||||
|
|
||||||
## Fonctionnalités
|
## Fonctionnalités
|
||||||
|
|
||||||
- Gestion centralisée du Lore : Lieux, Factions, PNJ, et tous les éléments de votre univers
|
- Gestion centralisée du Lore : Lieux, Factions, PNJ, et tous les éléments de votre univers
|
||||||
- Suivi de campagnes : Sessions, actions des joueurs, chronologie
|
- Suivi de campagnes : Sessions, actions des joueurs, chronologie
|
||||||
- Moteur IA intégré : Génération automatique de contenu (PNJ, Villes, Quêtes) à partir de templates
|
- Moteur IA intégré : Génération automatique de contenu (PNJ, Villes, Quêtes) à partir de templates
|
||||||
- Export vers FoundryVTT : Transfert structuré des données vers votre VTT préféré (en développement)
|
|
||||||
|
|
||||||
## Captures d'écran
|
## Démo
|
||||||
|
|
||||||
### Page d'accueil
|
Une démo est disponible sur le site [loremind-demo](https://loremind-demo.igmlcreation.fr/)
|
||||||

|
|
||||||
|
|
||||||
### Recherche
|
!! Attention, la démo est uniquement accessible à 10 personnes à la fois (instances personnalisées). Cette limite est mise en place pour éviter l'overhead sur les ressources serveur.
|
||||||

|
|
||||||
|
|
||||||
## Stack Technologique
|
Cette dernière est utilisable 20 minutes maximum par session avant d'être réinitialiser.
|
||||||
|
Vous comprendrez également qu'elle ne contient pas de démo pour la partie IA, pour laquelle il faut configurer un serveur Ollama (et qui ferait donc exploser le serveur) ou utiliser 1min.ai.
|
||||||
LoreMind utilise une architecture distribuée pour séparer les responsabilités :
|
|
||||||
|
|
||||||
- **Frontend** : Angular (Interface utilisateur, affichage du lore, formulaires de templates)
|
|
||||||
- **Backend Core** : Java (Spring Boot) - Orchestration, persistance, export VTT
|
|
||||||
- **Backend IA** : Python - Traitement des LLM et génération de contenu
|
|
||||||
- **Base de données** : PostgreSQL avec JSONB pour les templates flexibles
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Backend Java (Domain-Driven Design & Hexagonal)
|
|
||||||
|
|
||||||
Le Backend Core respecte strictement :
|
|
||||||
- **Domain-Driven Design (DDD)** : Séparation en Bounded Contexts autonomes
|
|
||||||
- **Architecture Hexagonale (Ports et Adaptateurs)** : Domaine pur sans dépendances techniques
|
|
||||||
|
|
||||||
#### Bounded Contexts
|
|
||||||
- **LoreContext** : Gestion de l'encyclopédie de l'univers
|
|
||||||
- **CampaignContext** : Suivi des sessions et chronologie
|
|
||||||
- **GenerationContext** : Gestion des requêtes IA et templates
|
|
||||||
|
|
||||||
#### Couches
|
|
||||||
- **Domaine (Core)** : Entités métier pures et interfaces (Ports)
|
|
||||||
- **Application** : Orchestration des flux (Use Cases)
|
|
||||||
- **Infrastructure** : Implémentation technique (Adapters)
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
Pour installer LoreMind chez vous (Docker requis), suivez le guide **[INSTALL.md](INSTALL.md)** — 3 étapes, 5 minutes chrono :
|
|
||||||
|
|
||||||
1. Télécharger `docker-compose.yml` + `.env.example` depuis la [dernière release](https://git.igmlcreation.fr/ietm64/LoreMindMJ/releases)
|
|
||||||
2. Renommer `.env.example` → `.env` et changer `POSTGRES_PASSWORD`
|
|
||||||
3. `docker compose up -d` → ouvrir http://localhost:8081
|
|
||||||
|
|
||||||
Mise à jour : `docker compose pull && docker compose up -d`.
|
|
||||||
|
|
||||||
## Développement (contributeurs)
|
|
||||||
|
|
||||||
Pour builder les images localement depuis les sources :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone https://git.igmlcreation.fr/ietm64/LoreMindMJ.git
|
|
||||||
cd LoreMindMJ
|
|
||||||
# Créer un docker-compose.override.yml local (voir docs de contrib)
|
|
||||||
docker compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from app.domain.models import (
|
|||||||
ChatMessage,
|
ChatMessage,
|
||||||
ChapterSummary,
|
ChapterSummary,
|
||||||
CharacterSummary,
|
CharacterSummary,
|
||||||
|
NpcSummary,
|
||||||
GameSystemContext,
|
GameSystemContext,
|
||||||
LoreStructuralContext,
|
LoreStructuralContext,
|
||||||
NarrativeEntityContext,
|
NarrativeEntityContext,
|
||||||
@@ -198,10 +199,12 @@ class ChatUseCase:
|
|||||||
else "\n(Cette campagne n'est associée à aucun univers — tu peux proposer des éléments d'ambiance libres.)"
|
else "\n(Cette campagne n'est associée à aucun univers — tu peux proposer des éléments d'ambiance libres.)"
|
||||||
)
|
)
|
||||||
characters_block = ChatUseCase._format_characters(ctx.characters)
|
characters_block = ChatUseCase._format_characters(ctx.characters)
|
||||||
|
npcs_block = ChatUseCase._format_npcs(ctx.npcs)
|
||||||
return (
|
return (
|
||||||
"--- CAMPAGNE COURANTE ---\n"
|
"--- CAMPAGNE COURANTE ---\n"
|
||||||
f"Nom : {ctx.campaign_name}{desc}{lore_note}\n"
|
f"Nom : {ctx.campaign_name}{desc}{lore_note}\n"
|
||||||
f"{characters_block}\n"
|
f"{characters_block}"
|
||||||
|
f"{npcs_block}\n"
|
||||||
"Structure narrative (les flèches → indiquent des transitions de scène "
|
"Structure narrative (les flèches → indiquent des transitions de scène "
|
||||||
"déclenchées par un choix des joueurs) :\n"
|
"déclenchées par un choix des joueurs) :\n"
|
||||||
f"{arcs_block}"
|
f"{arcs_block}"
|
||||||
@@ -231,6 +234,33 @@ class ChatUseCase:
|
|||||||
)
|
)
|
||||||
return "\n".join(lines) + "\n"
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_npcs(npcs: list[NpcSummary]) -> str:
|
||||||
|
"""Bloc PNJ — symétrique aux PJ avec sa propre instruction anti-halluci.
|
||||||
|
|
||||||
|
Distinction importante : pour les PNJ, l'IA est ENCOURAGÉE à proposer de
|
||||||
|
nouveaux PNJ (création créative = OK). En revanche, elle ne doit pas
|
||||||
|
référencer comme existant un PNJ qui n'est pas dans la liste ci-dessous.
|
||||||
|
"""
|
||||||
|
if not npcs:
|
||||||
|
return (
|
||||||
|
"\nPersonnages non-joueurs (PNJ) : aucun défini pour l'instant. "
|
||||||
|
"Tu peux librement proposer de nouveaux PNJ au MJ, mais ne "
|
||||||
|
"fais pas comme s'ils existaient déjà dans la campagne.\n"
|
||||||
|
)
|
||||||
|
lines = ["\nPersonnages non-joueurs (PNJ) connus :"]
|
||||||
|
for n in npcs:
|
||||||
|
if n.snippet:
|
||||||
|
lines.append(f"- **{n.name}** — {n.snippet}")
|
||||||
|
else:
|
||||||
|
lines.append(f"- **{n.name}** (fiche vide)")
|
||||||
|
lines.append(
|
||||||
|
"Pour une fiche complète d'un PNJ existant (apparence, motivations), "
|
||||||
|
"n'invente rien : demande au MJ d'ouvrir l'éditeur du PNJ. Tu peux "
|
||||||
|
"en revanche proposer librement de NOUVEAUX PNJ."
|
||||||
|
)
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _format_arcs(arcs: list[ArcSummary]) -> str:
|
def _format_arcs(arcs: list[ArcSummary]) -> str:
|
||||||
if not arcs:
|
if not arcs:
|
||||||
@@ -319,7 +349,8 @@ class ChatUseCase:
|
|||||||
"arc": "ARC",
|
"arc": "ARC",
|
||||||
"chapter": "CHAPITRE",
|
"chapter": "CHAPITRE",
|
||||||
"scene": "SCÈNE",
|
"scene": "SCÈNE",
|
||||||
"character": "FICHE DE PERSONNAGE",
|
"character": "FICHE DE PERSONNAGE (PJ)",
|
||||||
|
"npc": "FICHE DE PNJ",
|
||||||
}.get(ne.entity_type.lower(), ne.entity_type.upper())
|
}.get(ne.entity_type.lower(), ne.entity_type.upper())
|
||||||
if ne.fields:
|
if ne.fields:
|
||||||
fields_block = "\n".join(
|
fields_block = "\n".join(
|
||||||
|
|||||||
@@ -170,6 +170,7 @@ class CampaignStructuralContext:
|
|||||||
campaign_description: str | None
|
campaign_description: str | None
|
||||||
arcs: list[ArcSummary]
|
arcs: list[ArcSummary]
|
||||||
characters: list["CharacterSummary"] = field(default_factory=list)
|
characters: list["CharacterSummary"] = field(default_factory=list)
|
||||||
|
npcs: list["NpcSummary"] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -185,6 +186,19 @@ class CharacterSummary:
|
|||||||
snippet: str
|
snippet: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class NpcSummary:
|
||||||
|
"""Résumé d'un PNJ : symétrique à CharacterSummary.
|
||||||
|
|
||||||
|
Permet à l'IA de connaître les PNJ d'une campagne (nom + snippet) sans
|
||||||
|
injecter leurs fiches complètes. Évolution prévue : entity_type="npc"
|
||||||
|
pour focus sur la fiche complète.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
snippet: str
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class NarrativeEntityContext:
|
class NarrativeEntityContext:
|
||||||
"""Contexte d'une entité narrative précise en cours d'édition.
|
"""Contexte d'une entité narrative précise en cours d'édition.
|
||||||
|
|||||||
@@ -61,7 +61,16 @@ class OllamaLLMProvider:
|
|||||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||||
try:
|
try:
|
||||||
response = await client.post(url, json=payload)
|
response = await client.post(url, json=payload)
|
||||||
response.raise_for_status()
|
if response.status_code >= 400:
|
||||||
|
body = response.text
|
||||||
|
try:
|
||||||
|
err_obj = json.loads(body)
|
||||||
|
err_msg = err_obj.get("error") or body
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
err_msg = body
|
||||||
|
raise LLMProviderError(
|
||||||
|
f"Ollama HTTP {response.status_code} : {err_msg.strip()[:500]}"
|
||||||
|
)
|
||||||
except httpx.HTTPError as exc:
|
except httpx.HTTPError as exc:
|
||||||
raise LLMProviderError(
|
raise LLMProviderError(
|
||||||
f"Erreur lors de l'appel à Ollama : {exc}"
|
f"Erreur lors de l'appel à Ollama : {exc}"
|
||||||
@@ -105,7 +114,20 @@ class OllamaLLMProvider:
|
|||||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||||
try:
|
try:
|
||||||
async with client.stream("POST", url, json=payload) as response:
|
async with client.stream("POST", url, json=payload) as response:
|
||||||
response.raise_for_status()
|
if response.status_code >= 400:
|
||||||
|
# On lit le body d'erreur pour le remonter a l'utilisateur,
|
||||||
|
# sinon on ne voit que "500 Internal Server Error" sans
|
||||||
|
# savoir POURQUOI Ollama refuse (modele introuvable, OOM,
|
||||||
|
# num_ctx trop grand pour la VRAM, etc.).
|
||||||
|
body = (await response.aread()).decode("utf-8", errors="replace")
|
||||||
|
try:
|
||||||
|
err_obj = json.loads(body)
|
||||||
|
err_msg = err_obj.get("error") or body
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
err_msg = body
|
||||||
|
raise LLMProviderError(
|
||||||
|
f"Ollama HTTP {response.status_code} : {err_msg.strip()[:500]}"
|
||||||
|
)
|
||||||
async for line in response.aiter_lines():
|
async for line in response.aiter_lines():
|
||||||
if not line.strip():
|
if not line.strip():
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ from app.domain.models import (
|
|||||||
CampaignStructuralContext,
|
CampaignStructuralContext,
|
||||||
ChapterSummary,
|
ChapterSummary,
|
||||||
CharacterSummary,
|
CharacterSummary,
|
||||||
|
NpcSummary,
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
GameSystemContext,
|
GameSystemContext,
|
||||||
LoreStructuralContext,
|
LoreStructuralContext,
|
||||||
@@ -205,6 +206,13 @@ class CharacterSummaryDTO(BaseModel):
|
|||||||
snippet: str = ""
|
snippet: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class NpcSummaryDTO(BaseModel):
|
||||||
|
"""Résumé d'un PNJ : symétrique à CharacterSummaryDTO."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
snippet: str = ""
|
||||||
|
|
||||||
|
|
||||||
class CampaignContextDTO(BaseModel):
|
class CampaignContextDTO(BaseModel):
|
||||||
"""Carte narrative enrichie : arcs → chapitres → scènes avec synopsis."""
|
"""Carte narrative enrichie : arcs → chapitres → scènes avec synopsis."""
|
||||||
|
|
||||||
@@ -212,12 +220,13 @@ class CampaignContextDTO(BaseModel):
|
|||||||
campaign_description: str | None = None
|
campaign_description: str | None = None
|
||||||
arcs: list[ArcSummaryDTO] = Field(default_factory=list)
|
arcs: list[ArcSummaryDTO] = Field(default_factory=list)
|
||||||
characters: list[CharacterSummaryDTO] = Field(default_factory=list)
|
characters: list[CharacterSummaryDTO] = Field(default_factory=list)
|
||||||
|
npcs: list[NpcSummaryDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
class NarrativeEntityDTO(BaseModel):
|
class NarrativeEntityDTO(BaseModel):
|
||||||
"""Entité narrative (arc/chapter/scene/character) en cours d'édition — focus optionnel."""
|
"""Entité narrative (arc/chapter/scene/character) en cours d'édition — focus optionnel."""
|
||||||
|
|
||||||
entity_type: str = Field(pattern="^(arc|chapter|scene|character)$")
|
entity_type: str = Field(pattern="^(arc|chapter|scene|character|npc)$")
|
||||||
title: str
|
title: str
|
||||||
fields: dict[str, str] = Field(default_factory=dict)
|
fields: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
@@ -553,11 +562,16 @@ def _to_campaign_context(dto: CampaignContextDTO | None) -> CampaignStructuralCo
|
|||||||
CharacterSummary(name=c.name, snippet=c.snippet)
|
CharacterSummary(name=c.name, snippet=c.snippet)
|
||||||
for c in dto.characters
|
for c in dto.characters
|
||||||
]
|
]
|
||||||
|
npcs = [
|
||||||
|
NpcSummary(name=n.name, snippet=n.snippet)
|
||||||
|
for n in dto.npcs
|
||||||
|
]
|
||||||
return CampaignStructuralContext(
|
return CampaignStructuralContext(
|
||||||
campaign_name=dto.campaign_name,
|
campaign_name=dto.campaign_name,
|
||||||
campaign_description=dto.campaign_description,
|
campaign_description=dto.campaign_description,
|
||||||
arcs=arcs,
|
arcs=arcs,
|
||||||
characters=characters,
|
characters=characters,
|
||||||
|
npcs=npcs,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -689,6 +703,76 @@ async def get_ollama_model_info(
|
|||||||
return OllamaModelInfoDTO(context_length=0)
|
return OllamaModelInfoDTO(context_length=0)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/models/ollama/pull")
|
||||||
|
async def pull_ollama_model(
|
||||||
|
body: dict[str, str],
|
||||||
|
settings: Annotated[Settings, Depends(get_settings)],
|
||||||
|
) -> StreamingResponse:
|
||||||
|
"""Telecharge un modele depuis Ollama et streame la progression.
|
||||||
|
|
||||||
|
Proxifie l'endpoint `/api/pull` d'Ollama qui renvoie du JSON ligne par
|
||||||
|
ligne (NDJSON) avec le statut de chaque etape : manifest, layers,
|
||||||
|
digest, success. On reemet ce flux tel quel au client (le front
|
||||||
|
parsera les lignes et affichera une barre de progression).
|
||||||
|
|
||||||
|
Le timeout est intentionnellement tres long (60 min) car certains
|
||||||
|
modeles font 30+ Go.
|
||||||
|
"""
|
||||||
|
name = (body.get("name") or "").strip()
|
||||||
|
if not name:
|
||||||
|
raise HTTPException(status_code=400, detail="name requis")
|
||||||
|
url = f"{settings.ollama_base_url}/api/pull"
|
||||||
|
|
||||||
|
async def stream() -> AsyncIterator[bytes]:
|
||||||
|
# On utilise un timeout long pour la lecture (60 min) mais court pour
|
||||||
|
# la connexion (10s) — si Ollama n'est pas joignable, on echoue vite.
|
||||||
|
timeout = httpx.Timeout(connect=10, read=3600, write=10, pool=10)
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||||
|
async with client.stream("POST", url, json={"model": name, "stream": True}) as r:
|
||||||
|
if r.status_code != 200:
|
||||||
|
# Ollama renvoie un message JSON d'erreur. On le passe
|
||||||
|
# tel quel au client en preservant le code HTTP.
|
||||||
|
body_text = await r.aread()
|
||||||
|
yield body_text
|
||||||
|
return
|
||||||
|
async for chunk in r.aiter_bytes():
|
||||||
|
yield chunk
|
||||||
|
except httpx.HTTPError as e:
|
||||||
|
# Erreur reseau : on emet une ligne JSON d'erreur compatible
|
||||||
|
# avec le format NDJSON d'Ollama.
|
||||||
|
err = json.dumps({"error": f"Connexion a Ollama impossible : {e}"}) + "\n"
|
||||||
|
yield err.encode("utf-8")
|
||||||
|
|
||||||
|
# application/x-ndjson : un objet JSON par ligne, pas de wrapping SSE.
|
||||||
|
# C'est le format natif d'Ollama, le front le parsera ligne par ligne.
|
||||||
|
return StreamingResponse(stream(), media_type="application/x-ndjson")
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/models/ollama/{name:path}")
|
||||||
|
async def delete_ollama_model(
|
||||||
|
name: str,
|
||||||
|
settings: Annotated[Settings, Depends(get_settings)],
|
||||||
|
) -> dict[str, str]:
|
||||||
|
"""Supprime un modele du serveur Ollama.
|
||||||
|
|
||||||
|
Le `:path` dans le pattern autorise les `:` du nom (ex: `gemma4:e4b`)
|
||||||
|
sans avoir besoin de URL-encoder cote client.
|
||||||
|
"""
|
||||||
|
if not name.strip():
|
||||||
|
raise HTTPException(status_code=400, detail="name requis")
|
||||||
|
url = f"{settings.ollama_base_url}/api/delete"
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=10) as client:
|
||||||
|
response = await client.request("DELETE", url, json={"model": name})
|
||||||
|
if response.status_code == 404:
|
||||||
|
raise HTTPException(status_code=404, detail=f"Modele '{name}' introuvable")
|
||||||
|
response.raise_for_status()
|
||||||
|
except httpx.HTTPError as e:
|
||||||
|
raise HTTPException(status_code=502, detail=f"Ollama injoignable : {e}")
|
||||||
|
return {"status": "deleted", "name": name}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/models/onemin")
|
@app.get("/models/onemin")
|
||||||
def list_onemin_models() -> dict[str, list[dict[str, object]]]:
|
def list_onemin_models() -> dict[str, list[dict[str, object]]]:
|
||||||
"""Catalogue statique des modeles 1min.ai, groupes par fournisseur.
|
"""Catalogue statique des modeles 1min.ai, groupes par fournisseur.
|
||||||
|
|||||||
15
core/pom.xml
15
core/pom.xml
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>0.6.6</version>
|
<version>0.8.0</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
@@ -83,6 +83,19 @@
|
|||||||
<artifactId>minio</artifactId>
|
<artifactId>minio</artifactId>
|
||||||
<version>8.5.11</version>
|
<version>8.5.11</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Nimbus JOSE+JWT — verification des JWT Ed25519 (EdDSA) emis par le relais
|
||||||
|
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle. -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.nimbusds</groupId>
|
||||||
|
<artifactId>nimbus-jose-jwt</artifactId>
|
||||||
|
<version>9.40</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.bouncycastle</groupId>
|
||||||
|
<artifactId>bcprov-jdk18on</artifactId>
|
||||||
|
<version>1.78.1</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -2,12 +2,14 @@ package com.loremind;
|
|||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Classe principale de l'application LoreMind.
|
* Classe principale de l'application LoreMind.
|
||||||
* Point d'entrée Spring Boot qui démarre l'application.
|
* Point d'entrée Spring Boot qui démarre l'application.
|
||||||
*/
|
*/
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
|
@EnableScheduling
|
||||||
public class LoreMindApplication {
|
public class LoreMindApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service d'application pour les fiches de PNJ (campagne).
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class NpcService {
|
||||||
|
|
||||||
|
private final NpcRepository npcRepository;
|
||||||
|
|
||||||
|
public NpcService(NpcRepository npcRepository) {
|
||||||
|
this.npcRepository = npcRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parameter Object pour la création / mise à jour d'un Npc.
|
||||||
|
* `order` est fourni par le controller ; si absent, le service le calcule.
|
||||||
|
*/
|
||||||
|
public record NpcData(String name, String markdownContent, String campaignId, Integer order) {}
|
||||||
|
|
||||||
|
public Npc createNpc(NpcData data) {
|
||||||
|
int order = data.order() != null
|
||||||
|
? data.order()
|
||||||
|
: nextOrderFor(data.campaignId());
|
||||||
|
Npc npc = Npc.builder()
|
||||||
|
.name(data.name())
|
||||||
|
.markdownContent(data.markdownContent())
|
||||||
|
.campaignId(data.campaignId())
|
||||||
|
.order(order)
|
||||||
|
.build();
|
||||||
|
return npcRepository.save(npc);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Npc> getNpcById(String id) {
|
||||||
|
return npcRepository.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Npc> getNpcsByCampaignId(String campaignId) {
|
||||||
|
return npcRepository.findByCampaignId(campaignId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Npc updateNpc(String id, NpcData data) {
|
||||||
|
Npc existing = npcRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Npc non trouvé avec l'ID: " + id));
|
||||||
|
existing.setName(data.name());
|
||||||
|
existing.setMarkdownContent(data.markdownContent());
|
||||||
|
if (data.order() != null) {
|
||||||
|
existing.setOrder(data.order());
|
||||||
|
}
|
||||||
|
return npcRepository.save(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteNpc(String id) {
|
||||||
|
npcRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Renvoie la prochaine position libre — append en fin de liste. */
|
||||||
|
private int nextOrderFor(String campaignId) {
|
||||||
|
return npcRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.mapToInt(Npc::getOrder)
|
||||||
|
.max()
|
||||||
|
.orElse(-1) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,17 +4,20 @@ import com.loremind.domain.campaigncontext.Arc;
|
|||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
import com.loremind.domain.campaigncontext.Character;
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
import com.loremind.domain.campaigncontext.Scene;
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummary;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.NpcSummary;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
@@ -42,21 +45,24 @@ public class CampaignStructuralContextBuilder {
|
|||||||
private final ChapterRepository chapterRepository;
|
private final ChapterRepository chapterRepository;
|
||||||
private final SceneRepository sceneRepository;
|
private final SceneRepository sceneRepository;
|
||||||
private final CharacterRepository characterRepository;
|
private final CharacterRepository characterRepository;
|
||||||
|
private final NpcRepository npcRepository;
|
||||||
|
|
||||||
public CampaignStructuralContextBuilder(
|
public CampaignStructuralContextBuilder(
|
||||||
CampaignRepository campaignRepository,
|
CampaignRepository campaignRepository,
|
||||||
ArcRepository arcRepository,
|
ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository,
|
SceneRepository sceneRepository,
|
||||||
CharacterRepository characterRepository) {
|
CharacterRepository characterRepository,
|
||||||
|
NpcRepository npcRepository) {
|
||||||
this.campaignRepository = campaignRepository;
|
this.campaignRepository = campaignRepository;
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
this.characterRepository = characterRepository;
|
this.characterRepository = characterRepository;
|
||||||
|
this.npcRepository = npcRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Longueur max du snippet de PJ injecté dans le contexte (coût tokens maîtrisé). */
|
/** Longueur max du snippet de PJ/PNJ injecté dans le contexte (coût tokens maîtrisé). */
|
||||||
private static final int CHARACTER_SNIPPET_MAX_LEN = 160;
|
private static final int CHARACTER_SNIPPET_MAX_LEN = 160;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -79,11 +85,17 @@ public class CampaignStructuralContextBuilder {
|
|||||||
.map(this::toCharacterSummary)
|
.map(this::toCharacterSummary)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
List<NpcSummary> npcs = npcRepository.findByCampaignId(campaignId).stream()
|
||||||
|
.sorted(Comparator.comparingInt(Npc::getOrder))
|
||||||
|
.map(this::toNpcSummary)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
return new CampaignStructuralContext(
|
return new CampaignStructuralContext(
|
||||||
campaign.getName(),
|
campaign.getName(),
|
||||||
campaign.getDescription(),
|
campaign.getDescription(),
|
||||||
arcs,
|
arcs,
|
||||||
characters);
|
characters,
|
||||||
|
npcs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -95,6 +107,11 @@ public class CampaignStructuralContextBuilder {
|
|||||||
return new CharacterSummary(c.getName(), extractSnippet(c.getMarkdownContent()));
|
return new CharacterSummary(c.getName(), extractSnippet(c.getMarkdownContent()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Symétrique à {@link #toCharacterSummary} pour les PNJ. */
|
||||||
|
private NpcSummary toNpcSummary(Npc n) {
|
||||||
|
return new NpcSummary(n.getName(), extractSnippet(n.getMarkdownContent()));
|
||||||
|
}
|
||||||
|
|
||||||
private static String extractSnippet(String markdown) {
|
private static String extractSnippet(String markdown) {
|
||||||
if (markdown == null || markdown.isBlank()) return "";
|
if (markdown == null || markdown.isBlank()) return "";
|
||||||
String firstLine = markdown.lines()
|
String firstLine = markdown.lines()
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ package com.loremind.application.generationcontext;
|
|||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
import com.loremind.domain.campaigncontext.Character;
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
import com.loremind.domain.campaigncontext.Scene;
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
@@ -29,22 +31,25 @@ public class NarrativeEntityContextBuilder {
|
|||||||
private final ChapterRepository chapterRepository;
|
private final ChapterRepository chapterRepository;
|
||||||
private final SceneRepository sceneRepository;
|
private final SceneRepository sceneRepository;
|
||||||
private final CharacterRepository characterRepository;
|
private final CharacterRepository characterRepository;
|
||||||
|
private final NpcRepository npcRepository;
|
||||||
|
|
||||||
public NarrativeEntityContextBuilder(
|
public NarrativeEntityContextBuilder(
|
||||||
ArcRepository arcRepository,
|
ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
SceneRepository sceneRepository,
|
SceneRepository sceneRepository,
|
||||||
CharacterRepository characterRepository) {
|
CharacterRepository characterRepository,
|
||||||
|
NpcRepository npcRepository) {
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
this.characterRepository = characterRepository;
|
this.characterRepository = characterRepository;
|
||||||
|
this.npcRepository = npcRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Charge l'entité narrative ciblée et la projette vers un VO du GenerationContext.
|
* Charge l'entité narrative ciblée et la projette vers un VO du GenerationContext.
|
||||||
*
|
*
|
||||||
* @param entityType "arc", "chapter", "scene" ou "character" (insensible à la casse)
|
* @param entityType "arc", "chapter", "scene", "character" ou "npc" (insensible à la casse)
|
||||||
* @param entityId l'ID de l'entité
|
* @param entityId l'ID de l'entité
|
||||||
* @throws IllegalArgumentException si le type est inconnu ou l'entité introuvable
|
* @throws IllegalArgumentException si le type est inconnu ou l'entité introuvable
|
||||||
*/
|
*/
|
||||||
@@ -55,6 +60,7 @@ public class NarrativeEntityContextBuilder {
|
|||||||
case "chapter" -> fromChapter(loadChapter(entityId));
|
case "chapter" -> fromChapter(loadChapter(entityId));
|
||||||
case "scene" -> fromScene(loadScene(entityId));
|
case "scene" -> fromScene(loadScene(entityId));
|
||||||
case "character" -> fromCharacter(loadCharacter(entityId));
|
case "character" -> fromCharacter(loadCharacter(entityId));
|
||||||
|
case "npc" -> fromNpc(loadNpc(entityId));
|
||||||
default -> throw new IllegalArgumentException("Type d'entité narrative inconnu: " + entityType);
|
default -> throw new IllegalArgumentException("Type d'entité narrative inconnu: " + entityType);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -81,6 +87,11 @@ public class NarrativeEntityContextBuilder {
|
|||||||
.orElseThrow(() -> new IllegalArgumentException("Personnage non trouvé: " + id));
|
.orElseThrow(() -> new IllegalArgumentException("Personnage non trouvé: " + id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Npc loadNpc(String id) {
|
||||||
|
return npcRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("PNJ non trouvé: " + id));
|
||||||
|
}
|
||||||
|
|
||||||
// --- Mapping entité → VO ------------------------------------------------
|
// --- Mapping entité → VO ------------------------------------------------
|
||||||
|
|
||||||
private NarrativeEntityContext fromArc(Arc a) {
|
private NarrativeEntityContext fromArc(Arc a) {
|
||||||
@@ -123,6 +134,12 @@ public class NarrativeEntityContextBuilder {
|
|||||||
return new NarrativeEntityContext("character", c.getName(), fields);
|
return new NarrativeEntityContext("character", c.getName(), fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private NarrativeEntityContext fromNpc(Npc n) {
|
||||||
|
Map<String, String> fields = new LinkedHashMap<>();
|
||||||
|
putField(fields, "fiche complète (markdown)", n.getMarkdownContent());
|
||||||
|
return new NarrativeEntityContext("npc", n.getName(), fields);
|
||||||
|
}
|
||||||
|
|
||||||
/** Null/blank devient chaîne vide — uniforme côté prompt, pas de NPE côté LLM. */
|
/** Null/blank devient chaîne vide — uniforme côté prompt, pas de NPE côté LLM. */
|
||||||
private static void putField(Map<String, String> target, String key, String value) {
|
private static void putField(Map<String, String> target, String key, String value) {
|
||||||
target.put(key, value == null ? "" : value);
|
target.put(key, value == null ? "" : value);
|
||||||
|
|||||||
@@ -0,0 +1,261 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
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) {
|
||||||
|
this.repository = repository;
|
||||||
|
this.jwtVerifier = jwtVerifier;
|
||||||
|
this.relay = relay;
|
||||||
|
this.gracePeriodSeconds = (long) gracePeriodDays * 86_400L;
|
||||||
|
this.refreshBeforeExpirySeconds = (long) refreshBeforeExpiryDays * 86_400L;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return true si le verifier est configure (cle publique presente).
|
||||||
|
* L'UI peut masquer toute la section Patreon si false.
|
||||||
|
*/
|
||||||
|
public boolean isLicensingEnabled() {
|
||||||
|
return 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() {
|
||||||
|
Optional<License> opt = repository.findCurrent();
|
||||||
|
if (opt.isEmpty()) return LicenseSnapshot.none();
|
||||||
|
return snapshotOf(opt.get(), Instant.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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").
|
||||||
|
*
|
||||||
|
* @return true si un refresh a ete tente (avec ou sans succes)
|
||||||
|
*/
|
||||||
|
public boolean refreshIfNeeded() {
|
||||||
|
Optional<License> opt = repository.findCurrent();
|
||||||
|
if (opt.isEmpty()) return false;
|
||||||
|
License current = opt.get();
|
||||||
|
Instant now = Instant.now();
|
||||||
|
long secondsUntilExpiry = Duration.between(now, current.getExpiresAt()).getSeconds();
|
||||||
|
if (secondsUntilExpiry > refreshBeforeExpirySeconds) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return doRefresh(current, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Force un refresh immediat (bouton UI "Reessayer maintenant").
|
||||||
|
*/
|
||||||
|
public boolean forceRefresh() {
|
||||||
|
return repository.findCurrent()
|
||||||
|
.map(license -> doRefresh(license, Instant.now()))
|
||||||
|
.orElse(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean 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());
|
||||||
|
return true;
|
||||||
|
} 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());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (JwtVerifier.JwtVerificationException e) {
|
||||||
|
current.setLastRefreshAttemptAt(now);
|
||||||
|
current.setLastRefreshSucceeded(false);
|
||||||
|
repository.save(current);
|
||||||
|
log.error("Relay returned a JWT that fails verification: {}", e.getMessage());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,9 +12,10 @@ import java.time.LocalDateTime;
|
|||||||
* backstory, équipement). Évolution prévue vers un système templaté par
|
* backstory, équipement). Évolution prévue vers un système templaté par
|
||||||
* GameSystem (la fiche Nimble n'a pas les mêmes champs qu'une fiche D&D).
|
* GameSystem (la fiche Nimble n'a pas les mêmes champs qu'une fiche D&D).
|
||||||
* <p>
|
* <p>
|
||||||
* Scope strict PJ : les PNJ restent dans le Lore (pages templatées) ou
|
* Scope strict PJ : les PNJ sont gérés par l'entité {@link Npc} dédiée
|
||||||
* dans les scènes elles-mêmes. Si le besoin de PNJ spécifiques à une
|
* (entité distincte plutôt qu'enum PJ/PNJ — invariants métier divergents).
|
||||||
* campagne remonte, on étendra l'entité (ex: type enum PJ/PNJ).
|
* Évolution prévue : système de templating partagé PJ/PNJ piloté par
|
||||||
|
* GameSystem pour adapter les blocs aux différents systèmes de JDR.
|
||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
@Builder
|
@Builder
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.loremind.domain.campaigncontext;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche de personnage non-joueur (PNJ) d'une campagne.
|
||||||
|
* <p>
|
||||||
|
* MVP : entité dédiée, distincte de {@link Character} (PJ). Choix DDD assumé —
|
||||||
|
* un PNJ a vocation à porter à terme des invariants métier propres (faction,
|
||||||
|
* statut vivant/mort/disparu, visibilité côté joueurs, relations inter-PNJ)
|
||||||
|
* qui n'ont aucun sens sur un PJ. Mutualiser via un enum aurait pollué l'entité
|
||||||
|
* PJ avec des champs inutiles ({@code if (type == NPC)} partout = anti-pattern).
|
||||||
|
* <p>
|
||||||
|
* Contenu markdown libre comme les PJ. Évolution prévue : templating partagé
|
||||||
|
* PJ/PNJ piloté par GameSystem.
|
||||||
|
* <p>
|
||||||
|
* Scope campagne : les PNJ "univers" (worldboss, figures du Lore) restent
|
||||||
|
* gérés via le système Page/Template du LoreContext.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class Npc {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** Contenu libre markdown — description, motivation, stats, notes MJ. Nullable à la création. */
|
||||||
|
private String markdownContent;
|
||||||
|
|
||||||
|
/** Référence vers la Campaign parente (cross-aggregate via ID, jamais d'objet). */
|
||||||
|
private String campaignId;
|
||||||
|
|
||||||
|
/** Ordre d'affichage dans la liste des PNJ de la campagne. */
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie pour la persistance des fiches de PNJ (campagne).
|
||||||
|
*/
|
||||||
|
public interface NpcRepository {
|
||||||
|
|
||||||
|
Npc save(Npc npc);
|
||||||
|
|
||||||
|
Optional<Npc> findById(String id);
|
||||||
|
|
||||||
|
List<Npc> findByCampaignId(String campaignId);
|
||||||
|
|
||||||
|
void deleteById(String id);
|
||||||
|
|
||||||
|
boolean existsById(String id);
|
||||||
|
}
|
||||||
@@ -22,12 +22,14 @@ import java.util.List;
|
|||||||
* Record Java : pur domaine, aucune dépendance technique.
|
* Record Java : pur domaine, aucune dépendance technique.
|
||||||
*
|
*
|
||||||
* @param characters Personnages joueurs (PJ) de la campagne. Vide si aucun.
|
* @param characters Personnages joueurs (PJ) de la campagne. Vide si aucun.
|
||||||
|
* @param npcs Personnages non-joueurs (PNJ) de la campagne. Vide si aucun.
|
||||||
*/
|
*/
|
||||||
public record CampaignStructuralContext(
|
public record CampaignStructuralContext(
|
||||||
String campaignName,
|
String campaignName,
|
||||||
String campaignDescription,
|
String campaignDescription,
|
||||||
List<ArcSummary> arcs,
|
List<ArcSummary> arcs,
|
||||||
List<CharacterSummary> characters) {
|
List<CharacterSummary> characters,
|
||||||
|
List<NpcSummary> npcs) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Résumé d'un PJ : nom + snippet court du markdown.
|
* Résumé d'un PJ : nom + snippet court du markdown.
|
||||||
@@ -39,6 +41,14 @@ public record CampaignStructuralContext(
|
|||||||
public record CharacterSummary(String name, String snippet) {
|
public record CharacterSummary(String name, String snippet) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résumé d'un PNJ : symétrique à {@link CharacterSummary}.
|
||||||
|
* Snippet court extrait du markdown — la fiche complète est réservée
|
||||||
|
* à un usage focus (à venir, entity_type="npc").
|
||||||
|
*/
|
||||||
|
public record NpcSummary(String name, String snippet) {
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Résumé d'un arc : nom + description courte + ses chapitres.
|
* Résumé d'un arc : nom + description courte + ses chapitres.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
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
|
||||||
|
) {}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
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
|
||||||
|
) {}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.generationcontext.CampaignStructuralContext.ArcSummar
|
|||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.BranchHint;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.ChapterSummary;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.CharacterSummary;
|
||||||
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.NpcSummary;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext.SceneSummary;
|
||||||
import com.loremind.domain.generationcontext.ChatMessage;
|
import com.loremind.domain.generationcontext.ChatMessage;
|
||||||
import com.loremind.domain.generationcontext.ChatRequest;
|
import com.loremind.domain.generationcontext.ChatRequest;
|
||||||
@@ -132,6 +133,12 @@ public class BrainChatPayloadBuilder {
|
|||||||
.map(this::characterSummaryToMap)
|
.map(this::characterSummaryToMap)
|
||||||
.collect(Collectors.toList()));
|
.collect(Collectors.toList()));
|
||||||
}
|
}
|
||||||
|
// Liste des PNJ : symétrique aux PJ, omise si vide pour alléger le payload.
|
||||||
|
if (ctx.npcs() != null && !ctx.npcs().isEmpty()) {
|
||||||
|
map.put("npcs", ctx.npcs().stream()
|
||||||
|
.map(this::npcSummaryToMap)
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
}
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,6 +151,15 @@ public class BrainChatPayloadBuilder {
|
|||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> npcSummaryToMap(NpcSummary n) {
|
||||||
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
|
map.put("name", n.name());
|
||||||
|
if (n.snippet() != null && !n.snippet().isBlank()) {
|
||||||
|
map.put("snippet", n.snippet());
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper générique pour sérialiser les entités structurelles (Arc/Chapter/Scene)
|
* Helper générique pour sérialiser les entités structurelles (Arc/Chapter/Scene)
|
||||||
* avec name, description et illustration_count conditionnel.
|
* avec name, description et illustration_count conditionnel.
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
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);
|
||||||
|
|
||||||
|
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") && root.get("auths").isObject()
|
||||||
|
? (ObjectNode) root.get("auths")
|
||||||
|
: root.putObject("auths");
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
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
|
||||||
|
.setConnectTimeout(Duration.ofSeconds(5))
|
||||||
|
.setReadTimeout(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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
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.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
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
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.ASN1Sequence;
|
||||||
|
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.util.Base64;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
||||||
|
if (publicKey == null) {
|
||||||
|
throw new JwtVerificationException("JWT verifier not configured");
|
||||||
|
}
|
||||||
|
if (rawJwt == null || rawJwt.isBlank()) {
|
||||||
|
throw new JwtVerificationException("JWT is empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
SignedJWT signed;
|
||||||
|
try {
|
||||||
|
signed = SignedJWT.parse(rawJwt);
|
||||||
|
} catch (ParseException e) {
|
||||||
|
throw new JwtVerificationException("JWT parse error: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
JWSAlgorithm alg = signed.getHeader().getAlgorithm();
|
||||||
|
if (!JWSAlgorithm.EdDSA.equals(alg)) {
|
||||||
|
throw new JwtVerificationException("Unexpected JWT algorithm: " + alg);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
JWTClaimsSet claims;
|
||||||
|
try {
|
||||||
|
claims = signed.getJWTClaimsSet();
|
||||||
|
} catch (ParseException e) {
|
||||||
|
throw new JwtVerificationException("JWT claims parse error", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!expectedIssuer.equals(claims.getIssuer())) {
|
||||||
|
throw new JwtVerificationException("JWT issuer mismatch: " + claims.getIssuer());
|
||||||
|
}
|
||||||
|
if (claims.getAudience() == null || !claims.getAudience().contains(expectedAudience)) {
|
||||||
|
throw new JwtVerificationException("JWT audience mismatch");
|
||||||
|
}
|
||||||
|
|
||||||
|
Date exp = claims.getExpirationTime();
|
||||||
|
Date iat = claims.getIssueTime();
|
||||||
|
String sub = claims.getSubject();
|
||||||
|
if (exp == null || iat == null || sub == null) {
|
||||||
|
throw new JwtVerificationException("JWT missing required claims");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note : on ne refuse pas un JWT expire ici. C'est au LicenseService
|
||||||
|
// de decider ce qu'il fait d'un JWT expire (grace period, refresh, etc.).
|
||||||
|
// La verification de signature reste valide tant que la cle existe.
|
||||||
|
|
||||||
|
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.toInstant(),
|
||||||
|
exp.toInstant()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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(ASN1Sequence.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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entité JPA pour les fiches de PNJ d'une campagne.
|
||||||
|
* Pas de FK physique vers campaigns (weak reference cross-agrégat intra-contexte).
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "npcs")
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class NpcJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(name = "markdown_content", columnDefinition = "TEXT")
|
||||||
|
private String markdownContent;
|
||||||
|
|
||||||
|
@Column(name = "campaign_id", nullable = false)
|
||||||
|
private Long campaignId;
|
||||||
|
|
||||||
|
@Column(name = "\"order\"", nullable = false)
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at", nullable = false)
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = LocalDateTime.now();
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
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> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.NpcJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface NpcJpaRepository extends JpaRepository<NpcJpaEntity, Long> {
|
||||||
|
|
||||||
|
List<NpcJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.NpcJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.NpcJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class PostgresNpcRepository implements NpcRepository {
|
||||||
|
|
||||||
|
private final NpcJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresNpcRepository(NpcJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Npc save(Npc npc) {
|
||||||
|
NpcJpaEntity entity = toJpaEntity(npc);
|
||||||
|
NpcJpaEntity saved = jpaRepository.save(entity);
|
||||||
|
return toDomainEntity(saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<Npc> findById(String id) {
|
||||||
|
return jpaRepository.findById(Long.parseLong(id)).map(this::toDomainEntity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Npc> findByCampaignId(String campaignId) {
|
||||||
|
return jpaRepository.findByCampaignIdOrderByOrderAsc(Long.parseLong(campaignId)).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteById(String id) {
|
||||||
|
jpaRepository.deleteById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean existsById(String id) {
|
||||||
|
return jpaRepository.existsById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Npc toDomainEntity(NpcJpaEntity e) {
|
||||||
|
return Npc.builder()
|
||||||
|
.id(e.getId().toString())
|
||||||
|
.name(e.getName())
|
||||||
|
.markdownContent(e.getMarkdownContent())
|
||||||
|
.campaignId(e.getCampaignId().toString())
|
||||||
|
.order(e.getOrder())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.updatedAt(e.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private NpcJpaEntity toJpaEntity(Npc n) {
|
||||||
|
Long id = n.getId() != null ? Long.parseLong(n.getId()) : null;
|
||||||
|
return NpcJpaEntity.builder()
|
||||||
|
.id(id)
|
||||||
|
.name(n.getName())
|
||||||
|
.markdownContent(n.getMarkdownContent())
|
||||||
|
.campaignId(Long.parseLong(n.getCampaignId()))
|
||||||
|
.order(n.getOrder())
|
||||||
|
.createdAt(n.getCreatedAt())
|
||||||
|
.updatedAt(n.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
package com.loremind.infrastructure.updates;
|
package com.loremind.infrastructure.updates;
|
||||||
|
|
||||||
|
import com.loremind.application.licensing.LicenseService;
|
||||||
|
import com.loremind.domain.licensing.LicenseSnapshot;
|
||||||
|
import com.loremind.domain.licensing.LicenseStatus;
|
||||||
|
import com.loremind.domain.licensing.RegistryCredentials;
|
||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -10,6 +14,7 @@ import org.springframework.http.HttpHeaders;
|
|||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.client.HttpClientErrorException;
|
import org.springframework.web.client.HttpClientErrorException;
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
@@ -19,9 +24,11 @@ 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.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,8 +39,13 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
* image suivie ({@code update-check.images}). On stocke ces digests comme
|
* image suivie ({@code update-check.images}). On stocke ces digests comme
|
||||||
* "baseline" (= ce que le conteneur en cours d'execution est cense faire
|
* "baseline" (= ce que le conteneur en cours d'execution est cense faire
|
||||||
* tourner, puisque le `docker compose pull` precede toujours `up -d`).
|
* tourner, puisque le `docker compose pull` precede toujours `up -d`).
|
||||||
|
* - Si l'init echoue (reseau Docker pas encore pret, registry transitoirement
|
||||||
|
* indisponible), un thread daemon de retry avec backoff complete les
|
||||||
|
* baselines manquantes en arriere-plan.
|
||||||
* - {@link #check()} re-interroge le registry et compare. Si un digest a
|
* - {@link #check()} re-interroge le registry et compare. Si un digest a
|
||||||
* change, une mise a jour est disponible.
|
* change, une mise a jour est disponible. Si la baseline manque (echec
|
||||||
|
* de tous les retries), retourne {@link ImageStatusKind#UNKNOWN} pour
|
||||||
|
* cette image — JAMAIS d'alignement silencieux (eviterait des MAJ ratees).
|
||||||
* - {@link #apply()} POST sur /v1/update de Watchtower (qui doit etre lance
|
* - {@link #apply()} POST sur /v1/update de Watchtower (qui doit etre lance
|
||||||
* avec WATCHTOWER_HTTP_API_UPDATE=true et le meme token).
|
* avec WATCHTOWER_HTTP_API_UPDATE=true et le meme token).
|
||||||
*
|
*
|
||||||
@@ -63,6 +75,9 @@ public class UpdateCheckService {
|
|||||||
private final String tag;
|
private final String tag;
|
||||||
private final String watchtowerUrl;
|
private final String watchtowerUrl;
|
||||||
private final String watchtowerToken;
|
private final String watchtowerToken;
|
||||||
|
private final List<String> betaImages;
|
||||||
|
private final String betaTag;
|
||||||
|
private final LicenseService licenseService;
|
||||||
|
|
||||||
private final Map<String, String> baselineDigests = new ConcurrentHashMap<>();
|
private final Map<String, String> baselineDigests = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
@@ -72,7 +87,10 @@ public class UpdateCheckService {
|
|||||||
@Value("${update-check.images:}") String imagesCsv,
|
@Value("${update-check.images:}") String imagesCsv,
|
||||||
@Value("${update-check.tag:latest}") String tag,
|
@Value("${update-check.tag:latest}") String tag,
|
||||||
@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("${licensing.beta.tag:latest}") String betaTag,
|
||||||
|
LicenseService licenseService) {
|
||||||
this.http = builder
|
this.http = builder
|
||||||
.setConnectTimeout(Duration.ofSeconds(5))
|
.setConnectTimeout(Duration.ofSeconds(5))
|
||||||
.setReadTimeout(Duration.ofSeconds(15))
|
.setReadTimeout(Duration.ofSeconds(15))
|
||||||
@@ -82,8 +100,14 @@ public class UpdateCheckService {
|
|||||||
this.tag = tag;
|
this.tag = tag;
|
||||||
this.watchtowerUrl = watchtowerUrl;
|
this.watchtowerUrl = watchtowerUrl;
|
||||||
this.watchtowerToken = watchtowerToken;
|
this.watchtowerToken = watchtowerToken;
|
||||||
|
this.betaImages = parseImages(betaImagesCsv);
|
||||||
|
this.betaTag = betaTag;
|
||||||
|
this.licenseService = licenseService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Backoff progressif (ms) pour retry de baseline en cas d'echec initial. */
|
||||||
|
private static final long[] BASELINE_RETRY_BACKOFFS_MS = {2_000, 5_000, 15_000, 30_000, 60_000};
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
void initBaseline() {
|
void initBaseline() {
|
||||||
if (!isEnabled()) {
|
if (!isEnabled()) {
|
||||||
@@ -91,7 +115,19 @@ public class UpdateCheckService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
log.info("Update check enabled - registry={} images={} tag={}", registry, images, tag);
|
log.info("Update check enabled - registry={} images={} tag={}", registry, images, tag);
|
||||||
|
boolean complete = tryBaselineMissing();
|
||||||
|
if (!complete) {
|
||||||
|
startBaselineRetryThread();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tente de poser la baseline pour les images qui ne l'ont pas encore.
|
||||||
|
* @return true si TOUTES les images ont leur baseline apres cet essai.
|
||||||
|
*/
|
||||||
|
private boolean tryBaselineMissing() {
|
||||||
for (String image : images) {
|
for (String image : images) {
|
||||||
|
if (baselineDigests.containsKey(image)) continue;
|
||||||
try {
|
try {
|
||||||
String digest = fetchRemoteDigest(image);
|
String digest = fetchRemoteDigest(image);
|
||||||
if (digest != null) {
|
if (digest != null) {
|
||||||
@@ -102,6 +138,33 @@ public class UpdateCheckService {
|
|||||||
log.warn("Cannot baseline digest for {}: {}", image, e.getMessage());
|
log.warn("Cannot baseline digest for {}: {}", image, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return baselineDigests.size() == images.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lance un thread daemon qui retente de poser les baselines manquantes
|
||||||
|
* avec backoff. Le thread s'arrete des que toutes les baselines sont
|
||||||
|
* posees, ou apres epuisement des backoffs (et alors {@link #check()}
|
||||||
|
* retournera UNKNOWN pour ces images jusqu'au prochain redemarrage).
|
||||||
|
*/
|
||||||
|
private void startBaselineRetryThread() {
|
||||||
|
Thread t = new Thread(() -> {
|
||||||
|
for (long backoff : BASELINE_RETRY_BACKOFFS_MS) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(backoff);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tryBaselineMissing()) {
|
||||||
|
log.info("Baseline complete after retry");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.warn("Baseline incomplete after all retries; check() will return UNKNOWN for missing images");
|
||||||
|
}, "update-baseline-retry");
|
||||||
|
t.setDaemon(true);
|
||||||
|
t.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isEnabled() {
|
public boolean isEnabled() {
|
||||||
@@ -110,10 +173,11 @@ public class UpdateCheckService {
|
|||||||
|
|
||||||
public UpdateStatus check() {
|
public UpdateStatus check() {
|
||||||
if (!isEnabled()) {
|
if (!isEnabled()) {
|
||||||
return new UpdateStatus(false, false, List.of(), Instant.now());
|
return new UpdateStatus(false, false, false, List.of(), Instant.now());
|
||||||
}
|
}
|
||||||
List<ImageStatus> statuses = new ArrayList<>();
|
List<ImageStatus> statuses = new ArrayList<>();
|
||||||
boolean anyUpdate = false;
|
boolean anyUpdate = false;
|
||||||
|
boolean anyUnknown = false;
|
||||||
for (String image : images) {
|
for (String image : images) {
|
||||||
String baseline = baselineDigests.get(image);
|
String baseline = baselineDigests.get(image);
|
||||||
String remote = null;
|
String remote = null;
|
||||||
@@ -122,17 +186,133 @@ public class UpdateCheckService {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Check failed for {}: {}", image, e.getMessage());
|
log.warn("Check failed for {}: {}", image, e.getMessage());
|
||||||
}
|
}
|
||||||
// Si on n'a pas de baseline (echec au boot), on l'aligne maintenant
|
// PAS d'alignement lazy si baseline absente : ce serait un faux negatif
|
||||||
// pour eviter un faux positif "MAJ dispo".
|
// silencieux. On reporte UNKNOWN pour que l'UI le signale.
|
||||||
if (baseline == null && remote != null) {
|
ImageStatusKind kind;
|
||||||
baselineDigests.put(image, remote);
|
if (baseline == null || remote == null) {
|
||||||
baseline = remote;
|
kind = ImageStatusKind.UNKNOWN;
|
||||||
|
anyUnknown = true;
|
||||||
|
} else if (baseline.equals(remote)) {
|
||||||
|
kind = ImageStatusKind.UP_TO_DATE;
|
||||||
|
} else {
|
||||||
|
kind = ImageStatusKind.UPDATE_AVAILABLE;
|
||||||
|
anyUpdate = true;
|
||||||
}
|
}
|
||||||
boolean updateAvailable = baseline != null && remote != null && !baseline.equals(remote);
|
statuses.add(new ImageStatus(image, baseline, remote, kind));
|
||||||
if (updateAvailable) anyUpdate = true;
|
}
|
||||||
statuses.add(new ImageStatus(image, baseline, remote, updateAvailable));
|
return new UpdateStatus(true, anyUpdate, anyUnknown, statuses, Instant.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifie l'etat du canal beta (images privees GHCR).
|
||||||
|
* Necessite licence valide/grace + toggle beta ON.
|
||||||
|
* Authentification basic auth via le PAT distribue par le relais.
|
||||||
|
*
|
||||||
|
* @return statut beta (peut etre {@link BetaStatus#disabled()} si licence absente,
|
||||||
|
* beta off ou licence expiree)
|
||||||
|
*/
|
||||||
|
public BetaStatus checkBeta() {
|
||||||
|
if (!licenseService.isLicensingEnabled()) {
|
||||||
|
return BetaStatus.disabled("licensing-not-configured");
|
||||||
|
}
|
||||||
|
LicenseSnapshot snap = licenseService.getCurrentSnapshot();
|
||||||
|
if (snap.status() != LicenseStatus.VALID && snap.status() != LicenseStatus.GRACE) {
|
||||||
|
return BetaStatus.disabled("license-" + snap.status().name().toLowerCase());
|
||||||
|
}
|
||||||
|
if (!snap.betaChannelEnabled()) {
|
||||||
|
return BetaStatus.disabled("beta-toggle-off");
|
||||||
|
}
|
||||||
|
if (betaImages.isEmpty()) {
|
||||||
|
return BetaStatus.disabled("no-beta-images-configured");
|
||||||
|
}
|
||||||
|
|
||||||
|
Optional<RegistryCredentials> creds = licenseService.fetchRegistryCredentials();
|
||||||
|
if (creds.isEmpty()) {
|
||||||
|
return new BetaStatus(true, false, true, List.of(), Instant.now(), "relay-unavailable");
|
||||||
|
}
|
||||||
|
|
||||||
|
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(
|
||||||
|
(creds.get().username() + ":" + creds.get().password()).getBytes(StandardCharsets.UTF_8));
|
||||||
|
String betaRegistry = normalizeRegistry(creds.get().registry());
|
||||||
|
|
||||||
|
List<ImageStatus> statuses = new ArrayList<>();
|
||||||
|
boolean anyUpdate = false;
|
||||||
|
boolean anyUnknown = false;
|
||||||
|
for (String image : betaImages) {
|
||||||
|
String remote = null;
|
||||||
|
try {
|
||||||
|
remote = fetchRemoteDigestAuth(betaRegistry, image, betaTag, basicAuth);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Beta check failed for {}: {}", image, e.getMessage());
|
||||||
|
}
|
||||||
|
// Pas de baseline pour la beta : on ne peut pas dire "a jour" car on
|
||||||
|
// ne sait pas quelle version le user fait tourner. On expose juste le
|
||||||
|
// digest remote ; l'UI affichera "version disponible : <tag>" sans
|
||||||
|
// comparaison locale tant qu'il n'y a pas un mecanisme de baseline.
|
||||||
|
ImageStatusKind kind = (remote == null) ? ImageStatusKind.UNKNOWN : ImageStatusKind.UPDATE_AVAILABLE;
|
||||||
|
if (kind == ImageStatusKind.UNKNOWN) anyUnknown = true;
|
||||||
|
else anyUpdate = true;
|
||||||
|
statuses.add(new ImageStatus(image, null, remote, kind));
|
||||||
|
}
|
||||||
|
return new BetaStatus(true, anyUpdate, anyUnknown, statuses, Instant.now(), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String fetchRemoteDigestAuth(String registryUrl, String image, String tagName, String authHeader) {
|
||||||
|
String url = registryUrl + "/v2/" + image + "/manifests/" + tagName;
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setAccept(MANIFEST_ACCEPT);
|
||||||
|
headers.set(HttpHeaders.AUTHORIZATION, authHeader);
|
||||||
|
try {
|
||||||
|
return digestCall(url, headers);
|
||||||
|
} catch (HttpClientErrorException.Unauthorized e) {
|
||||||
|
// GHCR peut exiger d'echanger basic auth contre un bearer token via
|
||||||
|
// le challenge WWW-Authenticate. On reuse la logique existante en
|
||||||
|
// ajoutant l'auth header a la requete /token.
|
||||||
|
String www = e.getResponseHeaders() == null ? null
|
||||||
|
: e.getResponseHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE);
|
||||||
|
String token = obtainBearerTokenWithAuth(www, authHeader);
|
||||||
|
if (token == null) return null;
|
||||||
|
HttpHeaders bearerHeaders = new HttpHeaders();
|
||||||
|
bearerHeaders.setAccept(MANIFEST_ACCEPT);
|
||||||
|
bearerHeaders.setBearerAuth(token);
|
||||||
|
return digestCall(url, bearerHeaders);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("rawtypes")
|
||||||
|
private String obtainBearerTokenWithAuth(@Nullable String wwwAuth, String authHeader) {
|
||||||
|
if (wwwAuth == null) return null;
|
||||||
|
String prefix = "Bearer ";
|
||||||
|
if (!wwwAuth.regionMatches(true, 0, prefix, 0, prefix.length())) return null;
|
||||||
|
Map<String, String> params = parseAuthParams(wwwAuth.substring(prefix.length()));
|
||||||
|
String realm = params.get("realm");
|
||||||
|
if (realm == null) return null;
|
||||||
|
StringBuilder url = new StringBuilder(realm);
|
||||||
|
boolean hasQuery = realm.contains("?");
|
||||||
|
for (String key : new String[]{"service", "scope"}) {
|
||||||
|
String v = params.get(key);
|
||||||
|
if (v != null) {
|
||||||
|
String encoded = URLEncoder.encode(v, StandardCharsets.UTF_8)
|
||||||
|
.replace("%3A", ":")
|
||||||
|
.replace("%2F", "/");
|
||||||
|
url.append(hasQuery ? '&' : '?').append(key).append('=').append(encoded);
|
||||||
|
hasQuery = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.set(HttpHeaders.AUTHORIZATION, authHeader);
|
||||||
|
ResponseEntity<Map> resp = http.exchange(url.toString(), HttpMethod.GET,
|
||||||
|
new HttpEntity<>(headers), Map.class);
|
||||||
|
Map<?, ?> body = resp.getBody();
|
||||||
|
if (body == null) return null;
|
||||||
|
Object t = body.get("token");
|
||||||
|
if (t == null) t = body.get("access_token");
|
||||||
|
return t == null ? null : t.toString();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Beta bearer token request failed: {}", e.getMessage());
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
return new UpdateStatus(true, anyUpdate, statuses, Instant.now());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void apply() {
|
public void apply() {
|
||||||
@@ -198,9 +378,18 @@ public class UpdateCheckService {
|
|||||||
for (String key : new String[]{"service", "scope"}) {
|
for (String key : new String[]{"service", "scope"}) {
|
||||||
String v = params.get(key);
|
String v = params.get(key);
|
||||||
if (v != null) {
|
if (v != null) {
|
||||||
|
// URLEncoder fait du "form encoding" qui transforme `:` et `/`
|
||||||
|
// en %3A et %2F. La plupart des registries (Docker Hub, Gitea)
|
||||||
|
// acceptent les deux, mais GHCR est strict et rejette le scope
|
||||||
|
// encode (403 DENIED). On preserve donc `:` et `/` dans la
|
||||||
|
// valeur, conformement a ce que GHCR attend
|
||||||
|
// (et que docker pull lui-meme envoie).
|
||||||
|
String encoded = URLEncoder.encode(v, StandardCharsets.UTF_8)
|
||||||
|
.replace("%3A", ":")
|
||||||
|
.replace("%2F", "/");
|
||||||
url.append(hasQuery ? '&' : '?')
|
url.append(hasQuery ? '&' : '?')
|
||||||
.append(key).append('=')
|
.append(key).append('=')
|
||||||
.append(URLEncoder.encode(v, StandardCharsets.UTF_8));
|
.append(encoded);
|
||||||
hasQuery = true;
|
hasQuery = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -269,15 +458,61 @@ public class UpdateCheckService {
|
|||||||
// Records de retour (sortis sous forme JSON par Jackson)
|
// Records de retour (sortis sous forme JSON par Jackson)
|
||||||
// -----------------------------------------------------------------------
|
// -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Etat tri-state d'une image vis-a-vis du registry.
|
||||||
|
* <ul>
|
||||||
|
* <li>{@link #UP_TO_DATE} : digest local == digest remote.</li>
|
||||||
|
* <li>{@link #UPDATE_AVAILABLE} : digests differents, MAJ disponible.</li>
|
||||||
|
* <li>{@link #UNKNOWN} : impossible de comparer (baseline ou remote manquant).
|
||||||
|
* L'UI doit afficher un avertissement plutot que de declarer "a jour".</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public enum ImageStatusKind { UP_TO_DATE, UPDATE_AVAILABLE, UNKNOWN }
|
||||||
|
|
||||||
public record UpdateStatus(
|
public record UpdateStatus(
|
||||||
boolean enabled,
|
boolean enabled,
|
||||||
boolean updateAvailable,
|
boolean updateAvailable,
|
||||||
|
boolean anyUnknown,
|
||||||
List<ImageStatus> images,
|
List<ImageStatus> images,
|
||||||
Instant checkedAt) {}
|
Instant checkedAt) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Etat du canal beta.
|
||||||
|
* <ul>
|
||||||
|
* <li>{@code enabled} : true si le canal beta est actif et la licence valide.</li>
|
||||||
|
* <li>{@code disabledReason} : si {@code enabled=false}, raison technique
|
||||||
|
* (licensing-not-configured, license-none, license-expired, beta-toggle-off,
|
||||||
|
* no-beta-images-configured, relay-unavailable). Permet a l'UI d'afficher
|
||||||
|
* un message contextuel.</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public record BetaStatus(
|
||||||
|
boolean enabled,
|
||||||
|
boolean updateAvailable,
|
||||||
|
boolean anyUnknown,
|
||||||
|
List<ImageStatus> images,
|
||||||
|
Instant checkedAt,
|
||||||
|
String disabledReason) {
|
||||||
|
|
||||||
|
public static BetaStatus disabled(String reason) {
|
||||||
|
return new BetaStatus(false, false, false, List.of(), Instant.now(), reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Le champ {@code updateAvailable} est conserve pour la compatibilite
|
||||||
|
* avec les anciens clients ; il est strictement derive de {@code status}
|
||||||
|
* dans le constructeur compact.
|
||||||
|
*/
|
||||||
public record ImageStatus(
|
public record ImageStatus(
|
||||||
String image,
|
String image,
|
||||||
String localDigest,
|
String localDigest,
|
||||||
String remoteDigest,
|
String remoteDigest,
|
||||||
boolean updateAvailable) {}
|
ImageStatusKind status,
|
||||||
|
boolean updateAvailable) {
|
||||||
|
|
||||||
|
public ImageStatus(String image, String localDigest, String remoteDigest, ImageStatusKind status) {
|
||||||
|
this(image, localDigest, remoteDigest, status, status == ImageStatusKind.UPDATE_AVAILABLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ public class SecurityConfig {
|
|||||||
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
||||||
.requestMatchers("/api/settings/**").hasRole("ADMIN")
|
.requestMatchers("/api/settings/**").hasRole("ADMIN")
|
||||||
.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
||||||
|
.requestMatchers("/api/license/**").hasRole("ADMIN")
|
||||||
.anyRequest().permitAll()
|
.anyRequest().permitAll()
|
||||||
)
|
)
|
||||||
.httpBasic(basic -> {});
|
.httpBasic(basic -> {});
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
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.LicenseStatusDTO;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
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 {
|
||||||
|
|
||||||
|
private final LicenseService licenseService;
|
||||||
|
|
||||||
|
public LicenseController(LicenseService licenseService) {
|
||||||
|
this.licenseService = licenseService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@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<?> install(@RequestBody InstallRequest request) {
|
||||||
|
if (request == null || request.jwt() == null || request.jwt().isBlank()) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("error", "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", 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<?> setBetaChannel(@RequestBody BetaChannelRequest request) {
|
||||||
|
if (request == null) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("error", "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", e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record InstallRequest(String jwt) {}
|
||||||
|
public record BetaChannelRequest(boolean enabled) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.campaigncontext.NpcService;
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||||
|
import com.loremind.infrastructure.web.mapper.NpcMapper;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/npcs")
|
||||||
|
public class NpcController {
|
||||||
|
|
||||||
|
private final NpcService npcService;
|
||||||
|
private final NpcMapper npcMapper;
|
||||||
|
|
||||||
|
public NpcController(NpcService npcService, NpcMapper npcMapper) {
|
||||||
|
this.npcService = npcService;
|
||||||
|
this.npcMapper = npcMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<NpcDTO> createNpc(@RequestBody NpcDTO dto) {
|
||||||
|
Npc created = npcService.createNpc(
|
||||||
|
new NpcService.NpcData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), null)
|
||||||
|
);
|
||||||
|
return ResponseEntity.ok(npcMapper.toDTO(created));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<NpcDTO> getNpcById(@PathVariable String id) {
|
||||||
|
return npcService.getNpcById(id)
|
||||||
|
.map(n -> ResponseEntity.ok(npcMapper.toDTO(n)))
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/campaign/{campaignId}")
|
||||||
|
public ResponseEntity<List<NpcDTO>> getNpcsByCampaign(@PathVariable String campaignId) {
|
||||||
|
List<NpcDTO> dtos = npcService.getNpcsByCampaignId(campaignId).stream()
|
||||||
|
.map(npcMapper::toDTO)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return ResponseEntity.ok(dtos);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ResponseEntity<NpcDTO> updateNpc(@PathVariable String id, @RequestBody NpcDTO dto) {
|
||||||
|
Npc updated = npcService.updateNpc(
|
||||||
|
id,
|
||||||
|
new NpcService.NpcData(dto.getName(), dto.getMarkdownContent(), dto.getCampaignId(), dto.getOrder())
|
||||||
|
);
|
||||||
|
return ResponseEntity.ok(npcMapper.toDTO(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ResponseEntity<Void> deleteNpc(@PathVariable String id) {
|
||||||
|
npcService.deleteNpc(id);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,9 @@ import org.springframework.http.HttpMethod;
|
|||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
@@ -15,7 +17,15 @@ 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.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,13 +44,16 @@ public class SettingsController {
|
|||||||
|
|
||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
private final String brainBaseUrl;
|
private final String brainBaseUrl;
|
||||||
|
private final String brainInternalSecret;
|
||||||
private final boolean demoMode;
|
private final boolean demoMode;
|
||||||
|
|
||||||
public SettingsController(RestTemplate restTemplate,
|
public SettingsController(RestTemplate restTemplate,
|
||||||
@Value("${brain.base-url}") String brainBaseUrl,
|
@Value("${brain.base-url}") String brainBaseUrl,
|
||||||
|
@Value("${brain.internal-secret}") String brainInternalSecret,
|
||||||
@Value("${app.demo-mode:false}") boolean demoMode) {
|
@Value("${app.demo-mode:false}") boolean demoMode) {
|
||||||
this.restTemplate = restTemplate;
|
this.restTemplate = restTemplate;
|
||||||
this.brainBaseUrl = brainBaseUrl;
|
this.brainBaseUrl = brainBaseUrl;
|
||||||
|
this.brainInternalSecret = brainInternalSecret;
|
||||||
this.demoMode = demoMode;
|
this.demoMode = demoMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,11 +79,92 @@ public class SettingsController {
|
|||||||
return forward(HttpMethod.POST, "/models/ollama/info", body);
|
return forward(HttpMethod.POST, "/models/ollama/info", body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Telecharge un modele Ollama et streame la progression au client.
|
||||||
|
* <p>
|
||||||
|
* On bypass RestTemplate (qui bufferise toute la reponse) au profit du
|
||||||
|
* client HTTP standard de Java en mode streaming. Le Brain renvoie du
|
||||||
|
* NDJSON ligne par ligne ; on relaie chaque chunk tel quel pour que le
|
||||||
|
* frontend voie la progression en temps reel.
|
||||||
|
*/
|
||||||
|
@PostMapping(value = "/models/ollama/pull", produces = "application/x-ndjson")
|
||||||
|
public ResponseEntity<StreamingResponseBody> pullOllamaModel(@RequestBody Map<String, Object> body) {
|
||||||
|
guardDemoMode();
|
||||||
|
StreamingResponseBody stream = output -> {
|
||||||
|
// Force HTTP/1.1 : le HttpClient JDK essaie HTTP/2 par defaut,
|
||||||
|
// mais uvicorn (Brain) ne supporte que HTTP/1.1 et rejette la
|
||||||
|
// tentative d'upgrade ("Unsupported upgrade request") -> la
|
||||||
|
// requete n'arrive jamais a notre endpoint Python.
|
||||||
|
HttpClient http = HttpClient.newBuilder()
|
||||||
|
.version(HttpClient.Version.HTTP_1_1)
|
||||||
|
.connectTimeout(Duration.ofSeconds(10))
|
||||||
|
.build();
|
||||||
|
// Le RestTemplate auto-injecte X-Internal-Secret via un interceptor,
|
||||||
|
// mais on bypass RestTemplate pour le streaming -> on doit ajouter
|
||||||
|
// l'entete a la main, sinon le Brain repond 401.
|
||||||
|
HttpRequest.Builder reqBuilder = HttpRequest.newBuilder()
|
||||||
|
.uri(URI.create(brainBaseUrl + "/models/ollama/pull"))
|
||||||
|
.timeout(Duration.ofMinutes(60))
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(toJson(body)));
|
||||||
|
if (brainInternalSecret != null && !brainInternalSecret.isBlank()) {
|
||||||
|
reqBuilder.header("X-Internal-Secret", brainInternalSecret);
|
||||||
|
}
|
||||||
|
HttpRequest req = reqBuilder.build();
|
||||||
|
try {
|
||||||
|
HttpResponse<InputStream> resp = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
|
||||||
|
try (InputStream in = resp.body()) {
|
||||||
|
byte[] buf = new byte[4096];
|
||||||
|
int n;
|
||||||
|
while ((n = in.read(buf)) != -1) {
|
||||||
|
output.write(buf, 0, n);
|
||||||
|
output.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new IOException("Pull interrompu", ie);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/x-ndjson")).body(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/models/ollama/{name}")
|
||||||
|
public ResponseEntity<Map<String, Object>> deleteOllamaModel(@PathVariable("name") String name) {
|
||||||
|
guardDemoMode();
|
||||||
|
return forward(HttpMethod.DELETE, "/models/ollama/" + name, null);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/models/onemin")
|
@GetMapping("/models/onemin")
|
||||||
public ResponseEntity<Map<String, Object>> listOneMinModels() {
|
public ResponseEntity<Map<String, Object>> listOneMinModels() {
|
||||||
return forward(HttpMethod.GET, "/models/onemin", null);
|
return forward(HttpMethod.GET, "/models/onemin", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serialiseur JSON minimal pour eviter d'instancier ObjectMapper a chaque
|
||||||
|
* appel. Suffisant pour notre cas d'usage : Map<String,Object> avec des
|
||||||
|
* String/Number/Boolean en valeur.
|
||||||
|
*/
|
||||||
|
private static String toJson(Map<String, Object> m) {
|
||||||
|
StringBuilder sb = new StringBuilder("{");
|
||||||
|
boolean first = true;
|
||||||
|
for (Map.Entry<String, Object> e : m.entrySet()) {
|
||||||
|
if (!first) sb.append(",");
|
||||||
|
sb.append("\"").append(escape(e.getKey())).append("\":");
|
||||||
|
Object v = e.getValue();
|
||||||
|
if (v == null) sb.append("null");
|
||||||
|
else if (v instanceof Number || v instanceof Boolean) sb.append(v);
|
||||||
|
else sb.append("\"").append(escape(v.toString())).append("\"");
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
return sb.append("}").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String escape(String s) {
|
||||||
|
return s.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||||
|
.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
|
||||||
|
}
|
||||||
|
|
||||||
private void guardDemoMode() {
|
private void guardDemoMode() {
|
||||||
if (demoMode) {
|
if (demoMode) {
|
||||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Settings disabled in demo mode");
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Settings disabled in demo mode");
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.infrastructure.web.controller;
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
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.UpdateStatus;
|
import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -44,6 +45,12 @@ public class UpdatesController {
|
|||||||
return updates.check();
|
return updates.check();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/check-beta")
|
||||||
|
public BetaStatus checkBeta() {
|
||||||
|
guardDemoMode();
|
||||||
|
return updates.checkBeta();
|
||||||
|
}
|
||||||
|
|
||||||
@PostMapping("/apply")
|
@PostMapping("/apply")
|
||||||
public ResponseEntity<Map<String, Object>> apply() {
|
public ResponseEntity<Map<String, Object>> apply() {
|
||||||
guardDemoMode();
|
guardDemoMode();
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.loremind.infrastructure.web.dto.campaigncontext;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DTO pour les fiches de PNJ d'une campagne.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class NpcDTO {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
private String markdownContent;
|
||||||
|
private String campaignId;
|
||||||
|
private int order;
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.infrastructure.web.mapper;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class NpcMapper {
|
||||||
|
|
||||||
|
public NpcDTO toDTO(Npc n) {
|
||||||
|
if (n == null) return null;
|
||||||
|
NpcDTO dto = new NpcDTO();
|
||||||
|
dto.setId(n.getId());
|
||||||
|
dto.setName(n.getName());
|
||||||
|
dto.setMarkdownContent(n.getMarkdownContent());
|
||||||
|
dto.setCampaignId(n.getCampaignId());
|
||||||
|
dto.setOrder(n.getOrder());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Npc toDomain(NpcDTO dto) {
|
||||||
|
if (dto == null) return null;
|
||||||
|
return Npc.builder()
|
||||||
|
.id(dto.getId())
|
||||||
|
.name(dto.getName())
|
||||||
|
.markdownContent(dto.getMarkdownContent())
|
||||||
|
.campaignId(dto.getCampaignId())
|
||||||
|
.order(dto.getOrder())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,12 @@ server.port=8080
|
|||||||
# de WebFlux (utilisé uniquement pour WebClient côté adapter SSE vers le Brain).
|
# de WebFlux (utilisé uniquement pour WebClient côté adapter SSE vers le Brain).
|
||||||
spring.main.web-application-type=servlet
|
spring.main.web-application-type=servlet
|
||||||
|
|
||||||
|
# Pas de timeout sur les requetes async (StreamingResponseBody, SSE).
|
||||||
|
# Le defaut Tomcat coupe a 30s, ce qui interrompt le streaming d'un pull
|
||||||
|
# de modele Ollama (peut durer des dizaines de minutes pour un GGUF de 10+ Go).
|
||||||
|
# -1 = pas de timeout, on s'appuie sur la fermeture cote client ou cote upstream.
|
||||||
|
spring.mvc.async.request-timeout=-1
|
||||||
|
|
||||||
# Configuration de la base de donnees PostgreSQL
|
# Configuration de la base de donnees PostgreSQL
|
||||||
# Valeurs surchargeables via variables d'env (cf. docker-compose.yml).
|
# Valeurs surchargeables via variables d'env (cf. docker-compose.yml).
|
||||||
# En dev local, creez un fichier .env a la racine de core/ OU definissez les
|
# En dev local, creez un fichier .env a la racine de core/ OU definissez les
|
||||||
@@ -62,3 +68,38 @@ update-check.images=${UPDATE_CHECK_IMAGES:}
|
|||||||
update-check.tag=${UPDATE_CHECK_TAG:latest}
|
update-check.tag=${UPDATE_CHECK_TAG:latest}
|
||||||
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:}
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Licensing (canal beta gate par Patreon)
|
||||||
|
# ============================================================================
|
||||||
|
# URL du relais OAuth Patreon (Cloudflare Workers). En prod : valeur par defaut.
|
||||||
|
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}
|
||||||
|
licensing.beta.tag=${LICENSING_BETA_TAG:latest}
|
||||||
|
|
||||||
|
# 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}
|
||||||
|
|||||||
29
core/src/main/resources/licensing/README.md
Normal file
29
core/src/main/resources/licensing/README.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# 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)
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test unitaire pour NpcService.
|
||||||
|
* Couvre la création (avec auto-calcul de l'order), la lecture, la mise à jour
|
||||||
|
* (incl. cas non trouvé), la suppression, et le calcul d'order.
|
||||||
|
*/
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class NpcServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private NpcRepository npcRepository;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private NpcService npcService;
|
||||||
|
|
||||||
|
private Npc testNpc;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
testNpc = Npc.builder()
|
||||||
|
.id("npc-1")
|
||||||
|
.name("Borin le forgeron")
|
||||||
|
.markdownContent("# Borin\nForgeron nain")
|
||||||
|
.campaignId("camp-1")
|
||||||
|
.order(1)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCreateNpc_WithExplicitOrder() {
|
||||||
|
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||||
|
|
||||||
|
Npc result = npcService.createNpc(
|
||||||
|
new NpcService.NpcData("Borin le forgeron", "# Borin", "camp-1", 5));
|
||||||
|
|
||||||
|
assertNotNull(result);
|
||||||
|
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||||
|
verify(npcRepository).save(captor.capture());
|
||||||
|
assertEquals(5, captor.getValue().getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCreateNpc_AutoComputesNextOrder_WhenNullProvided() {
|
||||||
|
// Existant : 2 PNJ avec orders 0 et 3 → next = 4
|
||||||
|
Npc a = Npc.builder().id("a").campaignId("camp-1").order(0).build();
|
||||||
|
Npc b = Npc.builder().id("b").campaignId("camp-1").order(3).build();
|
||||||
|
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of(a, b));
|
||||||
|
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||||
|
|
||||||
|
npcService.createNpc(new NpcService.NpcData("Nouveau", null, "camp-1", null));
|
||||||
|
|
||||||
|
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||||
|
verify(npcRepository).save(captor.capture());
|
||||||
|
assertEquals(4, captor.getValue().getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCreateNpc_FirstNpcGetsOrderZero() {
|
||||||
|
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of());
|
||||||
|
when(npcRepository.save(any(Npc.class))).thenReturn(testNpc);
|
||||||
|
|
||||||
|
npcService.createNpc(new NpcService.NpcData("Premier", null, "camp-1", null));
|
||||||
|
|
||||||
|
ArgumentCaptor<Npc> captor = ArgumentCaptor.forClass(Npc.class);
|
||||||
|
verify(npcRepository).save(captor.capture());
|
||||||
|
assertEquals(0, captor.getValue().getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetNpcById_Found() {
|
||||||
|
when(npcRepository.findById("npc-1")).thenReturn(Optional.of(testNpc));
|
||||||
|
|
||||||
|
Optional<Npc> result = npcService.getNpcById("npc-1");
|
||||||
|
|
||||||
|
assertTrue(result.isPresent());
|
||||||
|
assertEquals("Borin le forgeron", result.get().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetNpcById_NotFound() {
|
||||||
|
when(npcRepository.findById("missing")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
Optional<Npc> result = npcService.getNpcById("missing");
|
||||||
|
|
||||||
|
assertFalse(result.isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetNpcsByCampaignId_DelegatesToRepository() {
|
||||||
|
Npc a = Npc.builder().id("a").campaignId("camp-1").order(1).build();
|
||||||
|
Npc b = Npc.builder().id("b").campaignId("camp-1").order(2).build();
|
||||||
|
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of(a, b));
|
||||||
|
|
||||||
|
List<Npc> result = npcService.getNpcsByCampaignId("camp-1");
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
verify(npcRepository).findByCampaignId("camp-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateNpc_Success() {
|
||||||
|
when(npcRepository.findById("npc-1")).thenReturn(Optional.of(testNpc));
|
||||||
|
when(npcRepository.save(any(Npc.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
Npc result = npcService.updateNpc("npc-1",
|
||||||
|
new NpcService.NpcData("Borin renommé", "# v2", "camp-1", 7));
|
||||||
|
|
||||||
|
assertEquals("Borin renommé", result.getName());
|
||||||
|
assertEquals("# v2", result.getMarkdownContent());
|
||||||
|
assertEquals(7, result.getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateNpc_OrderNullPreservesExistingOrder() {
|
||||||
|
when(npcRepository.findById("npc-1")).thenReturn(Optional.of(testNpc));
|
||||||
|
when(npcRepository.save(any(Npc.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||||
|
|
||||||
|
Npc result = npcService.updateNpc("npc-1",
|
||||||
|
new NpcService.NpcData("Borin", "# txt", "camp-1", null));
|
||||||
|
|
||||||
|
// testNpc avait order=1 → préservé
|
||||||
|
assertEquals(1, result.getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateNpc_NotFoundThrows() {
|
||||||
|
when(npcRepository.findById("missing")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> npcService.updateNpc("missing",
|
||||||
|
new NpcService.NpcData("x", null, "camp-1", null)));
|
||||||
|
assertTrue(ex.getMessage().contains("missing"));
|
||||||
|
verify(npcRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDeleteNpc_DelegatesToRepository() {
|
||||||
|
npcService.deleteNpc("npc-1");
|
||||||
|
verify(npcRepository).deleteById("npc-1");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,12 +3,15 @@ package com.loremind.application.generationcontext;
|
|||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Campaign;
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
import com.loremind.domain.campaigncontext.Scene;
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.SceneBranch;
|
import com.loremind.domain.campaigncontext.SceneBranch;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
import com.loremind.domain.generationcontext.CampaignStructuralContext;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -43,6 +46,8 @@ public class CampaignStructuralContextBuilderTest {
|
|||||||
private SceneRepository sceneRepository;
|
private SceneRepository sceneRepository;
|
||||||
@Mock
|
@Mock
|
||||||
private CharacterRepository characterRepository;
|
private CharacterRepository characterRepository;
|
||||||
|
@Mock
|
||||||
|
private NpcRepository npcRepository;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private CampaignStructuralContextBuilder builder;
|
private CampaignStructuralContextBuilder builder;
|
||||||
@@ -144,6 +149,66 @@ public class CampaignStructuralContextBuilderTest {
|
|||||||
assertEquals("(scène inconnue)", scene1Summary.branches().get(1).targetSceneName());
|
assertEquals("(scène inconnue)", scene1Summary.branches().get(1).targetSceneName());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBuild_ProjectsCharactersAndNpcsWithSnippets() {
|
||||||
|
Character pj1 = Character.builder().id("c-1").campaignId("camp-1").order(1)
|
||||||
|
.name("Aragorn")
|
||||||
|
.markdownContent("# Aragorn\n\nRôdeur du Nord, héritier d'Isildur.")
|
||||||
|
.build();
|
||||||
|
Character pj2 = Character.builder().id("c-2").campaignId("camp-1").order(2)
|
||||||
|
.name("Legolas")
|
||||||
|
.markdownContent(null) // pas de snippet → string vide
|
||||||
|
.build();
|
||||||
|
Npc npc1 = Npc.builder().id("n-1").campaignId("camp-1").order(2)
|
||||||
|
.name("Borin le forgeron")
|
||||||
|
.markdownContent("# Borin\n\nNain barbu au regard perçant, ancien clan Feuillefer.")
|
||||||
|
.build();
|
||||||
|
Npc npc2 = Npc.builder().id("n-2").campaignId("camp-1").order(1)
|
||||||
|
.name("Dame Elara")
|
||||||
|
.markdownContent("")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(campaignRepository.findById("camp-1")).thenReturn(Optional.of(campaign));
|
||||||
|
when(arcRepository.findByCampaignId("camp-1")).thenReturn(List.of());
|
||||||
|
when(characterRepository.findByCampaignId("camp-1")).thenReturn(List.of(pj2, pj1));
|
||||||
|
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of(npc1, npc2));
|
||||||
|
|
||||||
|
CampaignStructuralContext ctx = builder.build("camp-1");
|
||||||
|
|
||||||
|
// PJ triés par order croissant
|
||||||
|
assertEquals(2, ctx.characters().size());
|
||||||
|
assertEquals("Aragorn", ctx.characters().get(0).name());
|
||||||
|
assertEquals("Rôdeur du Nord, héritier d'Isildur.", ctx.characters().get(0).snippet());
|
||||||
|
assertEquals("Legolas", ctx.characters().get(1).name());
|
||||||
|
assertEquals("", ctx.characters().get(1).snippet());
|
||||||
|
|
||||||
|
// PNJ triés par order croissant : Elara (1) avant Borin (2)
|
||||||
|
assertEquals(2, ctx.npcs().size());
|
||||||
|
assertEquals("Dame Elara", ctx.npcs().get(0).name());
|
||||||
|
assertEquals("", ctx.npcs().get(0).snippet());
|
||||||
|
assertEquals("Borin le forgeron", ctx.npcs().get(1).name());
|
||||||
|
assertEquals("Nain barbu au regard perçant, ancien clan Feuillefer.",
|
||||||
|
ctx.npcs().get(1).snippet());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBuild_TruncatesLongSnippet() {
|
||||||
|
// Snippet > 160 chars : doit être tronqué à 159 + "…"
|
||||||
|
String longLine = "x".repeat(200);
|
||||||
|
Npc longNpc = Npc.builder().id("n-1").campaignId("camp-1").order(1)
|
||||||
|
.name("Verbeux").markdownContent(longLine).build();
|
||||||
|
|
||||||
|
when(campaignRepository.findById("camp-1")).thenReturn(Optional.of(campaign));
|
||||||
|
when(arcRepository.findByCampaignId("camp-1")).thenReturn(List.of());
|
||||||
|
when(npcRepository.findByCampaignId("camp-1")).thenReturn(List.of(longNpc));
|
||||||
|
|
||||||
|
CampaignStructuralContext ctx = builder.build("camp-1");
|
||||||
|
|
||||||
|
String snippet = ctx.npcs().get(0).snippet();
|
||||||
|
assertEquals(160, snippet.length());
|
||||||
|
assertTrue(snippet.endsWith("…"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testBuild_CountsIllustrationsNullSafe() {
|
void testBuild_CountsIllustrationsNullSafe() {
|
||||||
Arc arc = Arc.builder().id("arc-1").name("Arc").description("").order(1)
|
Arc arc = Arc.builder().id("arc-1").name("Arc").description("").order(1)
|
||||||
|
|||||||
@@ -2,9 +2,13 @@ package com.loremind.application.generationcontext;
|
|||||||
|
|
||||||
import com.loremind.domain.campaigncontext.Arc;
|
import com.loremind.domain.campaigncontext.Arc;
|
||||||
import com.loremind.domain.campaigncontext.Chapter;
|
import com.loremind.domain.campaigncontext.Chapter;
|
||||||
|
import com.loremind.domain.campaigncontext.Character;
|
||||||
|
import com.loremind.domain.campaigncontext.Npc;
|
||||||
import com.loremind.domain.campaigncontext.Scene;
|
import com.loremind.domain.campaigncontext.Scene;
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
import com.loremind.domain.generationcontext.NarrativeEntityContext;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -30,6 +34,8 @@ public class NarrativeEntityContextBuilderTest {
|
|||||||
@Mock private ArcRepository arcRepository;
|
@Mock private ArcRepository arcRepository;
|
||||||
@Mock private ChapterRepository chapterRepository;
|
@Mock private ChapterRepository chapterRepository;
|
||||||
@Mock private SceneRepository sceneRepository;
|
@Mock private SceneRepository sceneRepository;
|
||||||
|
@Mock private CharacterRepository characterRepository;
|
||||||
|
@Mock private NpcRepository npcRepository;
|
||||||
|
|
||||||
@InjectMocks private NarrativeEntityContextBuilder builder;
|
@InjectMocks private NarrativeEntityContextBuilder builder;
|
||||||
|
|
||||||
@@ -107,11 +113,59 @@ public class NarrativeEntityContextBuilderTest {
|
|||||||
assertEquals("arc", ctx.entityType());
|
assertEquals("arc", ctx.entityType());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBuild_Character_MarkdownProjected() {
|
||||||
|
Character c = Character.builder()
|
||||||
|
.id("c-1").name("Aragorn").markdownContent("# Aragorn\nRôdeur")
|
||||||
|
.build();
|
||||||
|
when(characterRepository.findById("c-1")).thenReturn(Optional.of(c));
|
||||||
|
|
||||||
|
NarrativeEntityContext ctx = builder.build("character", "c-1");
|
||||||
|
|
||||||
|
assertEquals("character", ctx.entityType());
|
||||||
|
assertEquals("Aragorn", ctx.title());
|
||||||
|
assertEquals("# Aragorn\nRôdeur", ctx.fields().get("fiche complète (markdown)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBuild_Npc_MarkdownProjected() {
|
||||||
|
Npc n = Npc.builder()
|
||||||
|
.id("n-1").name("Borin le forgeron")
|
||||||
|
.markdownContent("# Borin\n**Faction :** Clan Feuillefer")
|
||||||
|
.build();
|
||||||
|
when(npcRepository.findById("n-1")).thenReturn(Optional.of(n));
|
||||||
|
|
||||||
|
NarrativeEntityContext ctx = builder.build("npc", "n-1");
|
||||||
|
|
||||||
|
assertEquals("npc", ctx.entityType());
|
||||||
|
assertEquals("Borin le forgeron", ctx.title());
|
||||||
|
assertEquals("# Borin\n**Faction :** Clan Feuillefer",
|
||||||
|
ctx.fields().get("fiche complète (markdown)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBuild_Npc_NormalizesCase() {
|
||||||
|
Npc n = Npc.builder().id("n-1").name("Elara").markdownContent("desc").build();
|
||||||
|
when(npcRepository.findById("n-1")).thenReturn(Optional.of(n));
|
||||||
|
|
||||||
|
NarrativeEntityContext ctx = builder.build(" NPC ", "n-1");
|
||||||
|
assertEquals("npc", ctx.entityType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBuild_NpcNotFoundThrows() {
|
||||||
|
when(npcRepository.findById("missing")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> builder.build("npc", "missing"));
|
||||||
|
assertTrue(ex.getMessage().contains("missing"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testBuild_UnknownTypeThrows() {
|
void testBuild_UnknownTypeThrows() {
|
||||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
() -> builder.build("npc", "id"));
|
() -> builder.build("alien", "id"));
|
||||||
assertTrue(ex.getMessage().contains("npc"));
|
assertTrue(ex.getMessage().contains("alien"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ public class StreamChatForCampaignUseCaseTest {
|
|||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
campaignCtx = new CampaignStructuralContext("X", "d", List.of(), List.of());
|
campaignCtx = new CampaignStructuralContext("X", "d", List.of(), List.of(), List.of());
|
||||||
messages = List.of();
|
messages = List.of();
|
||||||
onUsage = mock(Consumer.class);
|
onUsage = mock(Consumer.class);
|
||||||
onToken = mock(Consumer.class);
|
onToken = mock(Consumer.class);
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ class CampaignStructuralContextTest {
|
|||||||
"Les Ombres",
|
"Les Ombres",
|
||||||
"Une campagne dark fantasy",
|
"Une campagne dark fantasy",
|
||||||
List.of(arc),
|
List.of(arc),
|
||||||
|
List.of(),
|
||||||
List.of());
|
List.of());
|
||||||
|
|
||||||
assertEquals("Les Ombres", ctx.campaignName());
|
assertEquals("Les Ombres", ctx.campaignName());
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ class ChatRequestTest {
|
|||||||
ChatRequest request = ChatRequest.builder()
|
ChatRequest request = ChatRequest.builder()
|
||||||
.messages(sampleMessages)
|
.messages(sampleMessages)
|
||||||
.campaignContext(new CampaignStructuralContext(
|
.campaignContext(new CampaignStructuralContext(
|
||||||
"Les Ombres", "...", List.of(), List.of()))
|
"Les Ombres", "...", List.of(), List.of(), List.of()))
|
||||||
.narrativeEntity(new NarrativeEntityContext(
|
.narrativeEntity(new NarrativeEntityContext(
|
||||||
"scene", "L'auberge", Map.of("location", "Taverne")))
|
"scene", "L'auberge", Map.of("location", "Taverne")))
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
ChapterSummary chapter = new ChapterSummary("L'arrivee", "...", 0, List.of(scene));
|
ChapterSummary chapter = new ChapterSummary("L'arrivee", "...", 0, List.of(scene));
|
||||||
ArcSummary arc = new ArcSummary("Acte I", "Mise en place", 1, List.of(chapter));
|
ArcSummary arc = new ArcSummary("Acte I", "Mise en place", 1, List.of(chapter));
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"Les Ombres", "dark fantasy", List.of(arc), List.of());
|
"Les Ombres", "dark fantasy", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
Map<String, Object> payload = builder.build(req);
|
Map<String, Object> payload = builder.build(req);
|
||||||
@@ -200,7 +200,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
void build_arcSummary_omitsIllustrationCount_whenZero() {
|
void build_arcSummary_omitsIllustrationCount_whenZero() {
|
||||||
ArcSummary arc = new ArcSummary("A", "", 0, List.of());
|
ArcSummary arc = new ArcSummary("A", "", 0, List.of());
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"X", "", List.of(arc), List.of());
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
Map<String, Object> payload = builder.build(req);
|
Map<String, Object> payload = builder.build(req);
|
||||||
@@ -217,7 +217,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||||
ArcSummary arc = new ArcSummary("A", "", 0, List.of(chapter));
|
ArcSummary arc = new ArcSummary("A", "", 0, List.of(chapter));
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"X", "", List.of(arc), List.of());
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
Map<String, Object> payload = builder.build(req);
|
Map<String, Object> payload = builder.build(req);
|
||||||
@@ -236,7 +236,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
ChapterSummary chapter = new ChapterSummary("Ch", "", 0, List.of(scene));
|
||||||
ArcSummary arc = new ArcSummary("A", "", 0, List.of(chapter));
|
ArcSummary arc = new ArcSummary("A", "", 0, List.of(chapter));
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"X", "", List.of(arc), List.of());
|
"X", "", List.of(arc), List.of(), List.of());
|
||||||
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
ChatRequest req = ChatRequest.builder().messages(sampleMessages).campaignContext(camp).build();
|
||||||
|
|
||||||
Map<String, Object> payload = builder.build(req);
|
Map<String, Object> payload = builder.build(req);
|
||||||
@@ -269,7 +269,7 @@ class BrainChatPayloadBuilderTest {
|
|||||||
@Test
|
@Test
|
||||||
void build_campaignScenario_includesBothContextsAndEntity() {
|
void build_campaignScenario_includesBothContextsAndEntity() {
|
||||||
CampaignStructuralContext camp = new CampaignStructuralContext(
|
CampaignStructuralContext camp = new CampaignStructuralContext(
|
||||||
"X", "", List.of(), List.of());
|
"X", "", List.of(), List.of(), List.of());
|
||||||
NarrativeEntityContext entity = new NarrativeEntityContext("arc", "T", Map.of());
|
NarrativeEntityContext entity = new NarrativeEntityContext("arc", "T", Map.of());
|
||||||
ChatRequest req = ChatRequest.builder()
|
ChatRequest req = ChatRequest.builder()
|
||||||
.messages(sampleMessages)
|
.messages(sampleMessages)
|
||||||
|
|||||||
@@ -0,0 +1,207 @@
|
|||||||
|
package com.loremind.infrastructure.updates;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatus;
|
||||||
|
import com.loremind.infrastructure.updates.UpdateCheckService.ImageStatusKind;
|
||||||
|
import com.loremind.infrastructure.updates.UpdateCheckService.UpdateStatus;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test unitaire pour UpdateCheckService.
|
||||||
|
*
|
||||||
|
* Couvre les invariants critiques de la detection de MAJ :
|
||||||
|
* - feature desactivee si token absent
|
||||||
|
* - status UP_TO_DATE quand baseline == remote
|
||||||
|
* - status UPDATE_AVAILABLE quand baseline != remote
|
||||||
|
* - status UNKNOWN quand baseline manque (PAS d'alignement lazy — invariant
|
||||||
|
* central, regression historique)
|
||||||
|
* - status UNKNOWN quand remote impossible a fetcher
|
||||||
|
* - drapeaux top-level updateAvailable / anyUnknown coherents
|
||||||
|
* - back-compat : champ updateAvailable sur ImageStatus = (status == UPDATE_AVAILABLE)
|
||||||
|
*/
|
||||||
|
public class UpdateCheckServiceTest {
|
||||||
|
|
||||||
|
private static UpdateCheckService newService(String token) {
|
||||||
|
// licensing.* params left empty + LicenseService null : la feature beta est
|
||||||
|
// desactivee dans ces tests, qui couvrent uniquement le canal stable.
|
||||||
|
return new UpdateCheckService(
|
||||||
|
new RestTemplateBuilder(),
|
||||||
|
"ghcr.io",
|
||||||
|
"igmlcreation/loremind-core,igmlcreation/loremind-brain",
|
||||||
|
"latest",
|
||||||
|
"http://watchtower:8080",
|
||||||
|
token,
|
||||||
|
"",
|
||||||
|
"latest",
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injecte un RestTemplate moque dans le service deja construit, et pose
|
||||||
|
* directement les baselines pour eviter les vrais appels HTTP.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static void setBaselines(UpdateCheckService svc, Map<String, String> baselines) {
|
||||||
|
((Map<String, String>) ReflectionTestUtils.getField(svc, "baselineDigests")).putAll(baselines);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RestTemplate stubHttp(UpdateCheckService svc) {
|
||||||
|
RestTemplate http = mock(RestTemplate.class);
|
||||||
|
ReflectionTestUtils.setField(svc, "http", http);
|
||||||
|
return http;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void stubRemoteDigest(RestTemplate http, String image, String digest) {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
if (digest != null) headers.add("Docker-Content-Digest", digest);
|
||||||
|
ResponseEntity<Void> resp = new ResponseEntity<>(headers, org.springframework.http.HttpStatus.OK);
|
||||||
|
when(http.exchange(eq("https://ghcr.io/v2/" + image + "/manifests/latest"),
|
||||||
|
eq(org.springframework.http.HttpMethod.HEAD), any(), eq(Void.class)))
|
||||||
|
.thenReturn(resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void stubRemoteFailure(RestTemplate http, String image) {
|
||||||
|
when(http.exchange(eq("https://ghcr.io/v2/" + image + "/manifests/latest"),
|
||||||
|
eq(org.springframework.http.HttpMethod.HEAD), any(), eq(Void.class)))
|
||||||
|
.thenThrow(new RuntimeException("network down"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void disabledWhenTokenMissing() {
|
||||||
|
UpdateCheckService svc = newService("");
|
||||||
|
UpdateStatus status = svc.check();
|
||||||
|
assertFalse(status.enabled());
|
||||||
|
assertFalse(status.updateAvailable());
|
||||||
|
assertFalse(status.anyUnknown());
|
||||||
|
assertTrue(status.images().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void upToDate_whenBaselineEqualsRemote() {
|
||||||
|
UpdateCheckService svc = newService("token");
|
||||||
|
ReflectionTestUtils.setField(svc, "baselineDigests", new ConcurrentHashMap<>());
|
||||||
|
setBaselines(svc, Map.of(
|
||||||
|
"igmlcreation/loremind-core", "sha256:aaa",
|
||||||
|
"igmlcreation/loremind-brain", "sha256:bbb"
|
||||||
|
));
|
||||||
|
RestTemplate http = stubHttp(svc);
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-core", "sha256:aaa");
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-brain", "sha256:bbb");
|
||||||
|
|
||||||
|
UpdateStatus status = svc.check();
|
||||||
|
|
||||||
|
assertTrue(status.enabled());
|
||||||
|
assertFalse(status.updateAvailable());
|
||||||
|
assertFalse(status.anyUnknown());
|
||||||
|
for (ImageStatus img : status.images()) {
|
||||||
|
assertEquals(ImageStatusKind.UP_TO_DATE, img.status());
|
||||||
|
assertFalse(img.updateAvailable(), "back-compat bool");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateAvailable_whenRemoteDiffers() {
|
||||||
|
UpdateCheckService svc = newService("token");
|
||||||
|
ReflectionTestUtils.setField(svc, "baselineDigests", new ConcurrentHashMap<>());
|
||||||
|
setBaselines(svc, Map.of(
|
||||||
|
"igmlcreation/loremind-core", "sha256:OLD",
|
||||||
|
"igmlcreation/loremind-brain", "sha256:bbb"
|
||||||
|
));
|
||||||
|
RestTemplate http = stubHttp(svc);
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-core", "sha256:NEW");
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-brain", "sha256:bbb");
|
||||||
|
|
||||||
|
UpdateStatus status = svc.check();
|
||||||
|
|
||||||
|
assertTrue(status.updateAvailable());
|
||||||
|
assertFalse(status.anyUnknown());
|
||||||
|
ImageStatus core = status.images().stream()
|
||||||
|
.filter(i -> i.image().endsWith("core")).findFirst().orElseThrow();
|
||||||
|
assertEquals(ImageStatusKind.UPDATE_AVAILABLE, core.status());
|
||||||
|
assertTrue(core.updateAvailable(), "back-compat bool");
|
||||||
|
ImageStatus brain = status.images().stream()
|
||||||
|
.filter(i -> i.image().endsWith("brain")).findFirst().orElseThrow();
|
||||||
|
assertEquals(ImageStatusKind.UP_TO_DATE, brain.status());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknown_whenBaselineMissing_DOES_NOT_lazyAlign() {
|
||||||
|
// INVARIANT CENTRAL : si la baseline est absente (echec init au boot),
|
||||||
|
// on NE DOIT PAS aligner lazy sur le remote courant — sinon une MAJ
|
||||||
|
// pousse APRES le boot serait declaree "a jour" silencieusement.
|
||||||
|
UpdateCheckService svc = newService("token");
|
||||||
|
ReflectionTestUtils.setField(svc, "baselineDigests", new ConcurrentHashMap<>());
|
||||||
|
// baseline DELIBEREMENT vide
|
||||||
|
RestTemplate http = stubHttp(svc);
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-core", "sha256:remote-now");
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-brain", "sha256:remote-now-2");
|
||||||
|
|
||||||
|
UpdateStatus status = svc.check();
|
||||||
|
|
||||||
|
assertTrue(status.enabled());
|
||||||
|
assertFalse(status.updateAvailable());
|
||||||
|
assertTrue(status.anyUnknown());
|
||||||
|
for (ImageStatus img : status.images()) {
|
||||||
|
assertEquals(ImageStatusKind.UNKNOWN, img.status());
|
||||||
|
assertNull(img.localDigest());
|
||||||
|
assertNotNull(img.remoteDigest()); // remote OK, baseline manquante
|
||||||
|
}
|
||||||
|
|
||||||
|
// VERIFICATION CRITIQUE : la baseline ne doit PAS avoir ete posee.
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, String> baselines = (Map<String, String>) ReflectionTestUtils.getField(svc, "baselineDigests");
|
||||||
|
assertTrue(baselines.isEmpty(),
|
||||||
|
"check() ne doit JAMAIS aligner lazy la baseline sur le remote — "
|
||||||
|
+ "regression de bug historique (faux negatif silencieux).");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknown_whenRemoteFetchFails() {
|
||||||
|
UpdateCheckService svc = newService("token");
|
||||||
|
ReflectionTestUtils.setField(svc, "baselineDigests", new ConcurrentHashMap<>());
|
||||||
|
setBaselines(svc, Map.of("igmlcreation/loremind-core", "sha256:aaa",
|
||||||
|
"igmlcreation/loremind-brain", "sha256:bbb"));
|
||||||
|
RestTemplate http = stubHttp(svc);
|
||||||
|
stubRemoteFailure(http, "igmlcreation/loremind-core");
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-brain", "sha256:bbb");
|
||||||
|
|
||||||
|
UpdateStatus status = svc.check();
|
||||||
|
|
||||||
|
assertFalse(status.updateAvailable());
|
||||||
|
assertTrue(status.anyUnknown());
|
||||||
|
ImageStatus core = status.images().stream()
|
||||||
|
.filter(i -> i.image().endsWith("core")).findFirst().orElseThrow();
|
||||||
|
assertEquals(ImageStatusKind.UNKNOWN, core.status());
|
||||||
|
assertNull(core.remoteDigest());
|
||||||
|
assertEquals("sha256:aaa", core.localDigest()); // baseline preservee
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mixedStatuses_anyUnknownAndAnyUpdateBothTrue() {
|
||||||
|
UpdateCheckService svc = newService("token");
|
||||||
|
ReflectionTestUtils.setField(svc, "baselineDigests", new ConcurrentHashMap<>());
|
||||||
|
setBaselines(svc, Map.of("igmlcreation/loremind-core", "sha256:OLD"));
|
||||||
|
// brain n'a pas de baseline -> UNKNOWN
|
||||||
|
RestTemplate http = stubHttp(svc);
|
||||||
|
stubRemoteDigest(http, "igmlcreation/loremind-core", "sha256:NEW");
|
||||||
|
stubRemoteFailure(http, "igmlcreation/loremind-brain");
|
||||||
|
|
||||||
|
UpdateStatus status = svc.check();
|
||||||
|
|
||||||
|
assertTrue(status.updateAvailable(), "core a une MAJ disponible");
|
||||||
|
assertTrue(status.anyUnknown(), "brain est UNKNOWN");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,7 +60,12 @@ services:
|
|||||||
"
|
"
|
||||||
|
|
||||||
core:
|
core:
|
||||||
image: ${REGISTRY:-git.igmlcreation.fr}/ietm64/core:${TAG:-latest}
|
# Defaut : GHCR (registry public, reputation domaine elevee).
|
||||||
|
# Pour les anciennes installs qui pointaient sur Gitea, REGISTRY et
|
||||||
|
# IMAGE_NAMESPACE peuvent etre overrides dans .env :
|
||||||
|
# REGISTRY=git.igmlcreation.fr
|
||||||
|
# IMAGE_NAMESPACE=ietm64/ (le slash final est important : voir image: ci-dessous)
|
||||||
|
image: ${REGISTRY:-ghcr.io}/${IMAGE_NAMESPACE:-igmlcreation/loremind-}core:${TAG:-latest}
|
||||||
container_name: loremind-core
|
container_name: loremind-core
|
||||||
labels:
|
labels:
|
||||||
- "com.centurylinklabs.watchtower.enable=true"
|
- "com.centurylinklabs.watchtower.enable=true"
|
||||||
@@ -84,21 +89,60 @@ services:
|
|||||||
# Detection des mises a jour : interroge le registry et delegue le pull/restart
|
# Detection des mises a jour : interroge le registry et delegue le pull/restart
|
||||||
# a Watchtower. Si WATCHTOWER_TOKEN est vide, la feature est desactivee
|
# a Watchtower. Si WATCHTOWER_TOKEN est vide, la feature est desactivee
|
||||||
# (l'UI masque le badge et le bouton).
|
# (l'UI masque le badge et le bouton).
|
||||||
UPDATE_CHECK_REGISTRY: ${REGISTRY:-git.igmlcreation.fr}
|
UPDATE_CHECK_REGISTRY: ${REGISTRY:-ghcr.io}
|
||||||
UPDATE_CHECK_IMAGES: ietm64/core,ietm64/brain,ietm64/web
|
UPDATE_CHECK_IMAGES: ${IMAGE_NAMESPACE:-igmlcreation/loremind-}core,${IMAGE_NAMESPACE:-igmlcreation/loremind-}brain,${IMAGE_NAMESPACE:-igmlcreation/loremind-}web
|
||||||
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
|
||||||
|
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
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# Ollama embarque (option par defaut pour les utilisateurs sans Ollama installe).
|
||||||
|
# Active via COMPOSE_PROFILES=local-ollama (gere par l'installeur).
|
||||||
|
# Si l'utilisateur a deja Ollama sur l'hote, ce service reste inactif et
|
||||||
|
# OLLAMA_BASE_URL pointe vers http://host.docker.internal:11434.
|
||||||
|
ollama:
|
||||||
|
image: ollama/ollama:latest
|
||||||
|
container_name: loremind-ollama
|
||||||
|
profiles: ["local-ollama"]
|
||||||
|
volumes:
|
||||||
|
- ollama-data:/root/.ollama
|
||||||
|
# Port expose sur loopback uniquement pour debug / pull manuel de modeles.
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:11434:11434"
|
||||||
|
# GPU NVIDIA si disponible (silencieusement ignore sinon).
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
reservations:
|
||||||
|
devices:
|
||||||
|
- driver: nvidia
|
||||||
|
count: all
|
||||||
|
capabilities: [gpu]
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
brain:
|
brain:
|
||||||
image: ${REGISTRY:-git.igmlcreation.fr}/ietm64/brain:${TAG:-latest}
|
image: ${REGISTRY:-ghcr.io}/${IMAGE_NAMESPACE:-igmlcreation/loremind-}brain:${TAG:-latest}
|
||||||
container_name: loremind-brain
|
container_name: loremind-brain
|
||||||
labels:
|
labels:
|
||||||
- "com.centurylinklabs.watchtower.enable=true"
|
- "com.centurylinklabs.watchtower.enable=true"
|
||||||
environment:
|
environment:
|
||||||
LLM_PROVIDER: ${LLM_PROVIDER:-ollama}
|
LLM_PROVIDER: ${LLM_PROVIDER:-ollama}
|
||||||
OLLAMA_BASE_URL: ${OLLAMA_BASE_URL:-http://host.docker.internal:11434}
|
# Defaut = Ollama embarque (service ollama du compose).
|
||||||
|
# L'installeur reecrit cette valeur en http://host.docker.internal:11434
|
||||||
|
# si l'utilisateur choisit le mode "Ollama deja installe sur l'hote".
|
||||||
|
OLLAMA_BASE_URL: ${OLLAMA_BASE_URL:-http://ollama:11434}
|
||||||
LLM_MODEL: ${LLM_MODEL:-gemma4:26b}
|
LLM_MODEL: ${LLM_MODEL:-gemma4:26b}
|
||||||
ONEMIN_API_KEY: ${ONEMIN_API_KEY:-}
|
ONEMIN_API_KEY: ${ONEMIN_API_KEY:-}
|
||||||
ONEMIN_MODEL: ${ONEMIN_MODEL:-gpt-4o-mini}
|
ONEMIN_MODEL: ${ONEMIN_MODEL:-gpt-4o-mini}
|
||||||
@@ -112,7 +156,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
web:
|
web:
|
||||||
image: ${REGISTRY:-git.igmlcreation.fr}/ietm64/web:${TAG:-latest}
|
image: ${REGISTRY:-ghcr.io}/${IMAGE_NAMESPACE:-igmlcreation/loremind-}web:${TAG:-latest}
|
||||||
container_name: loremind-web
|
container_name: loremind-web
|
||||||
labels:
|
labels:
|
||||||
- "com.centurylinklabs.watchtower.enable=true"
|
- "com.centurylinklabs.watchtower.enable=true"
|
||||||
@@ -128,12 +172,24 @@ services:
|
|||||||
# Postgres et MinIO sont volontairement exclus (donnees persistantes,
|
# Postgres et MinIO sont volontairement exclus (donnees persistantes,
|
||||||
# compatibilite de version a verifier manuellement).
|
# compatibilite de version a verifier manuellement).
|
||||||
watchtower:
|
watchtower:
|
||||||
image: containrrr/watchtower:latest
|
# Fork maintenu de containrrr/watchtower (l'original est abandonne depuis
|
||||||
|
# ~2023 et son client Docker API est trop vieux pour les versions recentes
|
||||||
|
# de Docker Desktop -- erreur "client version 1.25 is too old").
|
||||||
|
# nickfedor/watchtower est un drop-in : memes variables d'environnement,
|
||||||
|
# meme API HTTP, juste l'image change.
|
||||||
|
image: nickfedor/watchtower:latest
|
||||||
container_name: loremind-watchtower
|
container_name: loremind-watchtower
|
||||||
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"
|
||||||
@@ -154,3 +210,7 @@ volumes:
|
|||||||
postgres-data:
|
postgres-data:
|
||||||
minio-data:
|
minio-data:
|
||||||
brain-data:
|
brain-data:
|
||||||
|
ollama-data:
|
||||||
|
# Volume partage Core <-> Watchtower : config.json Docker pour
|
||||||
|
# l'authentification au registry prive GHCR (canal beta Patreon).
|
||||||
|
docker-config:
|
||||||
|
|||||||
@@ -1,109 +0,0 @@
|
|||||||
# LoreMindMJ — Installation rapide
|
|
||||||
|
|
||||||
Ces scripts installent Docker (si nécessaire), génèrent un `.env` sécurisé
|
|
||||||
et lancent la stack. Aucune configuration manuelle requise.
|
|
||||||
|
|
||||||
## Windows 10 / 11
|
|
||||||
|
|
||||||
Ouvrir **PowerShell** (clic droit → *Exécuter en tant qu'administrateur*) :
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
iwr https://git.igmlcreation.fr/ietm64/loremind/raw/branch/main/installers/install.ps1 -OutFile $env:TEMP\loremind-install.ps1
|
|
||||||
powershell -ExecutionPolicy Bypass -File $env:TEMP\loremind-install.ps1
|
|
||||||
```
|
|
||||||
|
|
||||||
Le script :
|
|
||||||
1. Vérifie / installe **WSL2** (un reboot peut être nécessaire — relancer le script après).
|
|
||||||
2. Vérifie / installe **Docker Desktop** via `winget`.
|
|
||||||
3. Génère `%LOCALAPPDATA%\LoreMind\.env` avec mots de passe aléatoires.
|
|
||||||
4. Lance la stack et ouvre `http://localhost:8081`.
|
|
||||||
|
|
||||||
## Linux (Debian / Ubuntu / Fedora / Arch)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -fsSL https://git.igmlcreation.fr/ietm64/loremind/raw/branch/main/installers/install.sh | bash
|
|
||||||
```
|
|
||||||
|
|
||||||
Le script :
|
|
||||||
1. Installe **Docker** via le script officiel `get.docker.com` si absent.
|
|
||||||
2. Ajoute l'utilisateur courant au groupe `docker` (relogin nécessaire la 1ʳᵉ fois).
|
|
||||||
3. Installe dans `~/.local/share/loremind`.
|
|
||||||
4. Lance la stack et ouvre `http://localhost:8081`.
|
|
||||||
|
|
||||||
## Variables disponibles
|
|
||||||
|
|
||||||
| Variable | Défaut | Effet |
|
|
||||||
|-------------------|---------------------------------|----------------------------------------|
|
|
||||||
| `WEB_PORT` | `8081` | Port HTTP de l'UI |
|
|
||||||
| `INSTALL_DIR` | `~/.local/share/loremind` (Lin) | Dossier d'installation |
|
|
||||||
| `NON_INTERACTIVE` | `0` | `1` = aucune question, valeurs par défaut |
|
|
||||||
|
|
||||||
Exemple Linux non-interactif sur port 9000 :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
WEB_PORT=9000 NON_INTERACTIVE=1 bash install.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
## Mises à jour automatiques (Watchtower)
|
|
||||||
|
|
||||||
Si vous avez répondu **oui** à la question "Activer les mises à jour auto",
|
|
||||||
un container [Watchtower](https://containrrr.dev/watchtower/) est lancé en
|
|
||||||
parallèle. Il vérifie chaque nuit à 4h les nouvelles versions de
|
|
||||||
`core`, `brain` et `web` sur le registry, télécharge et redémarre les
|
|
||||||
conteneurs concernés. **Postgres et MinIO sont volontairement exclus**
|
|
||||||
(données persistantes — montée de version à valider manuellement).
|
|
||||||
|
|
||||||
### Activer / désactiver après coup
|
|
||||||
|
|
||||||
Éditer `.env` dans le dossier d'installation :
|
|
||||||
|
|
||||||
```env
|
|
||||||
COMPOSE_PROFILES=autoupdate # active
|
|
||||||
COMPOSE_PROFILES= # desactive
|
|
||||||
```
|
|
||||||
|
|
||||||
Puis :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose up -d # applique le changement
|
|
||||||
docker compose stop watchtower # si on vient de le desactiver
|
|
||||||
```
|
|
||||||
|
|
||||||
### Changer l'horaire
|
|
||||||
|
|
||||||
`WATCHTOWER_SCHEDULE` dans `.env` accepte la syntaxe
|
|
||||||
[cron 6 champs](https://pkg.go.dev/github.com/robfig/cron) (sec min h jour mois j-sem).
|
|
||||||
Exemples : `0 0 4 * * *` (4h du matin, défaut), `0 30 3 * * 0` (dimanche 3h30).
|
|
||||||
|
|
||||||
### Mode "notification seulement" (sans auto-apply)
|
|
||||||
|
|
||||||
Si vous préférez être notifié *sans* que les conteneurs redémarrent
|
|
||||||
automatiquement la nuit, éditez `.env` :
|
|
||||||
|
|
||||||
```env
|
|
||||||
WATCHTOWER_MONITOR_ONLY=true
|
|
||||||
```
|
|
||||||
|
|
||||||
Puis `docker compose up -d watchtower`. Watchtower continuera à vérifier
|
|
||||||
le registry chaque nuit, le badge **MAJ** apparaîtra dans la sidebar de
|
|
||||||
l'UI, et un bouton **Mettre à jour maintenant** sera disponible dans
|
|
||||||
*Paramètres → Mises à jour*.
|
|
||||||
|
|
||||||
### Mise à jour manuelle (à tout moment)
|
|
||||||
|
|
||||||
Depuis l'interface : *Paramètres → Mises à jour → Mettre à jour maintenant*.
|
|
||||||
|
|
||||||
Ou en CLI :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose pull && docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
## Désinstallation
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd <dossier d'install>
|
|
||||||
docker compose down -v # -v supprime aussi les volumes (données effacées !)
|
|
||||||
```
|
|
||||||
|
|
||||||
Puis supprimer le dossier d'installation.
|
|
||||||
59
installers/install.bat
Normal file
59
installers/install.bat
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
@echo off
|
||||||
|
REM ============================================================================
|
||||||
|
REM LoreMindMJ - Lanceur Windows pour install.ps1
|
||||||
|
REM ----------------------------------------------------------------------------
|
||||||
|
REM Procedure :
|
||||||
|
REM 1. Clic-DROIT sur ce fichier (install.bat)
|
||||||
|
REM 2. Choisir "Executer en tant qu'administrateur"
|
||||||
|
REM 3. Accepter le prompt UAC
|
||||||
|
REM ============================================================================
|
||||||
|
|
||||||
|
setlocal
|
||||||
|
title LoreMindMJ - Installeur
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ============================================================
|
||||||
|
echo LoreMindMJ - Installeur Windows
|
||||||
|
echo ============================================================
|
||||||
|
echo.
|
||||||
|
|
||||||
|
REM --- Verification des droits administrateur --------------------------------
|
||||||
|
net session >nul 2>&1
|
||||||
|
if %errorlevel% NEQ 0 (
|
||||||
|
echo [ERREUR] Ce script doit etre execute en tant qu'administrateur.
|
||||||
|
echo.
|
||||||
|
echo Procedure :
|
||||||
|
echo 1. Fermez cette fenetre.
|
||||||
|
echo 2. Clic-DROIT sur install.bat ^> "Executer en tant qu'administrateur".
|
||||||
|
echo 3. Acceptez le prompt UAC.
|
||||||
|
echo.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
REM --- Verification de la presence d'install.ps1 -----------------------------
|
||||||
|
if not exist "%~dp0install.ps1" (
|
||||||
|
echo [ERREUR] install.ps1 introuvable dans le meme dossier que ce .bat.
|
||||||
|
echo Dossier attendu : %~dp0
|
||||||
|
echo.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
REM --- Lancement du script PowerShell ----------------------------------------
|
||||||
|
REM -ExecutionPolicy Bypass : uniquement pour cette session, ne modifie pas
|
||||||
|
REM les parametres systeme.
|
||||||
|
cd /d "%~dp0"
|
||||||
|
|
||||||
|
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1" %*
|
||||||
|
set "PS_EXIT=%errorlevel%"
|
||||||
|
|
||||||
|
echo.
|
||||||
|
if %PS_EXIT% EQU 0 (
|
||||||
|
echo Installation terminee avec succes.
|
||||||
|
) else (
|
||||||
|
echo [ATTENTION] Le script PowerShell s'est termine avec le code %PS_EXIT%.
|
||||||
|
)
|
||||||
|
echo.
|
||||||
|
pause
|
||||||
|
endlocal
|
||||||
@@ -1,20 +1,55 @@
|
|||||||
#Requires -Version 5.1
|
#Requires -Version 5.1
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Installeur LoreMindMJ pour Windows 10/11.
|
Installeur officiel de LoreMindMJ pour Windows 10/11.
|
||||||
|
|
||||||
.DESCRIPTION
|
.DESCRIPTION
|
||||||
- Verifie / installe WSL2 et Docker Desktop (via winget)
|
Script d'installation pas-a-pas qui :
|
||||||
- Genere un .env avec mots de passe aleatoires
|
- Verifie la presence de WSL2 et Docker Desktop ; les installe via winget si absents
|
||||||
- Recupere le docker-compose.yml officiel
|
- Telecharge le fichier docker-compose.yml officiel depuis le depot du projet
|
||||||
- Lance la stack et ouvre le navigateur
|
- Genere un fichier .env contenant des secrets aleatoires (RNG cryptographique)
|
||||||
|
- Configure le mode Ollama (embarque dans Docker ou Ollama deja installe sur l'hote)
|
||||||
|
- Demarre la stack Docker et ouvre l'application dans le navigateur
|
||||||
|
|
||||||
|
Aucune connexion sortante n'est etablie en dehors :
|
||||||
|
- du depot officiel du projet (fichier docker-compose.yml)
|
||||||
|
- du Docker Hub / registry Docker pour les images
|
||||||
|
|
||||||
|
Le code source de ce script est public et auditable a l'adresse indiquee dans .LINK.
|
||||||
|
|
||||||
|
.PARAMETER InstallDir
|
||||||
|
Dossier d'installation. Defaut : %LOCALAPPDATA%\LoreMind
|
||||||
|
|
||||||
|
.PARAMETER ComposeUrl
|
||||||
|
URL du fichier docker-compose.yml a recuperer. Defaut : version officielle du depot.
|
||||||
|
|
||||||
|
.PARAMETER WebPort
|
||||||
|
Port HTTP local sur lequel l'application sera exposee. Defaut : 8081.
|
||||||
|
|
||||||
|
.PARAMETER NonInteractive
|
||||||
|
Mode automatique pour CI / re-installation. Utilise les valeurs par defaut.
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
iwr https://git.igmlcreation.fr/ietm64/loremind/raw/branch/main/installers/install.ps1 | iex
|
Procedure recommandee :
|
||||||
|
1. Telechargez install.ps1 dans un dossier (clic droit -> Enregistrer la cible sous).
|
||||||
|
2. Ouvrez PowerShell en tant qu'administrateur (clic droit sur PowerShell).
|
||||||
|
3. Naviguez vers le dossier : cd C:\Chemin\Vers\Le\Dossier
|
||||||
|
4. Lancez : .\install.ps1
|
||||||
|
|
||||||
|
.NOTES
|
||||||
|
Auteur : ietm64
|
||||||
|
Licence : AGPL-3.0
|
||||||
|
Projet : LoreMindMJ - assistant pour Maitres de Jeu de JDR
|
||||||
|
Version : 0.8.0
|
||||||
|
|
||||||
|
.LINK
|
||||||
|
https://github.com/IGMLcreation/LoreMind
|
||||||
#>
|
#>
|
||||||
|
|
||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[string]$InstallDir = "$env:LOCALAPPDATA\LoreMind",
|
[string]$InstallDir = "$env:LOCALAPPDATA\LoreMind",
|
||||||
[string]$ComposeUrl = "https://git.igmlcreation.fr/ietm64/loremind/raw/branch/main/docker-compose.yml",
|
[string]$ComposeUrl = "https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/docker-compose.yml",
|
||||||
[int]$WebPort = 8081,
|
[int]$WebPort = 8081,
|
||||||
[switch]$NonInteractive
|
[switch]$NonInteractive
|
||||||
)
|
)
|
||||||
@@ -27,19 +62,16 @@ function Write-Warn2($msg) { Write-Host " !! $msg" -ForegroundColor Yellow }
|
|||||||
function Write-Err($msg) { Write-Host " XX $msg" -ForegroundColor Red }
|
function Write-Err($msg) { Write-Host " XX $msg" -ForegroundColor Red }
|
||||||
|
|
||||||
function Test-Admin {
|
function Test-Admin {
|
||||||
|
# Verifie si la session courante a les droits administrateur Windows.
|
||||||
$current = [Security.Principal.WindowsIdentity]::GetCurrent()
|
$current = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
return ([Security.Principal.WindowsPrincipal]$current).IsInRole(
|
return ([Security.Principal.WindowsPrincipal]$current).IsInRole(
|
||||||
[Security.Principal.WindowsBuiltInRole]::Administrator)
|
[Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||||
}
|
}
|
||||||
|
|
||||||
function Invoke-Elevated {
|
|
||||||
Write-Step "Relance en mode administrateur..."
|
|
||||||
$args = @('-NoProfile','-ExecutionPolicy','Bypass','-File',$PSCommandPath)
|
|
||||||
Start-Process powershell -Verb RunAs -ArgumentList $args
|
|
||||||
exit
|
|
||||||
}
|
|
||||||
|
|
||||||
function New-RandomSecret([int]$Length = 32) {
|
function New-RandomSecret([int]$Length = 32) {
|
||||||
|
# Genere un secret aleatoire imprimable (hex) via le RNG cryptographique
|
||||||
|
# de .NET. Utilise pour les mots de passe Postgres / MinIO / tokens internes
|
||||||
|
# afin que chaque installation ait des credentials uniques.
|
||||||
$bytes = New-Object byte[] $Length
|
$bytes = New-Object byte[] $Length
|
||||||
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
|
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
|
||||||
return ([BitConverter]::ToString($bytes) -replace '-','').ToLower().Substring(0, $Length)
|
return ([BitConverter]::ToString($bytes) -replace '-','').ToLower().Substring(0, $Length)
|
||||||
@@ -59,21 +91,54 @@ function Test-Docker {
|
|||||||
return ($LASTEXITCODE -eq 0)
|
return ($LASTEXITCODE -eq 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
function Wait-Docker([int]$TimeoutSec = 180) {
|
function Wait-Docker([int]$TimeoutSec = 600) {
|
||||||
|
# Attend que Docker reponde. Tolere les erreurs "command not found" pendant
|
||||||
|
# les premieres iterations le temps que le PATH soit rafraichi.
|
||||||
Write-Step "Attente du demarrage de Docker Desktop (max ${TimeoutSec}s)..."
|
Write-Step "Attente du demarrage de Docker Desktop (max ${TimeoutSec}s)..."
|
||||||
|
Write-Host " Si Docker Desktop affiche un contrat de licence, acceptez-le."
|
||||||
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
||||||
|
$reportedFound = $false
|
||||||
while ((Get-Date) -lt $deadline) {
|
while ((Get-Date) -lt $deadline) {
|
||||||
docker info *>$null
|
if (Get-Command docker -ErrorAction SilentlyContinue) {
|
||||||
if ($LASTEXITCODE -eq 0) { Write-Ok "Docker repond"; return $true }
|
if (-not $reportedFound) {
|
||||||
Start-Sleep -Seconds 3
|
Write-Ok "Commande 'docker' detectee, attente du daemon..."
|
||||||
|
$reportedFound = $true
|
||||||
|
}
|
||||||
|
docker info *>$null
|
||||||
|
if ($LASTEXITCODE -eq 0) { Write-Ok "Docker repond"; return $true }
|
||||||
|
}
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
}
|
}
|
||||||
return $false
|
return $false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Update-PathFromRegistry {
|
||||||
|
# winget install ne propage pas les modifs de PATH a la session courante.
|
||||||
|
# On relit la valeur PATH depuis le registre (Machine + User) et on
|
||||||
|
# l'applique a $env:PATH pour rendre 'docker.exe' immediatement utilisable.
|
||||||
|
$machinePath = [Environment]::GetEnvironmentVariable('Path','Machine')
|
||||||
|
$userPath = [Environment]::GetEnvironmentVariable('Path','User')
|
||||||
|
$env:PATH = ($machinePath, $userPath -join ';').TrimEnd(';')
|
||||||
|
}
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# 0. Pre-requis admin
|
# 0. Verification des droits administrateur
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
if (-not (Test-Admin)) { Invoke-Elevated }
|
# On NE force PAS l'elevation automatique : on demande a l'utilisateur de
|
||||||
|
# relancer le script lui-meme avec les droits admin. C'est plus transparent
|
||||||
|
# et evite les avertissements antivirus liees a l'elevation silencieuse.
|
||||||
|
if (-not (Test-Admin)) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Ce script doit etre execute en tant qu'administrateur." -ForegroundColor Yellow
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Procedure :"
|
||||||
|
Write-Host " 1. Fermez cette fenetre PowerShell."
|
||||||
|
Write-Host " 2. Cliquez-droit sur l'icone PowerShell > 'Executer en tant qu'administrateur'."
|
||||||
|
Write-Host " 3. Naviguez a nouveau vers ce dossier et relancez : .\install.ps1"
|
||||||
|
Write-Host ""
|
||||||
|
Read-Host "Appuyez sur Entree pour quitter"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "============================================================"
|
Write-Host "============================================================"
|
||||||
@@ -106,16 +171,32 @@ if (Test-Docker) {
|
|||||||
Write-Err "winget introuvable. Installez Docker Desktop manuellement : https://www.docker.com/products/docker-desktop/"
|
Write-Err "winget introuvable. Installez Docker Desktop manuellement : https://www.docker.com/products/docker-desktop/"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
Write-Warn2 "Installation de Docker Desktop via winget..."
|
Write-Warn2 "Installation de Docker Desktop via winget (gestionnaire de paquets officiel Microsoft)..."
|
||||||
|
# On invoque winget en mode interactif (l'utilisateur voit la progression).
|
||||||
|
# Les flags --accept-* sont necessaires pour ne pas bloquer sur les CGU
|
||||||
|
# (Docker Desktop a des conditions d'utilisation a accepter).
|
||||||
winget install --id Docker.DockerDesktop -e --accept-package-agreements --accept-source-agreements
|
winget install --id Docker.DockerDesktop -e --accept-package-agreements --accept-source-agreements
|
||||||
if ($LASTEXITCODE -ne 0) { Write-Err "Echec winget"; exit 1 }
|
if ($LASTEXITCODE -ne 0) { Write-Err "Echec de l'installation Docker Desktop via winget"; exit 1 }
|
||||||
|
|
||||||
|
# winget a modifie le PATH systeme mais pas celui de la session courante.
|
||||||
|
# On le rafraichit pour que la commande 'docker' soit immediatement trouvable.
|
||||||
|
Update-PathFromRegistry
|
||||||
|
|
||||||
Write-Step "Lancement de Docker Desktop..."
|
Write-Step "Lancement de Docker Desktop..."
|
||||||
$dd = "$env:ProgramFiles\Docker\Docker\Docker Desktop.exe"
|
$dd = "$env:ProgramFiles\Docker\Docker\Docker Desktop.exe"
|
||||||
if (Test-Path $dd) { Start-Process $dd }
|
if (Test-Path $dd) { Start-Process $dd }
|
||||||
|
|
||||||
if (-not (Wait-Docker 240)) {
|
Write-Host ""
|
||||||
Write-Err "Docker n'a pas demarre. Lancez-le manuellement puis relancez ce script."
|
Write-Host " Docker Desktop demarre pour la premiere fois." -ForegroundColor Yellow
|
||||||
|
Write-Host " Au premier lancement, il affiche un contrat de licence (Subscription Service Agreement)."
|
||||||
|
Write-Host " Cliquez 'Accept' pour continuer."
|
||||||
|
Write-Host ""
|
||||||
|
Read-Host " Appuyez sur Entree une fois que Docker Desktop affiche 'Engine running' (icone baleine verte)"
|
||||||
|
|
||||||
|
if (-not (Wait-Docker 600)) {
|
||||||
|
Write-Err "Docker ne repond toujours pas apres 10 minutes."
|
||||||
|
Write-Err "Verifiez que Docker Desktop est lance et que vous avez accepte le contrat,"
|
||||||
|
Write-Err "puis relancez install.bat."
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -128,9 +209,13 @@ New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
|
|||||||
Set-Location $InstallDir
|
Set-Location $InstallDir
|
||||||
|
|
||||||
$composePath = Join-Path $InstallDir 'docker-compose.yml'
|
$composePath = Join-Path $InstallDir 'docker-compose.yml'
|
||||||
Write-Step "Telechargement de docker-compose.yml"
|
Write-Step "Telechargement de docker-compose.yml depuis le depot officiel"
|
||||||
|
Write-Host " Source : $ComposeUrl"
|
||||||
|
# Seul telechargement reseau effectue par ce script. Aucune execution de code
|
||||||
|
# distant : le fichier est uniquement enregistre sur le disque puis passe a
|
||||||
|
# 'docker compose' pour interpretation locale.
|
||||||
Invoke-WebRequest -Uri $ComposeUrl -OutFile $composePath -UseBasicParsing
|
Invoke-WebRequest -Uri $ComposeUrl -OutFile $composePath -UseBasicParsing
|
||||||
Write-Ok "docker-compose.yml recupere"
|
Write-Ok "docker-compose.yml recupere ($composePath)"
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# 4. Generation du .env
|
# 4. Generation du .env
|
||||||
@@ -160,15 +245,79 @@ if ($llmProvider -eq 'onemin' -and -not $NonInteractive) {
|
|||||||
$onemKey = Read-Host " Cle API 1min.ai"
|
$onemKey = Read-Host " Cle API 1min.ai"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# --- Mode Ollama : 3 options possibles -------------------------------------
|
||||||
|
# 1. Hote : Ollama est deja installe sur cette machine -> on configure le
|
||||||
|
# pare-feu pour que Docker puisse l'atteindre sans exposer le port.
|
||||||
|
# 2. Embarque : Ollama tourne dans un conteneur Docker dedie (profile local-ollama).
|
||||||
|
# 3. Aucun : on n'installe rien tout de suite. L'utilisateur configurera
|
||||||
|
# Ollama plus tard via la page Parametres de LoreMind.
|
||||||
|
$ollamaMode = 'embedded' # valeurs : 'host' | 'embedded' | 'none'
|
||||||
|
$ollamaBaseUrl = 'http://ollama:11434'
|
||||||
|
if ($llmProvider -eq 'ollama') {
|
||||||
|
$hasHostOllama = if ($NonInteractive) { $false } else {
|
||||||
|
$r = Read-Host " Avez-vous deja Ollama installe sur cette machine ? [o/N]"
|
||||||
|
($r -match '^(o|O|y|Y|oui|yes)$')
|
||||||
|
}
|
||||||
|
if ($hasHostOllama) {
|
||||||
|
$ollamaMode = 'host'
|
||||||
|
} else {
|
||||||
|
# Pas d'Ollama present : proposer l'installation Docker, sinon laisser
|
||||||
|
# l'utilisateur le configurer plus tard via la page Parametres.
|
||||||
|
$installViaDocker = if ($NonInteractive) { $true } else {
|
||||||
|
$r = Read-Host " Voulez-vous installer Ollama via Docker maintenant ? [O/n]"
|
||||||
|
-not ($r -match '^(n|N|no|non)$')
|
||||||
|
}
|
||||||
|
$ollamaMode = if ($installViaDocker) { 'embedded' } else { 'none' }
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($ollamaMode -eq 'host') {
|
||||||
|
$ollamaBaseUrl = 'http://host.docker.internal:11434'
|
||||||
|
# Delegue au helper dedie : configure OLLAMA_HOST=0.0.0.0 ET ajoute des
|
||||||
|
# regles Windows Firewall qui n'autorisent l'acces qu'aux conteneurs
|
||||||
|
# Docker (loopback + sous-reseaux Docker Desktop). Resultat : Ollama
|
||||||
|
# n'est pas expose au LAN ni a Internet.
|
||||||
|
$secureHelper = Join-Path $PSScriptRoot 'secure-host-ollama.ps1'
|
||||||
|
if (Test-Path $secureHelper) {
|
||||||
|
Write-Step "Configuration securisee d'Ollama hote (helper dedie)..."
|
||||||
|
try {
|
||||||
|
& $secureHelper
|
||||||
|
} catch {
|
||||||
|
Write-Warn2 "Le helper secure-host-ollama.ps1 a echoue : $($_.Exception.Message)"
|
||||||
|
Write-Warn2 "Configurez Ollama manuellement avant de continuer."
|
||||||
|
}
|
||||||
|
Write-Host ""
|
||||||
|
Read-Host "Appuyez sur Entree une fois Ollama redemarre pour continuer l'installation"
|
||||||
|
} else {
|
||||||
|
Write-Warn2 "secure-host-ollama.ps1 introuvable a cote de install.ps1."
|
||||||
|
Write-Warn2 "Telechargez-le depuis le depot et relancez-le manuellement."
|
||||||
|
}
|
||||||
|
} elseif ($ollamaMode -eq 'embedded') {
|
||||||
|
Write-Ok "Ollama sera lance dans Docker (modeles dans un volume Docker dedie)"
|
||||||
|
} else {
|
||||||
|
# Mode 'none' : on cible host.docker.internal en supposant qu'Ollama
|
||||||
|
# sera installe plus tard sur l'hote. L'utilisateur peut aussi changer
|
||||||
|
# l'URL via la page Parametres pour pointer vers un Ollama distant.
|
||||||
|
$ollamaBaseUrl = 'http://host.docker.internal:11434'
|
||||||
|
Write-Warn2 "Aucun Ollama ne sera installe pour le moment. Configurez-le plus tard via la page Parametres de LoreMind."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$llmModel = 'gemma4:e4b'
|
||||||
|
|
||||||
$autoUpdate = if ($NonInteractive) { $true } else {
|
$autoUpdate = if ($NonInteractive) { $true } else {
|
||||||
$r = Read-Host " Activer les mises a jour auto (chaque nuit a 4h) ? [O/n]"
|
$r = Read-Host " Activer les mises a jour auto (chaque nuit a 4h) ? [O/n]"
|
||||||
-not ($r -match '^(n|N|no|non)$')
|
-not ($r -match '^(n|N|no|non)$')
|
||||||
}
|
}
|
||||||
$composeProfiles = if ($autoUpdate) { 'autoupdate' } else { '' }
|
# Combinaison de profiles : autoupdate et/ou local-ollama (separes par virgule).
|
||||||
|
$profilesList = @()
|
||||||
|
if ($autoUpdate) { $profilesList += 'autoupdate' }
|
||||||
|
if ($ollamaMode -eq 'embedded' -and $llmProvider -eq 'ollama'){ $profilesList += 'local-ollama' }
|
||||||
|
$composeProfiles = $profilesList -join ','
|
||||||
|
|
||||||
$envContent = @"
|
$envContent = @"
|
||||||
# Genere par install.ps1 le $(Get-Date -Format 'yyyy-MM-dd HH:mm')
|
# Genere par install.ps1 le $(Get-Date -Format 'yyyy-MM-dd HH:mm')
|
||||||
REGISTRY=git.igmlcreation.fr
|
REGISTRY=ghcr.io
|
||||||
|
IMAGE_NAMESPACE=igmlcreation/loremind-
|
||||||
TAG=latest
|
TAG=latest
|
||||||
|
|
||||||
WEB_PORT=$WebPort
|
WEB_PORT=$WebPort
|
||||||
@@ -186,8 +335,8 @@ MINIO_USER=minioadmin
|
|||||||
MINIO_PASSWORD=$(New-RandomSecret 24)
|
MINIO_PASSWORD=$(New-RandomSecret 24)
|
||||||
|
|
||||||
LLM_PROVIDER=$llmProvider
|
LLM_PROVIDER=$llmProvider
|
||||||
OLLAMA_BASE_URL=http://host.docker.internal:11434
|
OLLAMA_BASE_URL=$ollamaBaseUrl
|
||||||
LLM_MODEL=gemma4:26b
|
LLM_MODEL=$llmModel
|
||||||
ONEMIN_API_KEY=$onemKey
|
ONEMIN_API_KEY=$onemKey
|
||||||
ONEMIN_MODEL=gpt-4o-mini
|
ONEMIN_MODEL=gpt-4o-mini
|
||||||
|
|
||||||
@@ -212,6 +361,43 @@ Write-Step "Demarrage de la stack"
|
|||||||
docker compose up -d
|
docker compose up -d
|
||||||
if ($LASTEXITCODE -ne 0) { Write-Err "Echec docker compose up"; exit 1 }
|
if ($LASTEXITCODE -ne 0) { Write-Err "Echec docker compose up"; exit 1 }
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 5b. Telechargement du modele Ollama (mode embarque uniquement)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# En mode embarque, le conteneur Ollama est prêt mais ne contient aucun modele
|
||||||
|
# par defaut. On propose de pull le modele configure tout de suite pour que
|
||||||
|
# l'utilisateur ait quelque chose a utiliser des le premier lancement.
|
||||||
|
if ($ollamaMode -eq 'embedded' -and $llmProvider -eq 'ollama') {
|
||||||
|
$pullNow = if ($NonInteractive) { $true } else {
|
||||||
|
$r = Read-Host " Telecharger le modele '$llmModel' maintenant ? (peut prendre quelques minutes) [O/n]"
|
||||||
|
-not ($r -match '^(n|N|no|non)$')
|
||||||
|
}
|
||||||
|
if ($pullNow) {
|
||||||
|
# Petite attente pour laisser le conteneur ollama finir son init.
|
||||||
|
Write-Step "Attente de la disponibilite du conteneur Ollama..."
|
||||||
|
$ollamaReady = $false
|
||||||
|
for ($i = 0; $i -lt 30; $i++) {
|
||||||
|
docker exec loremind-ollama ollama list *>$null
|
||||||
|
if ($LASTEXITCODE -eq 0) { $ollamaReady = $true; break }
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
}
|
||||||
|
if (-not $ollamaReady) {
|
||||||
|
Write-Warn2 "Le conteneur Ollama ne repond pas encore. Vous pourrez pull le modele plus tard avec :"
|
||||||
|
Write-Warn2 " docker exec -it loremind-ollama ollama pull $llmModel"
|
||||||
|
} else {
|
||||||
|
Write-Step "Telechargement du modele $llmModel (peut prendre plusieurs minutes selon votre connexion)..."
|
||||||
|
docker exec loremind-ollama ollama pull $llmModel
|
||||||
|
if ($LASTEXITCODE -eq 0) {
|
||||||
|
Write-Ok "Modele $llmModel pret a l'emploi"
|
||||||
|
} else {
|
||||||
|
Write-Warn2 "Echec du pull. Reessayez manuellement : docker exec -it loremind-ollama ollama pull $llmModel"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Write-Host " Pour le telecharger plus tard : docker exec -it loremind-ollama ollama pull $llmModel"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# 6. Recap
|
# 6. Recap
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -229,6 +415,22 @@ if ($autoUpdate) {
|
|||||||
} else {
|
} else {
|
||||||
Write-Host " Auto-update : desactive (mise a jour manuelle uniquement)"
|
Write-Host " Auto-update : desactive (mise a jour manuelle uniquement)"
|
||||||
}
|
}
|
||||||
|
if ($llmProvider -eq 'ollama') {
|
||||||
|
switch ($ollamaMode) {
|
||||||
|
'embedded' {
|
||||||
|
Write-Host " Ollama : embarque (service Docker 'ollama')" -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " IMPORTANT : telechargez un modele avant utilisation :"
|
||||||
|
Write-Host " docker exec -it loremind-ollama ollama pull $llmModel"
|
||||||
|
}
|
||||||
|
'host' {
|
||||||
|
Write-Host " Ollama : hote (configure via secure-host-ollama.ps1)"
|
||||||
|
}
|
||||||
|
'none' {
|
||||||
|
Write-Host " Ollama : non configure - a faire via Parametres dans l'app" -ForegroundColor Yellow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " Commandes utiles (depuis $InstallDir) :"
|
Write-Host " Commandes utiles (depuis $InstallDir) :"
|
||||||
Write-Host " docker compose ps # etat"
|
Write-Host " docker compose ps # etat"
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
# ==========================================================================
|
# ==========================================================================
|
||||||
# Installeur LoreMindMJ pour Linux (Debian/Ubuntu/Fedora/Arch)
|
# Installeur LoreMindMJ pour Linux (Debian/Ubuntu/Fedora/Arch)
|
||||||
# Usage :
|
# Usage :
|
||||||
# curl -fsSL https://git.igmlcreation.fr/ietm64/loremind/raw/branch/main/installers/install.sh | bash
|
# curl -fsSL https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/installers/install.sh | bash
|
||||||
# ==========================================================================
|
# ==========================================================================
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/share/loremind}"
|
INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/share/loremind}"
|
||||||
COMPOSE_URL="${COMPOSE_URL:-https://git.igmlcreation.fr/ietm64/loremind/raw/branch/main/docker-compose.yml}"
|
COMPOSE_URL="${COMPOSE_URL:-https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/docker-compose.yml}"
|
||||||
WEB_PORT="${WEB_PORT:-8081}"
|
WEB_PORT="${WEB_PORT:-8081}"
|
||||||
NON_INTERACTIVE="${NON_INTERACTIVE:-0}"
|
NON_INTERACTIVE="${NON_INTERACTIVE:-0}"
|
||||||
|
|
||||||
@@ -123,15 +123,75 @@ if [ "$LLM_PROVIDER" = "onemin" ] && [ "$NON_INTERACTIVE" != "1" ]; then
|
|||||||
ONEMIN_API_KEY="$(ask "Cle API 1min.ai" "")"
|
ONEMIN_API_KEY="$(ask "Cle API 1min.ai" "")"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# --- Mode Ollama : 3 options possibles -------------------------------------
|
||||||
|
# 1. host : Ollama deja installe sur la machine -> helper de securisation
|
||||||
|
# 2. embedded : service 'ollama' du compose (profile local-ollama)
|
||||||
|
# 3. none : aucune installation, configuration ulterieure via l'app
|
||||||
|
OLLAMA_MODE="embedded"
|
||||||
|
OLLAMA_BASE_URL_VAL="http://ollama:11434"
|
||||||
|
LLM_MODEL_VAL="gemma4:e4b"
|
||||||
|
if [ "$LLM_PROVIDER" = "ollama" ]; then
|
||||||
|
HOST_OLLAMA_REPLY="$(ask "Avez-vous deja Ollama installe sur cette machine ? [o/N]" "N")"
|
||||||
|
case "$HOST_OLLAMA_REPLY" in
|
||||||
|
o|O|y|Y|oui|yes|Oui|Yes)
|
||||||
|
OLLAMA_MODE="host"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Pas d'Ollama present : proposer l'installation Docker.
|
||||||
|
INSTALL_DOCKER_REPLY="$(ask "Voulez-vous installer Ollama via Docker maintenant ? [O/n]" "O")"
|
||||||
|
case "$INSTALL_DOCKER_REPLY" in
|
||||||
|
n|N|no|non|No|Non) OLLAMA_MODE="none" ;;
|
||||||
|
*) OLLAMA_MODE="embedded" ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
case "$OLLAMA_MODE" in
|
||||||
|
host)
|
||||||
|
OLLAMA_BASE_URL_VAL="http://host.docker.internal:11434"
|
||||||
|
# Delegue la configuration securisee au helper dedie : il fait
|
||||||
|
# ecouter Ollama uniquement sur l'IP du bridge Docker (jamais
|
||||||
|
# exposee au LAN ni a Internet) plutot que sur 0.0.0.0.
|
||||||
|
SECURE_HELPER="$(dirname -- "$0")/secure-host-ollama.sh"
|
||||||
|
if [ -f "$SECURE_HELPER" ]; then
|
||||||
|
step "Configuration securisee d'Ollama hote..."
|
||||||
|
bash "$SECURE_HELPER" || warn "Le helper secure-host-ollama.sh a echoue. Configurez Ollama manuellement."
|
||||||
|
else
|
||||||
|
warn "secure-host-ollama.sh introuvable a cote de install.sh."
|
||||||
|
warn "Telechargez-le depuis le depot et relancez : bash secure-host-ollama.sh"
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
embedded)
|
||||||
|
ok "Ollama sera lance dans Docker (modeles dans un volume Docker)"
|
||||||
|
;;
|
||||||
|
none)
|
||||||
|
# On cible host.docker.internal par defaut en supposant qu'Ollama
|
||||||
|
# sera installe plus tard sur l'hote. L'utilisateur peut aussi
|
||||||
|
# changer l'URL via la page Parametres pour un Ollama distant.
|
||||||
|
OLLAMA_BASE_URL_VAL="http://host.docker.internal:11434"
|
||||||
|
warn "Aucun Ollama ne sera installe pour le moment. Configurez-le plus tard via la page Parametres de LoreMind."
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
AUTO_UPDATE_REPLY="$(ask "Activer les mises a jour auto (chaque nuit a 4h) ? [O/n]" "O")"
|
AUTO_UPDATE_REPLY="$(ask "Activer les mises a jour auto (chaque nuit a 4h) ? [O/n]" "O")"
|
||||||
case "$AUTO_UPDATE_REPLY" in
|
case "$AUTO_UPDATE_REPLY" in
|
||||||
n|N|no|non|No|Non) COMPOSE_PROFILES="" ; AUTO_UPDATE=0 ;;
|
n|N|no|non|No|Non) AUTO_UPDATE=0 ;;
|
||||||
*) COMPOSE_PROFILES="autoupdate" ; AUTO_UPDATE=1 ;;
|
*) AUTO_UPDATE=1 ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
|
# Combinaison de profiles : autoupdate et/ou local-ollama (separes par virgule).
|
||||||
|
PROFILES_ARR=()
|
||||||
|
[ "$AUTO_UPDATE" = "1" ] && PROFILES_ARR+=("autoupdate")
|
||||||
|
if [ "$LLM_PROVIDER" = "ollama" ] && [ "$OLLAMA_MODE" = "embedded" ]; then
|
||||||
|
PROFILES_ARR+=("local-ollama")
|
||||||
|
fi
|
||||||
|
COMPOSE_PROFILES="$(IFS=,; echo "${PROFILES_ARR[*]}")"
|
||||||
|
|
||||||
cat > .env <<EOF
|
cat > .env <<EOF
|
||||||
# Genere par install.sh le $(date '+%Y-%m-%d %H:%M')
|
# Genere par install.sh le $(date '+%Y-%m-%d %H:%M')
|
||||||
REGISTRY=git.igmlcreation.fr
|
REGISTRY=ghcr.io
|
||||||
|
IMAGE_NAMESPACE=igmlcreation/loremind-
|
||||||
TAG=latest
|
TAG=latest
|
||||||
|
|
||||||
WEB_PORT=${WEB_PORT}
|
WEB_PORT=${WEB_PORT}
|
||||||
@@ -149,8 +209,8 @@ MINIO_USER=minioadmin
|
|||||||
MINIO_PASSWORD=$(rand_hex 24)
|
MINIO_PASSWORD=$(rand_hex 24)
|
||||||
|
|
||||||
LLM_PROVIDER=${LLM_PROVIDER}
|
LLM_PROVIDER=${LLM_PROVIDER}
|
||||||
OLLAMA_BASE_URL=http://host.docker.internal:11434
|
OLLAMA_BASE_URL=${OLLAMA_BASE_URL_VAL}
|
||||||
LLM_MODEL=gemma4:26b
|
LLM_MODEL=${LLM_MODEL_VAL}
|
||||||
ONEMIN_API_KEY=${ONEMIN_API_KEY}
|
ONEMIN_API_KEY=${ONEMIN_API_KEY}
|
||||||
ONEMIN_MODEL=gpt-4o-mini
|
ONEMIN_MODEL=gpt-4o-mini
|
||||||
|
|
||||||
@@ -169,6 +229,41 @@ docker compose pull
|
|||||||
step "Demarrage de la stack"
|
step "Demarrage de la stack"
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
|
|
||||||
|
# 5b. Telechargement du modele Ollama (mode embarque uniquement)
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Le conteneur Ollama est pret mais sans modele. On propose le pull tout de
|
||||||
|
# suite pour que l'utilisateur ait quelque chose a utiliser au premier lancement.
|
||||||
|
if [ "$LLM_PROVIDER" = "ollama" ] && [ "$OLLAMA_MODE" = "embedded" ]; then
|
||||||
|
PULL_REPLY="$(ask "Telecharger le modele '${LLM_MODEL_VAL}' maintenant ? (peut prendre plusieurs minutes) [O/n]" "O")"
|
||||||
|
case "$PULL_REPLY" in
|
||||||
|
n|N|no|non|No|Non)
|
||||||
|
echo " Pour le telecharger plus tard : docker exec -it loremind-ollama ollama pull ${LLM_MODEL_VAL}"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
step "Attente de la disponibilite du conteneur Ollama..."
|
||||||
|
OLLAMA_READY=0
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
if docker exec loremind-ollama ollama list >/dev/null 2>&1; then
|
||||||
|
OLLAMA_READY=1
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
if [ "$OLLAMA_READY" = "0" ]; then
|
||||||
|
warn "Le conteneur Ollama ne repond pas encore. Vous pourrez pull plus tard :"
|
||||||
|
warn " docker exec -it loremind-ollama ollama pull ${LLM_MODEL_VAL}"
|
||||||
|
else
|
||||||
|
step "Telechargement du modele ${LLM_MODEL_VAL} (peut prendre plusieurs minutes selon votre connexion)..."
|
||||||
|
if docker exec loremind-ollama ollama pull "${LLM_MODEL_VAL}"; then
|
||||||
|
ok "Modele ${LLM_MODEL_VAL} pret a l'emploi"
|
||||||
|
else
|
||||||
|
warn "Echec du pull. Reessayez : docker exec -it loremind-ollama ollama pull ${LLM_MODEL_VAL}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
# 6. Recap
|
# 6. Recap
|
||||||
URL="http://localhost:${WEB_PORT}"
|
URL="http://localhost:${WEB_PORT}"
|
||||||
echo
|
echo
|
||||||
@@ -184,6 +279,22 @@ if [ "$AUTO_UPDATE" = "1" ]; then
|
|||||||
else
|
else
|
||||||
echo " Auto-update : desactive (mise a jour manuelle uniquement)"
|
echo " Auto-update : desactive (mise a jour manuelle uniquement)"
|
||||||
fi
|
fi
|
||||||
|
if [ "$LLM_PROVIDER" = "ollama" ]; then
|
||||||
|
case "$OLLAMA_MODE" in
|
||||||
|
embedded)
|
||||||
|
echo -e " Ollama : ${c_green}embarque${c_off} (service Docker 'ollama')"
|
||||||
|
echo
|
||||||
|
echo " IMPORTANT : telechargez un modele avant utilisation :"
|
||||||
|
echo " docker exec -it loremind-ollama ollama pull ${LLM_MODEL_VAL}"
|
||||||
|
;;
|
||||||
|
host)
|
||||||
|
echo " Ollama : hote (configure via secure-host-ollama.sh)"
|
||||||
|
;;
|
||||||
|
none)
|
||||||
|
echo -e " Ollama : ${c_yellow}non configure${c_off} - a faire via Parametres dans l'app"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
echo
|
echo
|
||||||
echo " Commandes utiles (depuis $INSTALL_DIR) :"
|
echo " Commandes utiles (depuis $INSTALL_DIR) :"
|
||||||
echo " docker compose ps # etat"
|
echo " docker compose ps # etat"
|
||||||
|
|||||||
183
installers/secure-host-ollama.ps1
Normal file
183
installers/secure-host-ollama.ps1
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Configuration securisee d'Ollama hote pour LoreMindMJ (Windows).
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
But : permettre au conteneur Docker LoreMind d'atteindre l'Ollama installe
|
||||||
|
sur l'hote, SANS exposer Ollama sur le LAN ni Internet.
|
||||||
|
|
||||||
|
Strategie (specifique a Docker Desktop / WSL2 sur Windows) :
|
||||||
|
1. Ollama doit ecouter sur 0.0.0.0 (techniquement necessaire car Docker
|
||||||
|
Desktop sur Windows utilise un reseau Hyper-V / WSL2 separe).
|
||||||
|
2. On compense en ajoutant des regles Windows Firewall qui :
|
||||||
|
- BLOQUENT le port 11434 entrant par defaut sur tout profil
|
||||||
|
- AUTORISENT 11434 uniquement depuis les sous-reseaux Docker Desktop
|
||||||
|
(detectes dynamiquement) et depuis le loopback.
|
||||||
|
|
||||||
|
Resultat : Ollama est joignable par les conteneurs Docker mais
|
||||||
|
inaccessible depuis le reseau local ou Internet.
|
||||||
|
|
||||||
|
.NOTES
|
||||||
|
Ce script doit etre execute en tant qu'administrateur.
|
||||||
|
Les regles ajoutees sont prefixees par "LoreMind-Ollama-" pour
|
||||||
|
faciliter leur identification et suppression ulterieure.
|
||||||
|
|
||||||
|
.LINK
|
||||||
|
https://github.com/IGMLcreation/LoreMind
|
||||||
|
#>
|
||||||
|
|
||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
function Write-Step($msg) { Write-Host "==> $msg" -ForegroundColor Cyan }
|
||||||
|
function Write-Ok($msg) { Write-Host " OK $msg" -ForegroundColor Green }
|
||||||
|
function Write-Warn2($msg) { Write-Host " !! $msg" -ForegroundColor Yellow }
|
||||||
|
function Write-Err($msg) { Write-Host " XX $msg" -ForegroundColor Red }
|
||||||
|
|
||||||
|
# --- 1. Verification admin -------------------------------------------------
|
||||||
|
$current = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
|
$isAdmin = ([Security.Principal.WindowsPrincipal]$current).IsInRole(
|
||||||
|
[Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||||
|
if (-not $isAdmin) {
|
||||||
|
Write-Err "Ce script doit etre execute en tant qu'administrateur."
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Procedure : clic-droit sur PowerShell > 'Executer en tant qu'administrateur',"
|
||||||
|
Write-Host "puis relancez ce script."
|
||||||
|
Read-Host "Appuyez sur Entree pour quitter"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 2. Detection des sous-reseaux Docker Desktop --------------------------
|
||||||
|
Write-Step "Detection des sous-reseaux utilises par Docker Desktop..."
|
||||||
|
|
||||||
|
$dockerSubnets = @()
|
||||||
|
|
||||||
|
# Methode 1 : interroger Docker pour les bridges actifs.
|
||||||
|
try {
|
||||||
|
$networks = docker network ls --filter driver=bridge --format "{{.Name}}" 2>$null
|
||||||
|
foreach ($net in $networks) {
|
||||||
|
if ([string]::IsNullOrWhiteSpace($net)) { continue }
|
||||||
|
$subnet = docker network inspect $net -f "{{range .IPAM.Config}}{{.Subnet}}{{end}}" 2>$null
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($subnet)) {
|
||||||
|
$dockerSubnets += $subnet.Trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
Write-Warn2 "Impossible d'interroger Docker pour les sous-reseaux. Utilisation des plages par defaut."
|
||||||
|
}
|
||||||
|
|
||||||
|
# Methode 2 : interfaces vEthernet (WSL/DockerNAT) detectees par Windows.
|
||||||
|
try {
|
||||||
|
$wslInterfaces = Get-NetIPConfiguration -ErrorAction SilentlyContinue |
|
||||||
|
Where-Object { $_.InterfaceAlias -match 'vEthernet \(WSL|vEthernet \(Default Switch|vEthernet \(Docker' }
|
||||||
|
foreach ($iface in $wslInterfaces) {
|
||||||
|
$ipv4 = $iface.IPv4Address
|
||||||
|
if ($ipv4 -and $ipv4.IPAddress) {
|
||||||
|
# On deduit un /24 a partir de l'adresse de l'interface (approximation safe).
|
||||||
|
$octets = $ipv4.IPAddress.Split('.')
|
||||||
|
$subnet = "{0}.{1}.{2}.0/24" -f $octets[0], $octets[1], $octets[2]
|
||||||
|
$dockerSubnets += $subnet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { }
|
||||||
|
|
||||||
|
# Methode 3 : fallback sur les plages connues de Docker Desktop si rien detecte.
|
||||||
|
if ($dockerSubnets.Count -eq 0) {
|
||||||
|
Write-Warn2 "Aucun sous-reseau Docker detecte. Utilisation des plages par defaut Docker Desktop."
|
||||||
|
$dockerSubnets = @(
|
||||||
|
"172.16.0.0/12", # Plage standard des reseaux bridge Docker
|
||||||
|
"192.168.65.0/24" # Plage WSL2 / Docker Desktop frequente
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
# Deduplication et nettoyage.
|
||||||
|
$dockerSubnets = $dockerSubnets | Where-Object { $_ -match '^\d+\.\d+\.\d+\.\d+/\d+$' } | Select-Object -Unique
|
||||||
|
Write-Ok "Sous-reseaux autorises : $($dockerSubnets -join ', ')"
|
||||||
|
|
||||||
|
# --- 3. Variable d'environnement OLLAMA_HOST -------------------------------
|
||||||
|
Write-Step "Configuration de la variable OLLAMA_HOST..."
|
||||||
|
[Environment]::SetEnvironmentVariable('OLLAMA_HOST','0.0.0.0:11434','User')
|
||||||
|
Write-Ok "OLLAMA_HOST=0.0.0.0:11434 definie au niveau utilisateur"
|
||||||
|
|
||||||
|
# --- 4. Suppression des anciennes regles LoreMind --------------------------
|
||||||
|
Write-Step "Nettoyage des anciennes regles Windows Firewall LoreMind..."
|
||||||
|
$oldRules = Get-NetFirewallRule -DisplayName "LoreMind-Ollama-*" -ErrorAction SilentlyContinue
|
||||||
|
if ($oldRules) {
|
||||||
|
$oldRules | Remove-NetFirewallRule
|
||||||
|
Write-Ok "$($oldRules.Count) ancienne(s) regle(s) supprimee(s)"
|
||||||
|
} else {
|
||||||
|
Write-Ok "Aucune ancienne regle a supprimer"
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 5. Creation des regles --------------------------------------------------
|
||||||
|
Write-Step "Creation des regles Windows Firewall..."
|
||||||
|
|
||||||
|
# 5a. Regle de blocage par defaut (priorite la plus basse en cas de conflit :
|
||||||
|
# les regles Allow ont priorite sur les Block dans Windows Firewall, donc
|
||||||
|
# ce Block sert de filet final pour tout ce qui n'est pas explicitement
|
||||||
|
# autorise par les regles ci-dessous).
|
||||||
|
New-NetFirewallRule `
|
||||||
|
-DisplayName "LoreMind-Ollama-Block-All" `
|
||||||
|
-Description "LoreMind: bloque toute connexion entrante Ollama par defaut" `
|
||||||
|
-Direction Inbound `
|
||||||
|
-Action Block `
|
||||||
|
-Protocol TCP `
|
||||||
|
-LocalPort 11434 `
|
||||||
|
-Profile Any `
|
||||||
|
-RemoteAddress Any | Out-Null
|
||||||
|
Write-Ok "Regle Block-All (port 11434) creee"
|
||||||
|
|
||||||
|
# 5b. Regle d'autorisation : loopback uniquement.
|
||||||
|
New-NetFirewallRule `
|
||||||
|
-DisplayName "LoreMind-Ollama-Allow-Loopback" `
|
||||||
|
-Description "LoreMind: autorise Ollama depuis 127.0.0.1" `
|
||||||
|
-Direction Inbound `
|
||||||
|
-Action Allow `
|
||||||
|
-Protocol TCP `
|
||||||
|
-LocalPort 11434 `
|
||||||
|
-Profile Any `
|
||||||
|
-RemoteAddress "127.0.0.1" | Out-Null
|
||||||
|
Write-Ok "Regle Allow-Loopback creee"
|
||||||
|
|
||||||
|
# 5c. Regles d'autorisation : sous-reseaux Docker Desktop.
|
||||||
|
foreach ($subnet in $dockerSubnets) {
|
||||||
|
$safeName = "LoreMind-Ollama-Allow-Docker-$($subnet -replace '[\./]','_')"
|
||||||
|
New-NetFirewallRule `
|
||||||
|
-DisplayName $safeName `
|
||||||
|
-Description "LoreMind: autorise Ollama depuis le sous-reseau Docker $subnet" `
|
||||||
|
-Direction Inbound `
|
||||||
|
-Action Allow `
|
||||||
|
-Protocol TCP `
|
||||||
|
-LocalPort 11434 `
|
||||||
|
-Profile Any `
|
||||||
|
-RemoteAddress $subnet | Out-Null
|
||||||
|
Write-Ok "Regle Allow-Docker creee pour $subnet"
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 6. Redemarrage Ollama -------------------------------------------------
|
||||||
|
Write-Step "Redemarrage d'Ollama pour appliquer OLLAMA_HOST..."
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Pour que la variable d'environnement prenne effet, vous devez :" -ForegroundColor Yellow
|
||||||
|
Write-Host " 1. Quitter completement Ollama (icone systray > Quit Ollama)"
|
||||||
|
Write-Host " 2. Le relancer depuis le menu Demarrer"
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
# --- 7. Recap --------------------------------------------------------------
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "============================================================" -ForegroundColor Green
|
||||||
|
Write-Host " Ollama hote configure de maniere securisee" -ForegroundColor Green
|
||||||
|
Write-Host "============================================================" -ForegroundColor Green
|
||||||
|
Write-Host " Adresse d'ecoute : 0.0.0.0:11434 (toutes interfaces)"
|
||||||
|
Write-Host " Pare-feu Windows : bloque par defaut, autorise loopback + Docker"
|
||||||
|
Write-Host " Inaccessible depuis : LAN, WiFi public, Internet"
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Pour LoreMind, definissez dans le fichier .env :"
|
||||||
|
Write-Host " OLLAMA_BASE_URL=http://host.docker.internal:11434"
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Pour annuler cette configuration :"
|
||||||
|
Write-Host ' Get-NetFirewallRule -DisplayName "LoreMind-Ollama-*" | Remove-NetFirewallRule'
|
||||||
|
Write-Host ' [Environment]::SetEnvironmentVariable("OLLAMA_HOST",$null,"User")'
|
||||||
|
Write-Host ""
|
||||||
128
installers/secure-host-ollama.sh
Normal file
128
installers/secure-host-ollama.sh
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# ============================================================================
|
||||||
|
# LoreMindMJ - Configuration securisee d'Ollama hote (Linux)
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# But : permettre au conteneur Docker de LoreMind d'atteindre l'Ollama
|
||||||
|
# installe sur l'hote, SANS l'exposer sur le LAN ni Internet.
|
||||||
|
#
|
||||||
|
# Strategie : faire ecouter Ollama uniquement sur l'IP de la passerelle du
|
||||||
|
# bridge Docker (typiquement 172.17.0.1). Cette IP n'est jamais
|
||||||
|
# routee en dehors de la machine — seuls les conteneurs Docker
|
||||||
|
# peuvent l'atteindre.
|
||||||
|
#
|
||||||
|
# Ce script peut etre lance independamment de install.sh, par ex. si vous
|
||||||
|
# avez initialement choisi le mode "Ollama embarque" et changez d'avis.
|
||||||
|
#
|
||||||
|
# Usage : bash secure-host-ollama.sh
|
||||||
|
# ============================================================================
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
c_cyan='\033[1;36m'; c_green='\033[1;32m'; c_yellow='\033[1;33m'; c_red='\033[1;31m'; c_off='\033[0m'
|
||||||
|
step() { echo -e "${c_cyan}==> $*${c_off}"; }
|
||||||
|
ok() { echo -e " ${c_green}OK${c_off} $*"; }
|
||||||
|
warn() { echo -e " ${c_yellow}!!${c_off} $*"; }
|
||||||
|
err() { echo -e " ${c_red}XX${c_off} $*" >&2; }
|
||||||
|
|
||||||
|
# --- 1. Verifications prealables -------------------------------------------
|
||||||
|
if ! command -v docker >/dev/null 2>&1; then
|
||||||
|
err "Docker introuvable. Installez Docker avant de lancer ce script."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! command -v systemctl >/dev/null 2>&1; then
|
||||||
|
err "systemctl introuvable. Ce script suppose un systeme avec systemd."
|
||||||
|
err "Configurez OLLAMA_HOST manuellement selon votre init system."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! systemctl list-unit-files 2>/dev/null | grep -q '^ollama\.service'; then
|
||||||
|
err "Service systemd 'ollama' introuvable."
|
||||||
|
err "Installez Ollama via le script officiel : curl -fsSL https://ollama.com/install.sh | sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# --- 2. Detection de l'IP de la passerelle Docker --------------------------
|
||||||
|
step "Detection de l'IP du bridge Docker..."
|
||||||
|
BRIDGE_IP=""
|
||||||
|
|
||||||
|
# Methode 1 : docker network inspect (la plus fiable)
|
||||||
|
if BRIDGE_IP="$(docker network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null)"; then
|
||||||
|
if [ -n "$BRIDGE_IP" ]; then
|
||||||
|
ok "IP du bridge Docker detectee via docker network inspect : $BRIDGE_IP"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Methode 2 : interface docker0 (si docker network inspect echoue)
|
||||||
|
if [ -z "$BRIDGE_IP" ] && command -v ip >/dev/null 2>&1; then
|
||||||
|
BRIDGE_IP="$(ip -4 addr show docker0 2>/dev/null | awk '/inet / {print $2}' | cut -d/ -f1 | head -1)"
|
||||||
|
if [ -n "$BRIDGE_IP" ]; then
|
||||||
|
ok "IP du bridge Docker detectee via interface docker0 : $BRIDGE_IP"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Methode 3 : valeur par defaut (compatible avec 99% des installations)
|
||||||
|
if [ -z "$BRIDGE_IP" ]; then
|
||||||
|
BRIDGE_IP="172.17.0.1"
|
||||||
|
warn "Detection automatique echouee, utilisation de la valeur par defaut : $BRIDGE_IP"
|
||||||
|
warn "Si Docker n'a jamais ete demarre sur cette machine, lancez 'docker info' une fois pour creer le bridge."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# --- 3. Ecriture de l'override systemd -------------------------------------
|
||||||
|
step "Configuration du service systemd Ollama..."
|
||||||
|
OVERRIDE_DIR="/etc/systemd/system/ollama.service.d"
|
||||||
|
OVERRIDE_FILE="$OVERRIDE_DIR/loremind-host.conf"
|
||||||
|
|
||||||
|
sudo mkdir -p "$OVERRIDE_DIR"
|
||||||
|
sudo tee "$OVERRIDE_FILE" >/dev/null <<EOF
|
||||||
|
# Genere par LoreMind secure-host-ollama.sh
|
||||||
|
# Lie Ollama exclusivement a l'IP de la passerelle Docker.
|
||||||
|
# Consequence : Ollama est joignable depuis les conteneurs Docker
|
||||||
|
# (via host.docker.internal) mais PAS depuis le LAN ni Internet.
|
||||||
|
# Pour revenir a la configuration par defaut : sudo rm $OVERRIDE_FILE && sudo systemctl daemon-reload && sudo systemctl restart ollama
|
||||||
|
[Service]
|
||||||
|
Environment="OLLAMA_HOST=$BRIDGE_IP:11434"
|
||||||
|
EOF
|
||||||
|
ok "Override ecrit : $OVERRIDE_FILE"
|
||||||
|
|
||||||
|
# --- 4. Rechargement et redemarrage ----------------------------------------
|
||||||
|
step "Rechargement de la configuration systemd..."
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
ok "daemon-reload effectue"
|
||||||
|
|
||||||
|
step "Redemarrage du service Ollama..."
|
||||||
|
sudo systemctl restart ollama
|
||||||
|
sleep 2
|
||||||
|
if sudo systemctl is-active --quiet ollama; then
|
||||||
|
ok "Ollama redemarre et actif"
|
||||||
|
else
|
||||||
|
err "Ollama n'a pas redemarre correctement. Verifiez : sudo journalctl -u ollama -n 50"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# --- 5. Verification du binding --------------------------------------------
|
||||||
|
step "Verification : Ollama doit ecouter sur $BRIDGE_IP:11434..."
|
||||||
|
sleep 1
|
||||||
|
if command -v ss >/dev/null 2>&1; then
|
||||||
|
if ss -tln 2>/dev/null | grep -q "$BRIDGE_IP:11434"; then
|
||||||
|
ok "Ollama ecoute bien sur $BRIDGE_IP:11434"
|
||||||
|
else
|
||||||
|
warn "Verification impossible (ss n'a pas trouve le binding). Cela peut etre normal si le service vient juste de demarrer."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# --- 6. Recap --------------------------------------------------------------
|
||||||
|
echo
|
||||||
|
echo -e "${c_green}============================================================${c_off}"
|
||||||
|
echo -e "${c_green} Ollama hote configure de maniere securisee${c_off}"
|
||||||
|
echo -e "${c_green}============================================================${c_off}"
|
||||||
|
echo " Adresse d'ecoute : $BRIDGE_IP:11434"
|
||||||
|
echo " Accessible depuis : conteneurs Docker uniquement (via host.docker.internal)"
|
||||||
|
echo " Inaccessible depuis : LAN, WiFi public, Internet"
|
||||||
|
echo
|
||||||
|
echo " Pour LoreMind, definissez dans le fichier .env :"
|
||||||
|
echo " OLLAMA_BASE_URL=http://host.docker.internal:11434"
|
||||||
|
echo
|
||||||
|
echo " Pour annuler cette configuration :"
|
||||||
|
echo " sudo rm $OVERRIDE_FILE"
|
||||||
|
echo " sudo systemctl daemon-reload && sudo systemctl restart ollama"
|
||||||
|
echo
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
FROM node:20-alpine AS build
|
FROM node:20-bookworm-slim AS build
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
RUN npm install -g npm@latest
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm ci
|
RUN npm ci --include=dev --ignore-scripts --no-audit --no-fund --no-progress
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Neutralise les URLs absolues hardcodees dans les services (dette assumee :
|
# Neutralise les URLs absolues hardcodees dans les services (dette assumee :
|
||||||
|
|||||||
@@ -301,6 +301,46 @@ export async function getPageById(
|
|||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SeededNpc {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function seedNpc(
|
||||||
|
request: APIRequestContext,
|
||||||
|
opts: { campaignId: string; name?: string; markdownContent?: string | null },
|
||||||
|
): Promise<SeededNpc> {
|
||||||
|
const name = opts.name ?? `E2E NPC ${Date.now()}-${Math.floor(Math.random() * 10000)}`;
|
||||||
|
const res = await request.post('/api/npcs', {
|
||||||
|
data: {
|
||||||
|
campaignId: opts.campaignId,
|
||||||
|
name,
|
||||||
|
markdownContent: opts.markdownContent ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(res.ok(), `POST /api/npcs -> ${res.status()}`).toBeTruthy();
|
||||||
|
const n = await res.json();
|
||||||
|
return { id: n.id, name };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getNpcById(
|
||||||
|
request: APIRequestContext,
|
||||||
|
npcId: string,
|
||||||
|
): Promise<{ id: string; name: string; markdownContent: string | null; campaignId: string; order: number }> {
|
||||||
|
const res = await request.get(`/api/npcs/${npcId}`);
|
||||||
|
expect(res.ok(), `GET /api/npcs/${npcId} -> ${res.status()}`).toBeTruthy();
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getNpcsByCampaign(
|
||||||
|
request: APIRequestContext,
|
||||||
|
campaignId: string,
|
||||||
|
): Promise<Array<{ id: string; name: string }>> {
|
||||||
|
const res = await request.get(`/api/npcs/campaign/${campaignId}`);
|
||||||
|
expect(res.ok(), `GET /api/npcs/campaign -> ${res.status()}`).toBeTruthy();
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
export async function getTemplateById(
|
export async function getTemplateById(
|
||||||
request: APIRequestContext,
|
request: APIRequestContext,
|
||||||
templateId: string,
|
templateId: string,
|
||||||
|
|||||||
75
web/e2e/tests/campaign/npc-create.spec.ts
Normal file
75
web/e2e/tests/campaign/npc-create.spec.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import {
|
||||||
|
seedCampaign,
|
||||||
|
deleteCampaign,
|
||||||
|
getNpcsByCampaign,
|
||||||
|
type SeededCampaign,
|
||||||
|
} from '../../fixtures/api';
|
||||||
|
|
||||||
|
test.describe('NPC creation', () => {
|
||||||
|
let campaign: SeededCampaign;
|
||||||
|
|
||||||
|
test.beforeEach(async ({ request }) => {
|
||||||
|
campaign = await seedCampaign(request);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.afterEach(async ({ request }) => {
|
||||||
|
if (campaign?.id) await deleteCampaign(request, campaign.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('creates an NPC and redirects back to the campaign', async ({ page, request }) => {
|
||||||
|
const npcName = `Borin le forgeron ${Date.now()}`;
|
||||||
|
const markdown = '# Borin\n\n**Faction :** Clan Feuillefer\n\nNain barbu au regard perçant.';
|
||||||
|
|
||||||
|
await page.goto(`/campaigns/${campaign.id}/npcs/create`);
|
||||||
|
await expect(page.getByRole('heading', { name: /Nouveau PNJ/i })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByLabel(/Nom du PNJ/i).fill(npcName);
|
||||||
|
await page.getByLabel(/Fiche \(markdown\)/i).fill(markdown);
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /^Créer$/i }).click();
|
||||||
|
|
||||||
|
// Retour à la page campagne après création
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}$`));
|
||||||
|
|
||||||
|
// Persistance vérifiée via API
|
||||||
|
const npcs = await getNpcsByCampaign(request, campaign.id);
|
||||||
|
const created = npcs.find((n) => n.name === npcName);
|
||||||
|
expect(created).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('submit is disabled when name is empty', async ({ page }) => {
|
||||||
|
await page.goto(`/campaigns/${campaign.id}/npcs/create`);
|
||||||
|
|
||||||
|
const submit = page.getByRole('button', { name: /^Créer$/i });
|
||||||
|
await expect(submit).toBeDisabled();
|
||||||
|
|
||||||
|
await page.getByLabel(/Nom du PNJ/i).fill('Elara');
|
||||||
|
await expect(submit).toBeEnabled();
|
||||||
|
|
||||||
|
await page.getByLabel(/Nom du PNJ/i).fill(' ');
|
||||||
|
await expect(submit).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('NPC appears in the sidebar PNJ branch', async ({ page, request }) => {
|
||||||
|
const npcName = `Sidebar test ${Date.now()}`;
|
||||||
|
|
||||||
|
await page.goto(`/campaigns/${campaign.id}/npcs/create`);
|
||||||
|
await page.getByLabel(/Nom du PNJ/i).fill(npcName);
|
||||||
|
await page.getByRole('button', { name: /^Créer$/i }).click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}$`));
|
||||||
|
|
||||||
|
// Le nœud "PNJ" doit apparaître dans la sidebar avec le nouveau PNJ.
|
||||||
|
// On clique sur le nœud PNJ pour le déplier au cas où il serait fermé,
|
||||||
|
// puis on vérifie que le PNJ est listé.
|
||||||
|
const pnjNode = page.getByRole('button', { name: /^PNJ\b/ }).or(
|
||||||
|
page.locator('.tree-item', { hasText: 'PNJ' }).first(),
|
||||||
|
);
|
||||||
|
await expect(pnjNode.first()).toBeVisible();
|
||||||
|
|
||||||
|
// Vérification fallback via API : la liste contient bien le PNJ créé.
|
||||||
|
const npcs = await getNpcsByCampaign(request, campaign.id);
|
||||||
|
expect(npcs.map((n) => n.name)).toContain(npcName);
|
||||||
|
});
|
||||||
|
});
|
||||||
69
web/e2e/tests/campaign/npc-edit.spec.ts
Normal file
69
web/e2e/tests/campaign/npc-edit.spec.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import {
|
||||||
|
seedCampaign,
|
||||||
|
seedNpc,
|
||||||
|
deleteCampaign,
|
||||||
|
getNpcById,
|
||||||
|
type SeededCampaign,
|
||||||
|
type SeededNpc,
|
||||||
|
} from '../../fixtures/api';
|
||||||
|
|
||||||
|
test.describe('NPC edit', () => {
|
||||||
|
let campaign: SeededCampaign;
|
||||||
|
let npc: SeededNpc;
|
||||||
|
|
||||||
|
test.beforeEach(async ({ request }) => {
|
||||||
|
campaign = await seedCampaign(request);
|
||||||
|
npc = await seedNpc(request, {
|
||||||
|
campaignId: campaign.id,
|
||||||
|
markdownContent: '# Initial\n\nFiche de départ.',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test.afterEach(async ({ request }) => {
|
||||||
|
if (campaign?.id) await deleteCampaign(request, campaign.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('edits name + markdown content and persists via API', async ({ page, request }) => {
|
||||||
|
const newName = `${npc.name} (renommé)`;
|
||||||
|
const newMarkdown = '# Borin réécrit\n\n**Statut :** Disparu\n\nDes traces dans la neige...';
|
||||||
|
|
||||||
|
await page.goto(`/campaigns/${campaign.id}/npcs/${npc.id}/edit`);
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: /Éditer le PNJ/i })).toBeVisible();
|
||||||
|
await expect(page.getByLabel(/Nom du PNJ/i)).toHaveValue(npc.name);
|
||||||
|
|
||||||
|
await page.getByLabel(/Nom du PNJ/i).fill(newName);
|
||||||
|
await page.getByLabel(/Fiche \(markdown\)/i).fill(newMarkdown);
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /^Enregistrer$/i }).click();
|
||||||
|
|
||||||
|
// Retour à la campagne après save
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/campaigns/${campaign.id}$`));
|
||||||
|
|
||||||
|
const persisted = await getNpcById(request, npc.id);
|
||||||
|
expect(persisted.name).toBe(newName);
|
||||||
|
expect(persisted.markdownContent).toBe(newMarkdown);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('save button is disabled when name is cleared', async ({ page }) => {
|
||||||
|
await page.goto(`/campaigns/${campaign.id}/npcs/${npc.id}/edit`);
|
||||||
|
|
||||||
|
const nameField = page.getByLabel(/Nom du PNJ/i);
|
||||||
|
const saveBtn = page.getByRole('button', { name: /^Enregistrer$/i });
|
||||||
|
|
||||||
|
await expect(saveBtn).toBeEnabled();
|
||||||
|
await nameField.fill('');
|
||||||
|
await expect(saveBtn).toBeDisabled();
|
||||||
|
await nameField.fill('OK');
|
||||||
|
await expect(saveBtn).toBeEnabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Assistant IA button is visible in edit mode', async ({ page }) => {
|
||||||
|
// Vérifie l'intégration drawer chat IA — symétrique aux PJ.
|
||||||
|
// Note : le drawer lui-même nécessite le Brain Python en route, donc
|
||||||
|
// on ne teste que la présence du bouton trigger.
|
||||||
|
await page.goto(`/campaigns/${campaign.id}/npcs/${npc.id}/edit`);
|
||||||
|
await expect(page.getByRole('button', { name: /Assistant IA/i })).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -20,6 +20,24 @@ server {
|
|||||||
proxy_send_timeout 300s;
|
proxy_send_timeout 300s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# index.html : toujours revalide. Empeche un navigateur qui a precedemment
|
||||||
|
# visite une autre instance LoreMind (demo en ligne, dev local, etc.) de
|
||||||
|
# servir une vieille version cachee a la place de l'app reelle.
|
||||||
|
location = /index.html {
|
||||||
|
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
|
||||||
|
add_header Pragma "no-cache" always;
|
||||||
|
expires 0;
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Assets Angular avec hash dans le nom (main.<hash>.js, etc.) :
|
||||||
|
# immuables, peuvent etre caches longtemps.
|
||||||
|
location ~* \.(?:js|css|woff2?|ttf|svg|png|jpg|jpeg|webp|ico)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable" always;
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
try_files $uri $uri/ /index.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
|
|||||||
4
web/package-lock.json
generated
4
web/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "0.6.6",
|
"version": "0.8.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "0.6.6",
|
"version": "0.8.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular/animations": "^17.0.0",
|
"@angular/animations": "^17.0.0",
|
||||||
"@angular/common": "^17.0.0",
|
"@angular/common": "^17.0.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "0.6.6",
|
"version": "0.8.0",
|
||||||
"description": "LoreMind Frontend - Angular",
|
"description": "LoreMind Frontend - Angular",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"ng": "ng",
|
"ng": "ng",
|
||||||
|
|||||||
@@ -15,19 +15,21 @@ export const routes: Routes = [
|
|||||||
{ path: 'lore/:loreId/pages/:pageId', loadComponent: () => import('./lore/page-view/page-view.component').then(m => m.PageViewComponent) },
|
{ path: 'lore/:loreId/pages/:pageId', loadComponent: () => import('./lore/page-view/page-view.component').then(m => m.PageViewComponent) },
|
||||||
{ path: 'lore/:loreId/pages/:pageId/edit', loadComponent: () => import('./lore/page-edit/page-edit.component').then(m => m.PageEditComponent) },
|
{ path: 'lore/:loreId/pages/:pageId/edit', loadComponent: () => import('./lore/page-edit/page-edit.component').then(m => m.PageEditComponent) },
|
||||||
{ path: 'campaigns', loadComponent: () => import('./campaigns/campaigns.component').then(m => m.CampaignsComponent) },
|
{ path: 'campaigns', loadComponent: () => import('./campaigns/campaigns.component').then(m => m.CampaignsComponent) },
|
||||||
{ path: 'campaigns/:id', loadComponent: () => import('./campaigns/campaign-detail/campaign-detail.component').then(m => m.CampaignDetailComponent) },
|
{ path: 'campaigns/:id', loadComponent: () => import('./campaigns/campaign/campaign-detail/campaign-detail.component').then(m => m.CampaignDetailComponent) },
|
||||||
{ path: 'campaigns/:campaignId/characters/create', loadComponent: () => import('./campaigns/character-edit/character-edit.component').then(m => m.CharacterEditComponent) },
|
{ path: 'campaigns/:campaignId/characters/create', loadComponent: () => import('./campaigns/character/character-edit/character-edit.component').then(m => m.CharacterEditComponent) },
|
||||||
{ path: 'campaigns/:campaignId/characters/:characterId/edit', loadComponent: () => import('./campaigns/character-edit/character-edit.component').then(m => m.CharacterEditComponent) },
|
{ path: 'campaigns/:campaignId/characters/:characterId/edit', loadComponent: () => import('./campaigns/character/character-edit/character-edit.component').then(m => m.CharacterEditComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/create', loadComponent: () => import('./campaigns/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
|
{ path: 'campaigns/:campaignId/npcs/create', loadComponent: () => import('./campaigns/npc/npc-edit/npc-edit.component').then(m => m.NpcEditComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId', loadComponent: () => import('./campaigns/arc-view/arc-view.component').then(m => m.ArcViewComponent) },
|
{ path: 'campaigns/:campaignId/npcs/:npcId/edit', loadComponent: () => import('./campaigns/npc/npc-edit/npc-edit.component').then(m => m.NpcEditComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/edit', loadComponent: () => import('./campaigns/arc-edit/arc-edit.component').then(m => m.ArcEditComponent) },
|
{ path: 'campaigns/:campaignId/arcs/create', loadComponent: () => import('./campaigns/arc/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/create', loadComponent: () => import('./campaigns/chapter-create/chapter-create.component').then(m => m.ChapterCreateComponent) },
|
{ path: 'campaigns/:campaignId/arcs/:arcId', loadComponent: () => import('./campaigns/arc/arc-view/arc-view.component').then(m => m.ArcViewComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId', loadComponent: () => import('./campaigns/chapter-view/chapter-view.component').then(m => m.ChapterViewComponent) },
|
{ path: 'campaigns/:campaignId/arcs/:arcId/edit', loadComponent: () => import('./campaigns/arc/arc-edit/arc-edit.component').then(m => m.ArcEditComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/graph', loadComponent: () => import('./campaigns/chapter-graph/chapter-graph.component').then(m => m.ChapterGraphComponent) },
|
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/create', loadComponent: () => import('./campaigns/chapter/chapter-create/chapter-create.component').then(m => m.ChapterCreateComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/edit', loadComponent: () => import('./campaigns/chapter-edit/chapter-edit.component').then(m => m.ChapterEditComponent) },
|
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId', loadComponent: () => import('./campaigns/chapter/chapter-view/chapter-view.component').then(m => m.ChapterViewComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/scenes/create', loadComponent: () => import('./campaigns/scene-create/scene-create.component').then(m => m.SceneCreateComponent) },
|
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/graph', loadComponent: () => import('./campaigns/chapter/chapter-graph/chapter-graph.component').then(m => m.ChapterGraphComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/scenes/:sceneId', loadComponent: () => import('./campaigns/scene-view/scene-view.component').then(m => m.SceneViewComponent) },
|
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/edit', loadComponent: () => import('./campaigns/chapter/chapter-edit/chapter-edit.component').then(m => m.ChapterEditComponent) },
|
||||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/scenes/:sceneId/edit', loadComponent: () => import('./campaigns/scene-edit/scene-edit.component').then(m => m.SceneEditComponent) },
|
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/scenes/create', loadComponent: () => import('./campaigns/scene/scene-create/scene-create.component').then(m => m.SceneCreateComponent) },
|
||||||
|
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/scenes/:sceneId', loadComponent: () => import('./campaigns/scene/scene-view/scene-view.component').then(m => m.SceneViewComponent) },
|
||||||
|
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/:chapterId/scenes/:sceneId/edit', loadComponent: () => import('./campaigns/scene/scene-edit/scene-edit.component').then(m => m.SceneEditComponent) },
|
||||||
{ path: 'game-systems', loadComponent: () => import('./game-systems/game-systems.component').then(m => m.GameSystemsComponent) },
|
{ path: 'game-systems', loadComponent: () => import('./game-systems/game-systems.component').then(m => m.GameSystemsComponent) },
|
||||||
{ path: 'game-systems/create', loadComponent: () => import('./game-systems/game-system-edit/game-system-edit.component').then(m => m.GameSystemEditComponent) },
|
{ path: 'game-systems/create', loadComponent: () => import('./game-systems/game-system-edit/game-system-edit.component').then(m => m.GameSystemEditComponent) },
|
||||||
{ path: 'game-systems/:id/edit', loadComponent: () => import('./game-systems/game-system-edit/game-system-edit.component').then(m => m.GameSystemEditComponent) },
|
{ path: 'game-systems/:id/edit', loadComponent: () => import('./game-systems/game-system-edit/game-system-edit.component').then(m => m.GameSystemEditComponent) },
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angula
|
|||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { forkJoin } from 'rxjs';
|
import { forkJoin } from 'rxjs';
|
||||||
import { LucideAngularModule, BookOpen } from 'lucide-angular';
|
import { LucideAngularModule, BookOpen } from 'lucide-angular';
|
||||||
import { CampaignService } from '../../services/campaign.service';
|
import { CampaignService } from '../../../services/campaign.service';
|
||||||
import { CharacterService } from '../../services/character.service';
|
import { CharacterService } from '../../../services/character.service';
|
||||||
import { LayoutService, GlobalItem } from '../../services/layout.service';
|
import { NpcService } from '../../../services/npc.service';
|
||||||
import { Campaign } from '../../services/campaign.model';
|
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||||
import { loadCampaignTreeData, buildCampaignTree } from '../campaign-tree.helper';
|
import { Campaign } from '../../../services/campaign.model';
|
||||||
import { IconPickerComponent } from '../../shared/icon-picker/icon-picker.component';
|
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||||
import { CAMPAIGN_ICON_OPTIONS } from '../campaign-icons';
|
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||||
|
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Écran de création d'un nouvel Arc narratif (contexte Campagne).
|
* Écran de création d'un nouvel Arc narratif (contexte Campagne).
|
||||||
@@ -39,6 +40,7 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
|||||||
private router: Router,
|
private router: Router,
|
||||||
private campaignService: CampaignService,
|
private campaignService: CampaignService,
|
||||||
private characterService: CharacterService,
|
private characterService: CharacterService,
|
||||||
|
private npcService: NpcService,
|
||||||
private layoutService: LayoutService
|
private layoutService: LayoutService
|
||||||
) {
|
) {
|
||||||
this.form = this.fb.group({
|
this.form = this.fb.group({
|
||||||
@@ -56,7 +58,7 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
|||||||
forkJoin({
|
forkJoin({
|
||||||
campaign: this.campaignService.getCampaignById(this.campaignId),
|
campaign: this.campaignService.getCampaignById(this.campaignId),
|
||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService)
|
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService, this.npcService)
|
||||||
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
||||||
this.existingArcCount = treeData.arcs.length;
|
this.existingArcCount = treeData.arcs.length;
|
||||||
|
|
||||||
@@ -87,7 +89,7 @@ export class ArcCreateComponent implements OnInit, OnDestroy {
|
|||||||
order: this.existingArcCount + 1,
|
order: this.existingArcCount + 1,
|
||||||
icon: this.selectedIcon
|
icon: this.selectedIcon
|
||||||
}).subscribe({
|
}).subscribe({
|
||||||
next: (created) => this.router.navigate(['/campaigns', this.campaignId, 'arcs', created.id]),
|
next: (created) => this.router.navigate(['/campaigns', this.campaignId, 'arcs', created.id, 'edit']),
|
||||||
error: () => console.error('Erreur lors de la création de l\'arc')
|
error: () => console.error('Erreur lors de la création de l\'arc')
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -5,19 +5,20 @@ import { ActivatedRoute, Router } from '@angular/router';
|
|||||||
import { forkJoin, of } from 'rxjs';
|
import { forkJoin, of } from 'rxjs';
|
||||||
import { switchMap } from 'rxjs/operators';
|
import { switchMap } from 'rxjs/operators';
|
||||||
import { LucideAngularModule, Trash2, Sparkles } from 'lucide-angular';
|
import { LucideAngularModule, Trash2, Sparkles } from 'lucide-angular';
|
||||||
import { CampaignService } from '../../services/campaign.service';
|
import { CampaignService } from '../../../services/campaign.service';
|
||||||
import { CharacterService } from '../../services/character.service';
|
import { CharacterService } from '../../../services/character.service';
|
||||||
import { PageService } from '../../services/page.service';
|
import { NpcService } from '../../../services/npc.service';
|
||||||
import { LayoutService, GlobalItem } from '../../services/layout.service';
|
import { PageService } from '../../../services/page.service';
|
||||||
import { PageTitleService } from '../../services/page-title.service';
|
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||||
import { Campaign, Arc } from '../../services/campaign.model';
|
import { PageTitleService } from '../../../services/page-title.service';
|
||||||
import { Page } from '../../services/page.model';
|
import { Campaign, Arc } from '../../../services/campaign.model';
|
||||||
import { loadCampaignTreeData, buildCampaignTree } from '../campaign-tree.helper';
|
import { Page } from '../../../services/page.model';
|
||||||
import { LoreLinkPickerComponent } from '../../shared/lore-link-picker/lore-link-picker.component';
|
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||||
import { AiChatDrawerComponent } from '../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
|
||||||
import { ImageGalleryComponent } from '../../shared/image-gallery/image-gallery.component';
|
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
||||||
import { IconPickerComponent } from '../../shared/icon-picker/icon-picker.component';
|
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||||
import { CAMPAIGN_ICON_OPTIONS } from '../campaign-icons';
|
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||||
|
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Écran de détail/modification d'un Arc.
|
* Écran de détail/modification d'un Arc.
|
||||||
@@ -74,6 +75,7 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
|||||||
private router: Router,
|
private router: Router,
|
||||||
private campaignService: CampaignService,
|
private campaignService: CampaignService,
|
||||||
private characterService: CharacterService,
|
private characterService: CharacterService,
|
||||||
|
private npcService: NpcService,
|
||||||
private pageService: PageService,
|
private pageService: PageService,
|
||||||
private layoutService: LayoutService,
|
private layoutService: LayoutService,
|
||||||
private pageTitleService: PageTitleService
|
private pageTitleService: PageTitleService
|
||||||
@@ -111,7 +113,7 @@ export class ArcEditComponent implements OnInit, OnDestroy {
|
|||||||
campaign: this.campaignService.getCampaignById(this.campaignId),
|
campaign: this.campaignService.getCampaignById(this.campaignId),
|
||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
arc: this.campaignService.getArcById(this.arcId),
|
arc: this.campaignService.getArcById(this.arcId),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService)
|
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService, this.npcService)
|
||||||
}).pipe(
|
}).pipe(
|
||||||
switchMap(data => {
|
switchMap(data => {
|
||||||
const lid = data.campaign.loreId ?? null;
|
const lid = data.campaign.loreId ?? null;
|
||||||
@@ -4,16 +4,17 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
|||||||
import { forkJoin, of } from 'rxjs';
|
import { forkJoin, of } from 'rxjs';
|
||||||
import { switchMap } from 'rxjs/operators';
|
import { switchMap } from 'rxjs/operators';
|
||||||
import { LucideAngularModule, Pencil, Trash2 } from 'lucide-angular';
|
import { LucideAngularModule, Pencil, Trash2 } from 'lucide-angular';
|
||||||
import { resolveCampaignIcon } from '../campaign-icons';
|
import { resolveCampaignIcon } from '../../campaign-icons';
|
||||||
import { CampaignService } from '../../services/campaign.service';
|
import { CampaignService } from '../../../services/campaign.service';
|
||||||
import { CharacterService } from '../../services/character.service';
|
import { CharacterService } from '../../../services/character.service';
|
||||||
import { PageService } from '../../services/page.service';
|
import { NpcService } from '../../../services/npc.service';
|
||||||
import { LayoutService, GlobalItem } from '../../services/layout.service';
|
import { PageService } from '../../../services/page.service';
|
||||||
import { PageTitleService } from '../../services/page-title.service';
|
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||||
import { Campaign, Arc } from '../../services/campaign.model';
|
import { PageTitleService } from '../../../services/page-title.service';
|
||||||
import { Page } from '../../services/page.model';
|
import { Campaign, Arc } from '../../../services/campaign.model';
|
||||||
import { loadCampaignTreeData, buildCampaignTree } from '../campaign-tree.helper';
|
import { Page } from '../../../services/page.model';
|
||||||
import { ImageGalleryComponent } from '../../shared/image-gallery/image-gallery.component';
|
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||||
|
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Écran de consultation d'un Arc narratif (lecture seule).
|
* Écran de consultation d'un Arc narratif (lecture seule).
|
||||||
@@ -46,6 +47,7 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
|||||||
private router: Router,
|
private router: Router,
|
||||||
private campaignService: CampaignService,
|
private campaignService: CampaignService,
|
||||||
private characterService: CharacterService,
|
private characterService: CharacterService,
|
||||||
|
private npcService: NpcService,
|
||||||
private pageService: PageService,
|
private pageService: PageService,
|
||||||
private layoutService: LayoutService,
|
private layoutService: LayoutService,
|
||||||
private pageTitleService: PageTitleService
|
private pageTitleService: PageTitleService
|
||||||
@@ -68,7 +70,7 @@ export class ArcViewComponent implements OnInit, OnDestroy {
|
|||||||
campaign: this.campaignService.getCampaignById(this.campaignId),
|
campaign: this.campaignService.getCampaignById(this.campaignId),
|
||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
arc: this.campaignService.getArcById(this.arcId),
|
arc: this.campaignService.getArcById(this.arcId),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService)
|
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService, this.npcService)
|
||||||
}).pipe(
|
}).pipe(
|
||||||
switchMap(data => {
|
switchMap(data => {
|
||||||
const lid = data.campaign.loreId ?? null;
|
const lid = data.campaign.loreId ?? null;
|
||||||
@@ -2,9 +2,11 @@ import { Observable, forkJoin, of } from 'rxjs';
|
|||||||
import { switchMap, map } from 'rxjs/operators';
|
import { switchMap, map } from 'rxjs/operators';
|
||||||
import { CampaignService } from '../services/campaign.service';
|
import { CampaignService } from '../services/campaign.service';
|
||||||
import { CharacterService } from '../services/character.service';
|
import { CharacterService } from '../services/character.service';
|
||||||
|
import { NpcService } from '../services/npc.service';
|
||||||
import { TreeItem } from '../services/layout.service';
|
import { TreeItem } from '../services/layout.service';
|
||||||
import { Arc, Chapter, Scene } from '../services/campaign.model';
|
import { Arc, Chapter, Scene } from '../services/campaign.model';
|
||||||
import { Character } from '../services/character.model';
|
import { Character } from '../services/character.model';
|
||||||
|
import { Npc } from '../services/npc.model';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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)
|
||||||
@@ -19,20 +21,23 @@ export interface CampaignTreeData {
|
|||||||
chaptersByArc: Record<string, Chapter[]>;
|
chaptersByArc: Record<string, Chapter[]>;
|
||||||
scenesByChapter: Record<string, Scene[]>;
|
scenesByChapter: Record<string, Scene[]>;
|
||||||
characters: Character[];
|
characters: Character[];
|
||||||
|
npcs: Npc[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadCampaignTreeData(
|
export function loadCampaignTreeData(
|
||||||
service: CampaignService,
|
service: CampaignService,
|
||||||
campaignId: string,
|
campaignId: string,
|
||||||
characterService: CharacterService
|
characterService: CharacterService,
|
||||||
|
npcService: NpcService
|
||||||
): Observable<CampaignTreeData> {
|
): Observable<CampaignTreeData> {
|
||||||
return forkJoin({
|
return forkJoin({
|
||||||
arcs: service.getArcs(campaignId),
|
arcs: service.getArcs(campaignId),
|
||||||
characters: characterService.getByCampaign(campaignId)
|
characters: characterService.getByCampaign(campaignId),
|
||||||
|
npcs: npcService.getByCampaign(campaignId)
|
||||||
}).pipe(
|
}).pipe(
|
||||||
switchMap(({ arcs, characters }) => {
|
switchMap(({ arcs, characters, npcs }) => {
|
||||||
if (arcs.length === 0) {
|
if (arcs.length === 0) {
|
||||||
return of({ arcs, chaptersByArc: {}, scenesByChapter: {}, characters });
|
return of({ arcs, chaptersByArc: {}, scenesByChapter: {}, characters, npcs });
|
||||||
}
|
}
|
||||||
const chapterCalls = arcs.map(a =>
|
const chapterCalls = arcs.map(a =>
|
||||||
service.getChapters(a.id!).pipe(map(chapters => ({ arcId: a.id!, chapters })))
|
service.getChapters(a.id!).pipe(map(chapters => ({ arcId: a.id!, chapters })))
|
||||||
@@ -47,7 +52,7 @@ export function loadCampaignTreeData(
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (allChapters.length === 0) {
|
if (allChapters.length === 0) {
|
||||||
return of({ arcs, chaptersByArc, scenesByChapter: {}, characters });
|
return of({ arcs, chaptersByArc, scenesByChapter: {}, characters, npcs });
|
||||||
}
|
}
|
||||||
const sceneCalls = allChapters.map(c =>
|
const sceneCalls = allChapters.map(c =>
|
||||||
service.getScenes(c.id!).pipe(map(scenes => ({ chapterId: c.id!, scenes })))
|
service.getScenes(c.id!).pipe(map(scenes => ({ chapterId: c.id!, scenes })))
|
||||||
@@ -56,7 +61,7 @@ export function loadCampaignTreeData(
|
|||||||
map(sceneResults => {
|
map(sceneResults => {
|
||||||
const scenesByChapter: Record<string, Scene[]> = {};
|
const scenesByChapter: Record<string, Scene[]> = {};
|
||||||
sceneResults.forEach(r => { scenesByChapter[r.chapterId] = r.scenes; });
|
sceneResults.forEach(r => { scenesByChapter[r.chapterId] = r.scenes; });
|
||||||
return { arcs, chaptersByArc, scenesByChapter, characters };
|
return { arcs, chaptersByArc, scenesByChapter, characters, npcs };
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@@ -83,13 +88,13 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
|||||||
|
|
||||||
const charactersNode: TreeItem = {
|
const charactersNode: TreeItem = {
|
||||||
id: 'characters-root',
|
id: 'characters-root',
|
||||||
label: 'Personnages',
|
label: 'PJ',
|
||||||
iconKey: 'users',
|
iconKey: 'users',
|
||||||
children: characterItems,
|
children: characterItems,
|
||||||
meta: characterItems.length ? String(characterItems.length) : undefined,
|
meta: characterItems.length ? String(characterItems.length) : undefined,
|
||||||
sectionHeaderBefore: 'Personnages',
|
sectionHeaderBefore: 'Personnages',
|
||||||
// Note : si pas d'arcs, le filet au-dessus de "Personnages" est masqué par CSS
|
// Note : le section header "Personnages" est porté par le premier nœud (PJ).
|
||||||
// (:first-child), ce qui est voulu — on ne veut pas de ligne seule en haut.
|
// Le filet au-dessus est masqué par CSS si c'est le tout premier item de la sidebar.
|
||||||
createActions: [{
|
createActions: [{
|
||||||
id: 'new-character',
|
id: 'new-character',
|
||||||
label: 'Nouveau PJ',
|
label: 'Nouveau PJ',
|
||||||
@@ -98,6 +103,28 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
|||||||
}]
|
}]
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sortedNpcs = [...data.npcs].sort(byName);
|
||||||
|
const npcItems: TreeItem[] = sortedNpcs.map(n => ({
|
||||||
|
id: `npc-${n.id}`,
|
||||||
|
label: n.name,
|
||||||
|
route: `/campaigns/${campaignId}/npcs/${n.id}/edit`
|
||||||
|
}));
|
||||||
|
|
||||||
|
const npcsNode: TreeItem = {
|
||||||
|
id: 'npcs-root',
|
||||||
|
label: 'PNJ',
|
||||||
|
iconKey: 'c-drama',
|
||||||
|
children: npcItems,
|
||||||
|
meta: npcItems.length ? String(npcItems.length) : undefined,
|
||||||
|
// Pas de sectionHeaderBefore : on reste sous le header "Personnages" du nœud PJ.
|
||||||
|
createActions: [{
|
||||||
|
id: 'new-npc',
|
||||||
|
label: 'Nouveau PNJ',
|
||||||
|
route: `/campaigns/${campaignId}/npcs/create`,
|
||||||
|
actionIcon: 'plus'
|
||||||
|
}]
|
||||||
|
};
|
||||||
|
|
||||||
const sortedArcs = [...data.arcs].sort(byName);
|
const sortedArcs = [...data.arcs].sort(byName);
|
||||||
|
|
||||||
const arcNodes: TreeItem[] = sortedArcs.map((arc, idx) => {
|
const arcNodes: TreeItem[] = sortedArcs.map((arc, idx) => {
|
||||||
@@ -143,5 +170,5 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return [...arcNodes, charactersNode];
|
return [...arcNodes, charactersNode, npcsNode];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ import { Component, EventEmitter, OnInit, Output } from '@angular/core';
|
|||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||||
import { LucideAngularModule, BookCopy, X } from 'lucide-angular';
|
import { LucideAngularModule, BookCopy, X } from 'lucide-angular';
|
||||||
import { LoreService } from '../../services/lore.service';
|
import { LoreService } from '../../../services/lore.service';
|
||||||
import { Lore } from '../../services/lore.model';
|
import { Lore } from '../../../services/lore.model';
|
||||||
import { GameSystemService } from '../../services/game-system.service';
|
import { GameSystemService } from '../../../services/game-system.service';
|
||||||
import { GameSystem } from '../../services/game-system.model';
|
import { GameSystem } from '../../../services/game-system.model';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Payload émis vers le parent à la création d'une campagne.
|
* Payload émis vers le parent à la création d'une campagne.
|
||||||
@@ -70,32 +70,75 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section class="detail-section characters-section" *ngIf="!editing">
|
<section class="detail-section personas-section" *ngIf="!editing">
|
||||||
<div class="section-header">
|
<div class="section-header">
|
||||||
<h2>Personnages joueurs</h2>
|
<h2>Personnages</h2>
|
||||||
<button class="btn-add" (click)="createCharacter()">
|
|
||||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
|
||||||
Nouveau PJ
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="characters-grid" *ngIf="characters.length > 0">
|
<!-- Sous-section : Personnages joueurs (PJ) -->
|
||||||
<div class="character-card" *ngFor="let character of characters" (click)="editCharacter(character)">
|
<div class="persona-subsection">
|
||||||
<lucide-icon [img]="User" [size]="20" class="character-icon"></lucide-icon>
|
<div class="subsection-header">
|
||||||
<div class="character-info">
|
<h3>
|
||||||
<span class="character-name">{{ character.name }}</span>
|
<lucide-icon [img]="User" [size]="16"></lucide-icon>
|
||||||
<span class="character-snippet">{{ characterSnippet(character) }}</span>
|
Personnages joueurs
|
||||||
|
<span class="count-badge" *ngIf="characters.length > 0">{{ characters.length }}</span>
|
||||||
|
</h3>
|
||||||
|
<button class="btn-add" (click)="createCharacter()">
|
||||||
|
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||||
|
Nouveau PJ
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="characters-grid" *ngIf="characters.length > 0">
|
||||||
|
<div class="character-card" *ngFor="let character of characters" (click)="editCharacter(character)">
|
||||||
|
<lucide-icon [img]="User" [size]="20" class="character-icon"></lucide-icon>
|
||||||
|
<div class="character-info">
|
||||||
|
<span class="character-name">{{ character.name }}</span>
|
||||||
|
<span class="character-snippet">{{ personaSnippet(character) }}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="empty-state empty-state--compact" *ngIf="characters.length === 0">
|
||||||
|
<p>Aucun personnage joueur pour le moment.</p>
|
||||||
|
<button class="btn-add-first" (click)="createCharacter()">
|
||||||
|
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||||
|
Créer votre premier PJ
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="empty-state" *ngIf="characters.length === 0">
|
<!-- Sous-section : Personnages non-joueurs (PNJ) -->
|
||||||
<lucide-icon [img]="User" [size]="40" class="empty-icon"></lucide-icon>
|
<div class="persona-subsection">
|
||||||
<p>Aucun personnage joueur pour le moment.</p>
|
<div class="subsection-header">
|
||||||
<button class="btn-add-first" (click)="createCharacter()">
|
<h3>
|
||||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
<lucide-icon [img]="Drama" [size]="16"></lucide-icon>
|
||||||
Créer votre premier PJ
|
Personnages non-joueurs
|
||||||
</button>
|
<span class="count-badge" *ngIf="npcs.length > 0">{{ npcs.length }}</span>
|
||||||
|
</h3>
|
||||||
|
<button class="btn-add" (click)="createNpc()">
|
||||||
|
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||||
|
Nouveau PNJ
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="characters-grid" *ngIf="npcs.length > 0">
|
||||||
|
<div class="character-card" *ngFor="let npc of npcs" (click)="editNpc(npc)">
|
||||||
|
<lucide-icon [img]="Drama" [size]="20" class="character-icon character-icon--npc"></lucide-icon>
|
||||||
|
<div class="character-info">
|
||||||
|
<span class="character-name">{{ npc.name }}</span>
|
||||||
|
<span class="character-snippet">{{ personaSnippet(npc) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="empty-state empty-state--compact" *ngIf="npcs.length === 0">
|
||||||
|
<p>Aucun PNJ pour le moment.</p>
|
||||||
|
<button class="btn-add-first" (click)="createNpc()">
|
||||||
|
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||||
|
Créer votre premier PNJ
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -197,6 +197,54 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Encart "Personnages" qui regroupe les sous-sections PJ et PNJ.
|
||||||
|
.personas-section {
|
||||||
|
|
||||||
|
.persona-subsection + .persona-subsection {
|
||||||
|
margin-top: 1.75rem;
|
||||||
|
padding-top: 1.5rem;
|
||||||
|
border-top: 1px solid #1f2937;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.subsection-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
color: #d1d5db;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
margin: 0;
|
||||||
|
|
||||||
|
lucide-icon { color: #a78bfa; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.count-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 1.4rem;
|
||||||
|
height: 1.4rem;
|
||||||
|
padding: 0 0.45rem;
|
||||||
|
background: #1f2937;
|
||||||
|
color: #a78bfa;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0;
|
||||||
|
text-transform: none;
|
||||||
|
margin-left: 0.25rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.characters-grid {
|
.characters-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||||||
@@ -243,8 +291,23 @@
|
|||||||
|
|
||||||
.empty-icon { color: #374151; }
|
.empty-icon { color: #374151; }
|
||||||
p { font-size: 0.95rem; }
|
p { font-size: 0.95rem; }
|
||||||
|
|
||||||
|
// Variante condensée pour les sous-sections PJ/PNJ — pas besoin du
|
||||||
|
// padding vertical massif quand l'encart parent en porte déjà.
|
||||||
|
&.empty-state--compact {
|
||||||
|
padding: 1.5rem 1rem;
|
||||||
|
gap: 0.75rem;
|
||||||
|
|
||||||
|
p {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Variante d'icône pour les cartes PNJ (rouge-violet pour différencier des PJ).
|
||||||
|
.character-icon--npc { color: #c084fc !important; }
|
||||||
|
|
||||||
.btn-add-first {
|
.btn-add-first {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -2,21 +2,23 @@ import { Component, OnInit, OnDestroy } from '@angular/core';
|
|||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { ActivatedRoute } from '@angular/router';
|
import { ActivatedRoute } from '@angular/router';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, User, Dices } from 'lucide-angular';
|
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, User, Dices, Drama } from 'lucide-angular';
|
||||||
import { Router, RouterLink } from '@angular/router';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { forkJoin, of } from 'rxjs';
|
import { forkJoin, of } from 'rxjs';
|
||||||
import { catchError, switchMap, filter, map } from 'rxjs/operators';
|
import { catchError, switchMap, filter, map } from 'rxjs/operators';
|
||||||
import { CampaignService } from '../../services/campaign.service';
|
import { CampaignService } from '../../../services/campaign.service';
|
||||||
import { LoreService } from '../../services/lore.service';
|
import { LoreService } from '../../../services/lore.service';
|
||||||
import { GameSystemService } from '../../services/game-system.service';
|
import { GameSystemService } from '../../../services/game-system.service';
|
||||||
import { GameSystem } from '../../services/game-system.model';
|
import { GameSystem } from '../../../services/game-system.model';
|
||||||
import { CharacterService } from '../../services/character.service';
|
import { CharacterService } from '../../../services/character.service';
|
||||||
import { Character } from '../../services/character.model';
|
import { NpcService } from '../../../services/npc.service';
|
||||||
import { LayoutService, GlobalItem } from '../../services/layout.service';
|
import { Character } from '../../../services/character.model';
|
||||||
import { PageTitleService } from '../../services/page-title.service';
|
import { Npc } from '../../../services/npc.model';
|
||||||
import { Campaign, Arc } from '../../services/campaign.model';
|
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||||
import { Lore } from '../../services/lore.model';
|
import { PageTitleService } from '../../../services/page-title.service';
|
||||||
import { loadCampaignTreeData, buildCampaignTree, CampaignTreeData } from '../campaign-tree.helper';
|
import { Campaign, Arc } from '../../../services/campaign.model';
|
||||||
|
import { Lore } from '../../../services/lore.model';
|
||||||
|
import { loadCampaignTreeData, buildCampaignTree, CampaignTreeData } from '../../campaign-tree.helper';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-campaign-detail',
|
selector: 'app-campaign-detail',
|
||||||
@@ -33,6 +35,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
readonly Trash2 = Trash2;
|
readonly Trash2 = Trash2;
|
||||||
readonly User = User;
|
readonly User = User;
|
||||||
readonly Dices = Dices;
|
readonly Dices = Dices;
|
||||||
|
readonly Drama = Drama;
|
||||||
|
|
||||||
campaign: Campaign | null = null;
|
campaign: Campaign | null = null;
|
||||||
arcs: Arc[] = [];
|
arcs: Arc[] = [];
|
||||||
@@ -48,6 +51,8 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
linkedGameSystem: GameSystem | null = null;
|
linkedGameSystem: GameSystem | null = null;
|
||||||
/** Fiches de personnages (PJ) de la campagne. */
|
/** Fiches de personnages (PJ) de la campagne. */
|
||||||
characters: Character[] = [];
|
characters: Character[] = [];
|
||||||
|
/** Fiches de personnages non-joueurs (PNJ) de la campagne. */
|
||||||
|
npcs: Npc[] = [];
|
||||||
|
|
||||||
/** Mode édition inline. */
|
/** Mode édition inline. */
|
||||||
editing = false;
|
editing = false;
|
||||||
@@ -63,6 +68,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
private loreService: LoreService,
|
private loreService: LoreService,
|
||||||
private gameSystemService: GameSystemService,
|
private gameSystemService: GameSystemService,
|
||||||
private characterService: CharacterService,
|
private characterService: CharacterService,
|
||||||
|
private npcService: NpcService,
|
||||||
private layoutService: LayoutService,
|
private layoutService: LayoutService,
|
||||||
private pageTitleService: PageTitleService
|
private pageTitleService: PageTitleService
|
||||||
) {}
|
) {}
|
||||||
@@ -77,8 +83,8 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
switchMap(id => forkJoin({
|
switchMap(id => forkJoin({
|
||||||
campaign: this.campaignService.getCampaignById(id),
|
campaign: this.campaignService.getCampaignById(id),
|
||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, id, this.characterService).pipe(
|
treeData: loadCampaignTreeData(this.campaignService, id, this.characterService, this.npcService).pipe(
|
||||||
catchError(() => of({ arcs: [], chaptersByArc: {}, scenesByChapter: {}, characters: [] } as CampaignTreeData))
|
catchError(() => of({ arcs: [], chaptersByArc: {}, scenesByChapter: {}, characters: [], npcs: [] } as CampaignTreeData))
|
||||||
)
|
)
|
||||||
}))
|
}))
|
||||||
).subscribe(({ campaign, allCampaigns, treeData }) => {
|
).subscribe(({ campaign, allCampaigns, treeData }) => {
|
||||||
@@ -87,6 +93,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
this.loadLinkedLore(campaign);
|
this.loadLinkedLore(campaign);
|
||||||
this.loadLinkedGameSystem(campaign);
|
this.loadLinkedGameSystem(campaign);
|
||||||
this.loadCharacters(campaign.id!);
|
this.loadCharacters(campaign.id!);
|
||||||
|
this.loadNpcs(campaign.id!);
|
||||||
this.arcs = treeData.arcs;
|
this.arcs = treeData.arcs;
|
||||||
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
||||||
this.showLayout(allCampaigns, treeData);
|
this.showLayout(allCampaigns, treeData);
|
||||||
@@ -111,8 +118,8 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
forkJoin({
|
forkJoin({
|
||||||
campaign: this.campaignService.getCampaignById(id),
|
campaign: this.campaignService.getCampaignById(id),
|
||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, id, this.characterService).pipe(
|
treeData: loadCampaignTreeData(this.campaignService, id, this.characterService, this.npcService).pipe(
|
||||||
catchError(() => of({ arcs: [], chaptersByArc: {}, scenesByChapter: {}, characters: [] } as CampaignTreeData))
|
catchError(() => of({ arcs: [], chaptersByArc: {}, scenesByChapter: {}, characters: [], npcs: [] } as CampaignTreeData))
|
||||||
)
|
)
|
||||||
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
||||||
this.campaign = campaign;
|
this.campaign = campaign;
|
||||||
@@ -120,6 +127,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
this.loadLinkedLore(campaign);
|
this.loadLinkedLore(campaign);
|
||||||
this.loadLinkedGameSystem(campaign);
|
this.loadLinkedGameSystem(campaign);
|
||||||
this.loadCharacters(campaign.id!);
|
this.loadCharacters(campaign.id!);
|
||||||
|
this.loadNpcs(campaign.id!);
|
||||||
this.arcs = treeData.arcs;
|
this.arcs = treeData.arcs;
|
||||||
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
||||||
this.showLayout(allCampaigns, treeData);
|
this.showLayout(allCampaigns, treeData);
|
||||||
@@ -159,11 +167,28 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
).subscribe(list => this.characters = list);
|
).subscribe(list => this.characters = list);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Symétrique pour les PNJ. */
|
||||||
|
private loadNpcs(campaignId: string): void {
|
||||||
|
this.npcService.getByCampaign(campaignId).pipe(
|
||||||
|
catchError(() => of([] as Npc[]))
|
||||||
|
).subscribe(list => this.npcs = list);
|
||||||
|
}
|
||||||
|
|
||||||
createCharacter(): void {
|
createCharacter(): void {
|
||||||
if (!this.campaign) return;
|
if (!this.campaign) return;
|
||||||
this.router.navigate(['/campaigns', this.campaign.id, 'characters', 'create']);
|
this.router.navigate(['/campaigns', this.campaign.id, 'characters', 'create']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
createNpc(): void {
|
||||||
|
if (!this.campaign) return;
|
||||||
|
this.router.navigate(['/campaigns', this.campaign.id, 'npcs', 'create']);
|
||||||
|
}
|
||||||
|
|
||||||
|
editNpc(npc: Npc): void {
|
||||||
|
if (!this.campaign || !npc.id) return;
|
||||||
|
this.router.navigate(['/campaigns', this.campaign.id, 'npcs', npc.id, 'edit']);
|
||||||
|
}
|
||||||
|
|
||||||
editCharacter(character: Character): void {
|
editCharacter(character: Character): void {
|
||||||
if (!this.campaign || !character.id) return;
|
if (!this.campaign || !character.id) return;
|
||||||
this.router.navigate(['/campaigns', this.campaign.id, 'characters', character.id, 'edit']);
|
this.router.navigate(['/campaigns', this.campaign.id, 'characters', character.id, 'edit']);
|
||||||
@@ -179,10 +204,13 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', arc.id]);
|
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', arc.id]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Extrait une ligne de résumé depuis le markdown (1re ligne non-vide, non-titre). */
|
/**
|
||||||
characterSnippet(c: Character): string {
|
* Extrait une ligne de résumé depuis le markdown (1re ligne non-vide, non-titre).
|
||||||
if (!c.markdownContent) return '(Fiche vide)';
|
* Générique : utilisé pour les fiches PJ comme PNJ (mêmes besoins d'aperçu carte).
|
||||||
const firstMeaningful = c.markdownContent
|
*/
|
||||||
|
personaSnippet(p: { markdownContent?: string | null }): string {
|
||||||
|
if (!p.markdownContent) return '(Fiche vide)';
|
||||||
|
const firstMeaningful = p.markdownContent
|
||||||
.split('\n')
|
.split('\n')
|
||||||
.map(l => l.trim())
|
.map(l => l.trim())
|
||||||
.find(l => l && !l.startsWith('#'));
|
.find(l => l && !l.startsWith('#'));
|
||||||
@@ -192,6 +220,11 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
: firstMeaningful;
|
: firstMeaningful;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Alias gardé pour compatibilité avec les anciens templates. */
|
||||||
|
characterSnippet(c: Character): string {
|
||||||
|
return this.personaSnippet(c);
|
||||||
|
}
|
||||||
|
|
||||||
private showLayout(allCampaigns: Campaign[], data: CampaignTreeData): void {
|
private showLayout(allCampaigns: Campaign[], data: CampaignTreeData): void {
|
||||||
const campaignId = this.campaign!.id!;
|
const campaignId = this.campaign!.id!;
|
||||||
const globalItems: GlobalItem[] = allCampaigns.map(c => ({
|
const globalItems: GlobalItem[] = allCampaigns.map(c => ({
|
||||||
@@ -4,7 +4,7 @@ import { Router } from '@angular/router';
|
|||||||
import { LucideAngularModule, Map, Plus } from 'lucide-angular';
|
import { LucideAngularModule, Map, Plus } from 'lucide-angular';
|
||||||
import { CampaignService } from '../services/campaign.service';
|
import { CampaignService } from '../services/campaign.service';
|
||||||
import { Campaign } from '../services/campaign.model';
|
import { Campaign } from '../services/campaign.model';
|
||||||
import { CampaignCreateComponent, CampaignCreatePayload } from './campaign-create/campaign-create.component';
|
import { CampaignCreateComponent, CampaignCreatePayload } from './campaign/campaign-create/campaign-create.component';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-campaigns',
|
selector: 'app-campaigns',
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angula
|
|||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { forkJoin } from 'rxjs';
|
import { forkJoin } from 'rxjs';
|
||||||
import { LucideAngularModule } from 'lucide-angular';
|
import { LucideAngularModule } from 'lucide-angular';
|
||||||
import { CampaignService } from '../../services/campaign.service';
|
import { CampaignService } from '../../../services/campaign.service';
|
||||||
import { CharacterService } from '../../services/character.service';
|
import { CharacterService } from '../../../services/character.service';
|
||||||
import { LayoutService, GlobalItem } from '../../services/layout.service';
|
import { NpcService } from '../../../services/npc.service';
|
||||||
import { Campaign } from '../../services/campaign.model';
|
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||||
import { loadCampaignTreeData, buildCampaignTree } from '../campaign-tree.helper';
|
import { Campaign } from '../../../services/campaign.model';
|
||||||
import { IconPickerComponent } from '../../shared/icon-picker/icon-picker.component';
|
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||||
import { CAMPAIGN_ICON_OPTIONS } from '../campaign-icons';
|
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||||
|
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Écran de création d'un nouveau chapitre rattaché à un arc.
|
* Écran de création d'un nouveau chapitre rattaché à un arc.
|
||||||
@@ -39,6 +40,7 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
|
|||||||
private router: Router,
|
private router: Router,
|
||||||
private campaignService: CampaignService,
|
private campaignService: CampaignService,
|
||||||
private characterService: CharacterService,
|
private characterService: CharacterService,
|
||||||
|
private npcService: NpcService,
|
||||||
private layoutService: LayoutService
|
private layoutService: LayoutService
|
||||||
) {
|
) {
|
||||||
this.form = this.fb.group({
|
this.form = this.fb.group({
|
||||||
@@ -57,7 +59,7 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
|
|||||||
forkJoin({
|
forkJoin({
|
||||||
campaign: this.campaignService.getCampaignById(this.campaignId),
|
campaign: this.campaignService.getCampaignById(this.campaignId),
|
||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService)
|
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService, this.npcService)
|
||||||
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
}).subscribe(({ campaign, allCampaigns, treeData }) => {
|
||||||
const currentArc = treeData.arcs.find(a => a.id === this.arcId);
|
const currentArc = treeData.arcs.find(a => a.id === this.arcId);
|
||||||
this.arcName = currentArc?.name ?? '';
|
this.arcName = currentArc?.name ?? '';
|
||||||
@@ -5,19 +5,20 @@ import { ActivatedRoute, Router } from '@angular/router';
|
|||||||
import { forkJoin, of } from 'rxjs';
|
import { forkJoin, of } from 'rxjs';
|
||||||
import { switchMap } from 'rxjs/operators';
|
import { switchMap } from 'rxjs/operators';
|
||||||
import { LucideAngularModule, Trash2, Sparkles } from 'lucide-angular';
|
import { LucideAngularModule, Trash2, Sparkles } from 'lucide-angular';
|
||||||
import { CampaignService } from '../../services/campaign.service';
|
import { CampaignService } from '../../../services/campaign.service';
|
||||||
import { CharacterService } from '../../services/character.service';
|
import { CharacterService } from '../../../services/character.service';
|
||||||
import { PageService } from '../../services/page.service';
|
import { NpcService } from '../../../services/npc.service';
|
||||||
import { LayoutService, GlobalItem } from '../../services/layout.service';
|
import { PageService } from '../../../services/page.service';
|
||||||
import { PageTitleService } from '../../services/page-title.service';
|
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||||
import { Campaign, Chapter } from '../../services/campaign.model';
|
import { PageTitleService } from '../../../services/page-title.service';
|
||||||
import { Page } from '../../services/page.model';
|
import { Campaign, Chapter } from '../../../services/campaign.model';
|
||||||
import { loadCampaignTreeData, buildCampaignTree } from '../campaign-tree.helper';
|
import { Page } from '../../../services/page.model';
|
||||||
import { LoreLinkPickerComponent } from '../../shared/lore-link-picker/lore-link-picker.component';
|
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||||
import { AiChatDrawerComponent } from '../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
|
||||||
import { ImageGalleryComponent } from '../../shared/image-gallery/image-gallery.component';
|
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
|
||||||
import { IconPickerComponent } from '../../shared/icon-picker/icon-picker.component';
|
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||||
import { CAMPAIGN_ICON_OPTIONS } from '../campaign-icons';
|
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
|
||||||
|
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Écran de détail/modification d'un Chapitre.
|
* Écran de détail/modification d'un Chapitre.
|
||||||
@@ -67,6 +68,7 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
|||||||
private router: Router,
|
private router: Router,
|
||||||
private campaignService: CampaignService,
|
private campaignService: CampaignService,
|
||||||
private characterService: CharacterService,
|
private characterService: CharacterService,
|
||||||
|
private npcService: NpcService,
|
||||||
private pageService: PageService,
|
private pageService: PageService,
|
||||||
private layoutService: LayoutService,
|
private layoutService: LayoutService,
|
||||||
private pageTitleService: PageTitleService
|
private pageTitleService: PageTitleService
|
||||||
@@ -104,7 +106,7 @@ export class ChapterEditComponent implements OnInit, OnDestroy {
|
|||||||
campaign: this.campaignService.getCampaignById(this.campaignId),
|
campaign: this.campaignService.getCampaignById(this.campaignId),
|
||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
chapter: this.campaignService.getChapterById(this.chapterId),
|
chapter: this.campaignService.getChapterById(this.chapterId),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService)
|
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService, this.npcService)
|
||||||
}).pipe(
|
}).pipe(
|
||||||
switchMap(data => {
|
switchMap(data => {
|
||||||
const lid = data.campaign.loreId ?? null;
|
const lid = data.campaign.loreId ?? null;
|
||||||
@@ -3,12 +3,13 @@ import { CommonModule } from '@angular/common';
|
|||||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||||
import { forkJoin } from 'rxjs';
|
import { forkJoin } from 'rxjs';
|
||||||
import { LucideAngularModule, ArrowLeft } from 'lucide-angular';
|
import { LucideAngularModule, ArrowLeft } from 'lucide-angular';
|
||||||
import { CampaignService } from '../../services/campaign.service';
|
import { CampaignService } from '../../../services/campaign.service';
|
||||||
import { CharacterService } from '../../services/character.service';
|
import { CharacterService } from '../../../services/character.service';
|
||||||
import { LayoutService, GlobalItem } from '../../services/layout.service';
|
import { NpcService } from '../../../services/npc.service';
|
||||||
import { PageTitleService } from '../../services/page-title.service';
|
import { LayoutService, GlobalItem } from '../../../services/layout.service';
|
||||||
import { Campaign, Chapter, Scene } from '../../services/campaign.model';
|
import { PageTitleService } from '../../../services/page-title.service';
|
||||||
import { loadCampaignTreeData, buildCampaignTree } from '../campaign-tree.helper';
|
import { Campaign, Chapter, Scene } from '../../../services/campaign.model';
|
||||||
|
import { loadCampaignTreeData, buildCampaignTree } from '../../campaign-tree.helper';
|
||||||
|
|
||||||
interface GraphNode { id: string; name: string; displayName: string; x: number; y: number; }
|
interface GraphNode { id: string; name: string; displayName: string; x: number; y: number; }
|
||||||
interface GraphEdge { key: string; label: string; x1: number; y1: number; x2: number; y2: number; labelX: number; labelY: number; }
|
interface GraphEdge { key: string; label: string; x1: number; y1: number; x2: number; y2: number; labelX: number; labelY: number; }
|
||||||
@@ -68,6 +69,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
|||||||
private router: Router,
|
private router: Router,
|
||||||
private campaignService: CampaignService,
|
private campaignService: CampaignService,
|
||||||
private characterService: CharacterService,
|
private characterService: CharacterService,
|
||||||
|
private npcService: NpcService,
|
||||||
private layoutService: LayoutService,
|
private layoutService: LayoutService,
|
||||||
private pageTitleService: PageTitleService
|
private pageTitleService: PageTitleService
|
||||||
) {}
|
) {}
|
||||||
@@ -87,7 +89,7 @@ export class ChapterGraphComponent implements OnInit, OnDestroy {
|
|||||||
allCampaigns: this.campaignService.getAllCampaigns(),
|
allCampaigns: this.campaignService.getAllCampaigns(),
|
||||||
chapter: this.campaignService.getChapterById(this.chapterId),
|
chapter: this.campaignService.getChapterById(this.chapterId),
|
||||||
scenes: this.campaignService.getScenes(this.chapterId),
|
scenes: this.campaignService.getScenes(this.chapterId),
|
||||||
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService)
|
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService, this.npcService)
|
||||||
}).subscribe(({ campaign, allCampaigns, chapter, scenes, treeData }) => {
|
}).subscribe(({ campaign, allCampaigns, chapter, scenes, treeData }) => {
|
||||||
this.chapter = chapter;
|
this.chapter = chapter;
|
||||||
this.scenes = scenes;
|
this.scenes = scenes;
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user