Compare commits
10 Commits
9d4e72af26
...
v0.16.0
| Author | SHA1 | Date | |
|---|---|---|---|
| f04ecf1021 | |||
| 72fe5e6215 | |||
| 7dfa9c3655 | |||
| 7aa174d75a | |||
| 48baa08cfb | |||
| f1c68634f7 | |||
| 1e501e03a4 | |||
| bf871852b8 | |||
| 78e735c959 | |||
| c734de447f |
120
.github/workflows/desktop-release.yml
vendored
Normal file
120
.github/workflows/desktop-release.yml
vendored
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
name: Desktop installers
|
||||||
|
|
||||||
|
# Produit les installeurs de BUREAU (.msi Windows pour l'instant) et les publie
|
||||||
|
# en tant qu'assets d'une GitHub Release, sur tag `v*`.
|
||||||
|
#
|
||||||
|
# Complementaire au pipeline Gitea Actions (.gitea/workflows/release.yml) qui,
|
||||||
|
# lui, build et pousse les IMAGES Docker. Ici on est sur GitHub car jpackage et
|
||||||
|
# PyInstaller ne savent PAS cross-compiler : le .msi DOIT etre construit sur un
|
||||||
|
# runner Windows, et GitHub en fournit gratuitement (windows-latest).
|
||||||
|
#
|
||||||
|
# Prerequis : le depot Gitea doit etre mirrore vers GitHub (push mirror, tags
|
||||||
|
# inclus) pour que le tag declenche ce workflow.
|
||||||
|
#
|
||||||
|
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
||||||
|
# Tag beta vX.Y.Z-beta* -> AUCUNE publication publique. Le .msi est depose en
|
||||||
|
# ARTEFACT PRIVE du run (telechargeable seulement par
|
||||||
|
# toi via l'onglet Actions) ; tu le joins ensuite a un
|
||||||
|
# post Patreon reserve a un palier. Patreon = la
|
||||||
|
# barriere d'acces (equivalent du registry prive +
|
||||||
|
# relais pour les images Docker beta).
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*']
|
||||||
|
# Declenchement MANUEL depuis l'onglet Actions ("Run workflow"). Utile quand un
|
||||||
|
# tag a ete pousse AVANT que le workflow existe sur GitHub (ne se redeclenche
|
||||||
|
# pas tout seul), ou pour rejouer un build. Saisir la version SANS le "v".
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: "Version a builder (doit correspondre a un tag existant, ex: 0.15.0 ou 0.15.0-beta)"
|
||||||
|
required: true
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write # requis pour creer la Release et y attacher le .msi
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
windows:
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
# En declenchement manuel, on checkout le TAG correspondant a la version
|
||||||
|
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
||||||
|
# on prend la ref poussee.
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event_name == 'workflow_dispatch' && format('v{0}', inputs.version) || github.ref }}
|
||||||
|
|
||||||
|
# Apporte jpackage (lanceur d'empaquetage natif) dans le PATH.
|
||||||
|
- name: Set up JDK 21
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '21'
|
||||||
|
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
|
||||||
|
# Python 3.12 = meme version que l'image Docker du Brain (coherence runtime).
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
|
||||||
|
# jpackage genere le MSI via WiX Toolset v3 (candle.exe/light.exe). WiX 4+
|
||||||
|
# ne convient pas (outils renommes). Le paquet choco `wixtoolset` est la
|
||||||
|
# ligne 3.x et s'ajoute au PATH.
|
||||||
|
- name: Install WiX Toolset 3
|
||||||
|
shell: pwsh
|
||||||
|
run: choco install wixtoolset -y --no-progress
|
||||||
|
|
||||||
|
# Version de l'installeur = version du tag (push) OU de l'input (manuel).
|
||||||
|
# Sorties : version (numerique X.Y.Z pour le MSI), tag (vX.Y.Z[-beta]),
|
||||||
|
# isbeta (true/false) — independant du nom de ref (qui est une branche en manuel).
|
||||||
|
- name: Derive version
|
||||||
|
id: ver
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
if ('${{ github.event_name }}' -eq 'workflow_dispatch') {
|
||||||
|
$raw = '${{ inputs.version }}'
|
||||||
|
} else {
|
||||||
|
$raw = '${{ github.ref_name }}'
|
||||||
|
}
|
||||||
|
$raw = $raw -replace '^v','' # 0.15.0 ou 0.15.0-beta
|
||||||
|
$num = ($raw -split '-')[0] # 0.15.0
|
||||||
|
$isbeta = if ($raw -like '*-beta*') { 'true' } else { 'false' }
|
||||||
|
"version=$num" >> $env:GITHUB_OUTPUT
|
||||||
|
"tag=v$raw" >> $env:GITHUB_OUTPUT
|
||||||
|
"isbeta=$isbeta" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Build Windows installer
|
||||||
|
shell: pwsh
|
||||||
|
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||||
|
|
||||||
|
# STABLE uniquement : Release GitHub publique avec le .msi.
|
||||||
|
# tag_name explicite : en declenchement manuel, github.ref est une branche,
|
||||||
|
# donc on cible le tag derive (la release est attachee au bon tag).
|
||||||
|
- name: Publish installer to GitHub Release (stable)
|
||||||
|
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ steps.ver.outputs.tag }}
|
||||||
|
files: core/target/dist-out/*.msi
|
||||||
|
fail_on_unmatched_files: true
|
||||||
|
generate_release_notes: true
|
||||||
|
|
||||||
|
# BETA uniquement : artefact PRIVE (pas de release publique). A recuperer
|
||||||
|
# via l'onglet Actions puis a joindre a un post Patreon gate par palier.
|
||||||
|
- name: Upload installer as private artifact (beta)
|
||||||
|
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: loremind-beta-${{ steps.ver.outputs.version }}-msi
|
||||||
|
path: core/target/dist-out/*.msi
|
||||||
|
retention-days: 90
|
||||||
|
|
||||||
|
# TODO (plus tard) : job `linux` sur ubuntu-latest produisant un AppImage
|
||||||
|
# (jpackage --type app-image + appimagetool) + PyInstaller Linux du Brain,
|
||||||
|
# attache a la MEME release. Reutilise la meme matrice / les memes etapes.
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -45,6 +45,12 @@ env/
|
|||||||
.coverage
|
.coverage
|
||||||
htmlcov/
|
htmlcov/
|
||||||
|
|
||||||
|
# Artefacts du build bureau (cf. installers/desktop)
|
||||||
|
.venv-build/
|
||||||
|
brain/build/
|
||||||
|
brain/dist-embed/
|
||||||
|
*.spec
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Angular / Node (Web)
|
# Angular / Node (Web)
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
@@ -116,3 +122,4 @@ brain/data/notebooks/5.json
|
|||||||
# Contient le site premium (sources) + son Worker de gate dans gate/.
|
# Contient le site premium (sources) + son Worker de gate dans gate/.
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
docusaurus/loremind-patreon/
|
docusaurus/loremind-patreon/
|
||||||
|
installers/desktop/README.md
|
||||||
|
|||||||
68
README.fr.md
Normal file
68
README.fr.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# LoreMind
|
||||||
|
|
||||||
|
[English](README.md) · **Français**
|
||||||
|
|
||||||
|
> Application web auto-hébergeable pour MJ qui veulent centraliser leur univers, leurs campagnes et leurs personnages — avec un assistant IA contextuel.
|
||||||
|
|
||||||
|
[](LICENSE)
|
||||||
|
[](https://loremind-docs.igmlcreation.fr/)
|
||||||
|
[](https://loremind-demo.igmlcreation.fr/)
|
||||||
|
[](https://www.patreon.com/c/IGMLCreation)
|
||||||
|
[](https://discord.gg/cPpFzCjEzQ)
|
||||||
|
|
||||||
|
## Découvrir LoreMind en vidéo
|
||||||
|
|
||||||
|
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Ce que ça fait
|
||||||
|
|
||||||
|
LoreMind regroupe ce qu'un MJ utilise habituellement éparpillé entre plusieurs outils. L'application s'articule autour de trois modules principaux, augmentés par un assistant IA qui exploite tout votre contenu.
|
||||||
|
|
||||||
|
### Lore
|
||||||
|
|
||||||
|
Construire votre univers avec une arborescence de pages templatées : lieux, factions, PNJ, événements, organisations... Chaque type de page suit un template configurable, ce qui garantit la cohérence et facilite la navigation dans des univers riches.
|
||||||
|
|
||||||
|
### Game System
|
||||||
|
|
||||||
|
Stocker les règles de votre système de jeu (D&D, Nimble, créations maison...) et définir les modèles de fiches de personnages associés. Les règles indexées peuvent être injectées dans le contexte de l'IA pour des réponses fidèles à votre système.
|
||||||
|
|
||||||
|
### Campaign
|
||||||
|
|
||||||
|
Structurer vos campagnes en Arcs → Chapitres → Scènes avec séparation claire du contenu MJ et du contenu joueurs. Gérer les PJ et PNJ via des fiches dynamiques basées sur les templates du game system retenu.
|
||||||
|
|
||||||
|
### Assistant IA
|
||||||
|
|
||||||
|
Un assistant contextuel qui pioche dans votre Lore, vos règles et vos campagnes pour répondre à vos questions, suggérer du contenu cohérent, ou rebondir sur une situation improvisée en table.
|
||||||
|
|
||||||
|
L'IA s'exécute **en local via [Ollama](https://ollama.com/)** ou via **[1min.ai](https://1min.ai/)**. D'autres moteurs seront supportés à l'avenir.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
Toute la documentation (installation, configuration, prise en main) est sur **[loremind-docs.igmlcreation.fr](https://loremind-docs.igmlcreation.fr/)**.
|
||||||
|
|
||||||
|
## Démo en ligne
|
||||||
|
|
||||||
|
Une instance de démonstration est disponible sur **[loremind-demo.igmlcreation.fr](https://loremind-demo.igmlcreation.fr/)**.
|
||||||
|
|
||||||
|
Quelques limites à connaître :
|
||||||
|
- 10 utilisateurs maximum simultanés (instances isolées)
|
||||||
|
- Session limitée à 20 minutes avant réinitialisation
|
||||||
|
- Partie IA non incluse dans la démo (nécessite Ollama ou 1min.ai côté serveur)
|
||||||
|
|
||||||
|
## Soutenir le projet
|
||||||
|
|
||||||
|
LoreMind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||||
|
|
||||||
|
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
||||||
|
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
LoreMind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||||
|
|
||||||
|
En pratique :
|
||||||
|
- Vous pouvez l'utiliser gratuitement, l'héberger, la modifier, la redistribuer.
|
||||||
|
- Si vous modifiez le code et que vous exposez l'application modifiée sur un réseau (même en SaaS privé), vous devez rendre vos modifications publiques sous la même licence.
|
||||||
|
- Les univers (Lore) et campagnes que vous créez avec LoreMind **vous appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||||
70
README.md
70
README.md
@@ -1,66 +1,68 @@
|
|||||||
# LoreMind
|
# LoreMind
|
||||||
|
|
||||||
> Application web auto-hébergeable pour MJ qui veulent centraliser leur univers, leurs campagnes et leurs personnages — avec un assistant IA contextuel.
|
**English** · [Français](README.fr.md)
|
||||||
|
|
||||||
[](LICENSE)
|
> A self-hostable web app for game masters who want to centralize their world, campaigns and characters — with a context-aware AI assistant.
|
||||||
[](https://loremind-docs.igmlcreation.fr/)
|
|
||||||
[](https://loremind-demo.igmlcreation.fr/)
|
|
||||||
[](https://www.patreon.com/c/IGMLCreation)
|
|
||||||
[](https://discord.gg/cPpFzCjEzQ)
|
|
||||||
|
|
||||||
## Découvrir LoreMind en vidéo
|
[](LICENSE)
|
||||||
|
[](https://loremind-docs.igmlcreation.fr/en/)
|
||||||
|
[](https://loremind-demo.igmlcreation.fr/)
|
||||||
|
[](https://www.patreon.com/c/IGMLCreation)
|
||||||
|
[](https://discord.gg/cPpFzCjEzQ)
|
||||||
|
|
||||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
## See LoreMind in action
|
||||||
|
|
||||||

|
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||||
|
|
||||||
## Ce que ça fait
|

|
||||||
|
|
||||||
LoreMind regroupe ce qu'un MJ utilise habituellement éparpillé entre plusieurs outils. L'application s'articule autour de trois modules principaux, augmentés par un assistant IA qui exploite tout votre contenu.
|
## What it does
|
||||||
|
|
||||||
|
LoreMind brings together what a game master usually scatters across several tools. The app is built around three core modules, augmented by an AI assistant that draws on all of your content.
|
||||||
|
|
||||||
### Lore
|
### Lore
|
||||||
|
|
||||||
Construire votre univers avec une arborescence de pages templatées : lieux, factions, PNJ, événements, organisations... Chaque type de page suit un template configurable, ce qui garantit la cohérence et facilite la navigation dans des univers riches.
|
Build your world with a tree of templated pages: locations, factions, NPCs, events, organizations... Each page type follows a configurable template, which keeps things consistent and makes navigating rich worlds easy.
|
||||||
|
|
||||||
### Game System
|
### Game System
|
||||||
|
|
||||||
Stocker les règles de votre système de jeu (D&D, Nimble, créations maison...) et définir les modèles de fiches de personnages associés. Les règles indexées peuvent être injectées dans le contexte de l'IA pour des réponses fidèles à votre système.
|
Store the rules of your game system (D&D, Nimble, homebrew...) and define the matching character sheet templates. Indexed rules can be injected into the AI's context for answers that stay true to your system.
|
||||||
|
|
||||||
### Campaign
|
### Campaign
|
||||||
|
|
||||||
Structurer vos campagnes en Arcs → Chapitres → Scènes avec séparation claire du contenu MJ et du contenu joueurs. Gérer les PJ et PNJ via des fiches dynamiques basées sur les templates du game system retenu.
|
Structure your campaigns as Arcs → Chapters → Scenes, with a clear split between GM-only and player-facing content. Manage PCs and NPCs through dynamic sheets based on your chosen game system's templates.
|
||||||
|
|
||||||
### Assistant IA
|
### AI Assistant
|
||||||
|
|
||||||
Un assistant contextuel qui pioche dans votre Lore, vos règles et vos campagnes pour répondre à vos questions, suggérer du contenu cohérent, ou rebondir sur une situation improvisée en table.
|
A context-aware assistant that pulls from your Lore, rules and campaigns to answer your questions, suggest consistent content, or improvise around an unexpected situation at the table.
|
||||||
|
|
||||||
L'IA s'exécute **en local via [Ollama](https://ollama.com/)** ou via **[1min.ai](https://1min.ai/)**. D'autres moteurs seront supportés à l'avenir.
|
The AI runs **locally via [Ollama](https://ollama.com/)** or via **[1min.ai](https://1min.ai/)**. More engines will be supported in the future.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
Toute la documentation (installation, configuration, prise en main) est sur **[loremind-docs.igmlcreation.fr](https://loremind-docs.igmlcreation.fr/)**.
|
The full documentation (installation, configuration, getting started) lives at **[loremind-docs.igmlcreation.fr/en](https://loremind-docs.igmlcreation.fr/en/)**.
|
||||||
|
|
||||||
## Démo en ligne
|
## Live demo
|
||||||
|
|
||||||
Une instance de démonstration est disponible sur **[loremind-demo.igmlcreation.fr](https://loremind-demo.igmlcreation.fr/)**.
|
A demo instance is available at **[loremind-demo.igmlcreation.fr](https://loremind-demo.igmlcreation.fr/)**.
|
||||||
|
|
||||||
Quelques limites à connaître :
|
A few limitations to be aware of:
|
||||||
- 10 utilisateurs maximum simultanés (instances isolées)
|
- 10 concurrent users maximum (isolated instances)
|
||||||
- Session limitée à 20 minutes avant réinitialisation
|
- Sessions limited to 20 minutes before reset
|
||||||
- Partie IA non incluse dans la démo (nécessite Ollama ou 1min.ai côté serveur)
|
- The AI part is not included in the demo (requires Ollama or 1min.ai server-side)
|
||||||
|
|
||||||
## Soutenir le projet
|
## Support the project
|
||||||
|
|
||||||
LoreMind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
LoreMind is **and will remain free when self-hosted**. Development moves faster with your support:
|
||||||
|
|
||||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — early access to features, roadmap voting, exclusive devlogs
|
||||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
||||||
|
|
||||||
## Licence
|
## License
|
||||||
|
|
||||||
LoreMind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
LoreMind is distributed under the **[GNU AGPL v3](LICENSE)** license.
|
||||||
|
|
||||||
En pratique :
|
In practice:
|
||||||
- Vous pouvez l'utiliser gratuitement, l'héberger, la modifier, la redistribuer.
|
- You can use it for free, host it, modify it, and redistribute it.
|
||||||
- Si vous modifiez le code et que vous exposez l'application modifiée sur un réseau (même en SaaS privé), vous devez rendre vos modifications publiques sous la même licence.
|
- If you modify the code and expose the modified app over a network (even as a private SaaS), you must make your changes public under the same license.
|
||||||
- Les univers (Lore) et campagnes que vous créez avec LoreMind **vous appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
- The worlds (Lore) and campaigns you create with LoreMind **belong entirely to you** — the license only covers the application's code.
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="0.14.0-beta",
|
version="0.16.0",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|||||||
27
brain/run_local.py
Normal file
27
brain/run_local.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
"""Point d'entree LOCAL du Brain (hors Docker).
|
||||||
|
|
||||||
|
Lance le serveur uvicorn sur 127.0.0.1:8000 — l'equivalent autonome de la
|
||||||
|
commande Docker `uvicorn app.main:app --host 0.0.0.0 --port 8000`, mais en
|
||||||
|
n'ecoutant QUE sur la boucle locale (mono-utilisateur, jamais expose au reseau).
|
||||||
|
|
||||||
|
Empaquete avec le Python *embeddable* officiel (signe par la PSF) dans
|
||||||
|
l'application de bureau : on evite ainsi tout executable "gele" type PyInstaller
|
||||||
|
que les antivirus prennent souvent pour un trojan (bootloader packe).
|
||||||
|
Le Core le lance via : python\\python.exe run_local.py
|
||||||
|
|
||||||
|
On insere le dossier de CE fichier dans sys.path pour que le package `app`
|
||||||
|
soit importable quel que soit le repertoire de travail (le Core fixe le cwd
|
||||||
|
ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
import uvicorn # noqa: E402
|
||||||
|
|
||||||
|
from app.main import app # noqa: E402
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# host 127.0.0.1 : accessible uniquement depuis le Core sur la meme machine.
|
||||||
|
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
|
||||||
72
core/pom.xml
72
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.14.0-beta</version>
|
<version>0.16.0</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
@@ -60,11 +60,31 @@
|
|||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- H2 Database pour les tests -->
|
<!-- Flyway : migrations de schema versionnees (remplace ddl-auto=update).
|
||||||
|
Un SEUL jeu de migrations en SQL PostgreSQL sert les deux bases :
|
||||||
|
- Postgres (Docker/serveur) nativement ;
|
||||||
|
- H2 (mode local-first) via MODE=PostgreSQL dans l'URL JDBC.
|
||||||
|
flyway-database-postgresql : module requis depuis Flyway 10 (DBs
|
||||||
|
externalisees du core). H2 reste supporte par flyway-core. -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-core</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.flywaydb</groupId>
|
||||||
|
<artifactId>flyway-database-postgresql</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- H2 Database :
|
||||||
|
- tests (toujours) ;
|
||||||
|
- RUNTIME du profil "local" (mode local-first / jpackage) : base
|
||||||
|
fichier embarquee a la place de Postgres, donc le driver doit etre
|
||||||
|
sur le classpath d'execution. Scope runtime (jamais compile contre)
|
||||||
|
=> present a l'execution + tests, ~2,5 Mo inutilises cote Docker. -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.h2database</groupId>
|
<groupId>com.h2database</groupId>
|
||||||
<artifactId>h2</artifactId>
|
<artifactId>h2</artifactId>
|
||||||
<scope>test</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Lombok (réduit le code boilerplate) -->
|
<!-- Lombok (réduit le code boilerplate) -->
|
||||||
@@ -179,4 +199,50 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<!-- =================================================================
|
||||||
|
Profil "desktop" : build local-first (application de bureau).
|
||||||
|
Active avec : mvn -Pdesktop package
|
||||||
|
Embarque le build Angular dans le jar (classpath:/static/) pour que
|
||||||
|
le Core serve lui-meme le front (cf. LocalWebConfig, profil Spring
|
||||||
|
"local"). Le build Docker normal (sans ce profil) reste une API pure :
|
||||||
|
le front y est servi par le conteneur nginx, donc rien n'est copie.
|
||||||
|
================================================================= -->
|
||||||
|
<profile>
|
||||||
|
<id>desktop</id>
|
||||||
|
<properties>
|
||||||
|
<!-- Sortie du `ng build` (builder browser) : web/dist/web. -->
|
||||||
|
<frontend.dist>${project.basedir}/../web/dist/web</frontend.dist>
|
||||||
|
</properties>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-resources-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>copy-frontend</id>
|
||||||
|
<!-- Avant le repackage Spring Boot : on injecte le
|
||||||
|
front dans les classes compilees -> embarque
|
||||||
|
dans le fat jar sous /static. -->
|
||||||
|
<phase>prepare-package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>copy-resources</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<outputDirectory>${project.build.outputDirectory}/static</outputDirectory>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>${frontend.dist}</directory>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package com.loremind;
|
package com.loremind;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.desktop.DesktopSingleInstance;
|
||||||
|
import com.loremind.infrastructure.desktop.DesktopUserConfig;
|
||||||
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;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
@@ -13,6 +15,29 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
|||||||
public class LoreMindApplication {
|
public class LoreMindApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(LoreMindApplication.class, args);
|
// Mode bureau (profil "local") : garde-fou instance unique. Si l'app
|
||||||
|
// tourne deja, on ouvre juste le navigateur et on sort proprement (code 0)
|
||||||
|
// au lieu de demarrer un 2e serveur qui echouerait sur le verrou H2 — ce
|
||||||
|
// qui evite le trompeur « Failed to launch JVM » du launcher jpackage.
|
||||||
|
boolean local = DesktopSingleInstance.isLocalProfile(args);
|
||||||
|
if (local && !DesktopSingleInstance.tryAcquire()) {
|
||||||
|
DesktopSingleInstance.openAppInBrowser();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SpringApplication app = new SpringApplication(LoreMindApplication.class);
|
||||||
|
if (local) {
|
||||||
|
// Mode bureau : on a besoin d'AWT (icone de la zone de notification,
|
||||||
|
// cf. SystemTrayManager). Spring Boot force headless=true par defaut,
|
||||||
|
// ce qui leverait HeadlessException — on le desactive ici. En mode
|
||||||
|
// serveur/Docker, on reste en headless (defaut), aucun impact.
|
||||||
|
app.setHeadless(false);
|
||||||
|
// Config utilisateur editable (~/.loremind/loremind.properties) : creee
|
||||||
|
// au 1er lancement (port + identifiants admin). Puis resolution du port :
|
||||||
|
// celui configure s'il est libre, sinon un port libre (evite l'echec de
|
||||||
|
// demarrage si 8080 est deja pris). Publie server.port + ~/.loremind/.port.
|
||||||
|
DesktopUserConfig.ensureExists();
|
||||||
|
DesktopUserConfig.resolveAndPublishPort();
|
||||||
|
}
|
||||||
|
app.run(args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,26 +40,33 @@ public class LicenseService {
|
|||||||
private final LicenseRelay relay;
|
private final LicenseRelay relay;
|
||||||
private final long gracePeriodSeconds;
|
private final long gracePeriodSeconds;
|
||||||
private final long refreshBeforeExpirySeconds;
|
private final long refreshBeforeExpirySeconds;
|
||||||
|
private final boolean licensingEnabled;
|
||||||
|
|
||||||
public LicenseService(
|
public LicenseService(
|
||||||
LicenseRepository repository,
|
LicenseRepository repository,
|
||||||
JwtVerifier jwtVerifier,
|
JwtVerifier jwtVerifier,
|
||||||
LicenseRelay relay,
|
LicenseRelay relay,
|
||||||
@Value("${licensing.grace-period-days:14}") int gracePeriodDays,
|
@Value("${licensing.grace-period-days:14}") int gracePeriodDays,
|
||||||
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays) {
|
@Value("${licensing.refresh-before-expiry-days:2}") int refreshBeforeExpiryDays,
|
||||||
|
@Value("${licensing.enabled:true}") boolean licensingEnabled) {
|
||||||
this.repository = repository;
|
this.repository = repository;
|
||||||
this.jwtVerifier = jwtVerifier;
|
this.jwtVerifier = jwtVerifier;
|
||||||
this.relay = relay;
|
this.relay = relay;
|
||||||
this.gracePeriodSeconds = (long) gracePeriodDays * 86_400L;
|
this.gracePeriodSeconds = (long) gracePeriodDays * 86_400L;
|
||||||
this.refreshBeforeExpirySeconds = (long) refreshBeforeExpiryDays * 86_400L;
|
this.refreshBeforeExpirySeconds = (long) refreshBeforeExpiryDays * 86_400L;
|
||||||
|
this.licensingEnabled = licensingEnabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return true si le verifier est configure (cle publique presente).
|
* @return true si le licensing Patreon est actif : il faut a la fois que la
|
||||||
* L'UI peut masquer toute la section Patreon si false.
|
* feature soit activee ({@code licensing.enabled}, faux en mode
|
||||||
|
* bureau/local ou le gating par image Docker n'a aucun sens) ET que
|
||||||
|
* le verifier soit configure (cle publique presente). Faux => l'UI
|
||||||
|
* masque toute la section Patreon, le daemon de refresh est no-op,
|
||||||
|
* et le canal beta est desactive.
|
||||||
*/
|
*/
|
||||||
public boolean isLicensingEnabled() {
|
public boolean isLicensingEnabled() {
|
||||||
return jwtVerifier.isConfigured();
|
return licensingEnabled && jwtVerifier.isConfigured();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -26,6 +26,21 @@ public interface ImageStorage {
|
|||||||
*/
|
*/
|
||||||
String upload(String filename, String contentType, InputStream data, long sizeBytes);
|
String upload(String filename, String contentType, InputStream data, long sizeBytes);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stocke un flux binaire SOUS UNE CLE IMPOSEE (pas de generation).
|
||||||
|
* <p>
|
||||||
|
* Utilise par l'import de contenu pour reinjecter une image sous sa cle
|
||||||
|
* d'origine, garantissant que les references {@code storageKey} portees par
|
||||||
|
* les entites restent valides apres un transfert inter-instance.
|
||||||
|
* Ecrase si la cle existe deja.
|
||||||
|
*
|
||||||
|
* @param storageKey cle opaque exacte sous laquelle stocker (ex: images/UUID.ext)
|
||||||
|
* @param contentType MIME type
|
||||||
|
* @param data flux binaire a stocker
|
||||||
|
* @param sizeBytes taille en octets (requis par certains backends comme S3)
|
||||||
|
*/
|
||||||
|
void store(String storageKey, String contentType, InputStream data, long sizeBytes);
|
||||||
|
|
||||||
/** Recupere le flux binaire associe a une cle, ou null si inexistante. */
|
/** Recupere le flux binaire associe a une cle, ou null si inexistante. */
|
||||||
InputStream download(String storageKey);
|
InputStream download(String storageKey);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import jakarta.annotation.PreDestroy;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lance le Brain (service IA Python) comme SOUS-PROCESSUS du Core, en mode
|
||||||
|
* local-first (application de bureau empaquetee, sans Docker).
|
||||||
|
* <p>
|
||||||
|
* Cycle de vie calque sur celui du Core :
|
||||||
|
* <ul>
|
||||||
|
* <li>demarrage : a {@link ApplicationReadyEvent} (le serveur HTTP du Core
|
||||||
|
* est deja pret) ;</li>
|
||||||
|
* <li>arret : a {@link PreDestroy} (fermeture du contexte Spring) — on arrete
|
||||||
|
* proprement le Brain pour ne pas laisser de process orphelin.</li>
|
||||||
|
* </ul>
|
||||||
|
* <p>
|
||||||
|
* Tolerance aux pannes : si le Brain ne peut pas etre lance (exe absent,
|
||||||
|
* commande non configuree...), on LOGGUE sans faire echouer le Core. L'app
|
||||||
|
* reste utilisable (Lore, Campagnes, Systeme de jeu) ; seules les fonctions IA
|
||||||
|
* sont indisponibles jusqu'a correction.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Profile("local")
|
||||||
|
public class BrainSidecar {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(BrainSidecar.class);
|
||||||
|
|
||||||
|
private final BrainSidecarProperties props;
|
||||||
|
private final String internalSecret;
|
||||||
|
|
||||||
|
private volatile Process process;
|
||||||
|
|
||||||
|
public BrainSidecar(BrainSidecarProperties props,
|
||||||
|
@Value("${brain.internal-secret:}") String internalSecret) {
|
||||||
|
this.props = props;
|
||||||
|
this.internalSecret = internalSecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void start() {
|
||||||
|
if (!props.isEnabled()) {
|
||||||
|
log.info("[Brain] Sidecar desactive (brain.sidecar.enabled=false).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (props.getCommand() == null || props.getCommand().isEmpty()) {
|
||||||
|
log.warn("[Brain] Aucune commande configuree (brain.sidecar.command) : "
|
||||||
|
+ "le Brain n'est pas lance. Les fonctions IA seront indisponibles.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
ProcessBuilder pb = new ProcessBuilder(props.getCommand());
|
||||||
|
pb.redirectErrorStream(true);
|
||||||
|
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
|
||||||
|
|
||||||
|
File workingDir = resolveWorkingDir();
|
||||||
|
if (workingDir != null) {
|
||||||
|
pb.directory(workingDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Secret partage Core <-> Brain : le Brain est fail-closed sans lui.
|
||||||
|
// (cf. Settings.internal_shared_secret cote Python -> env INTERNAL_SHARED_SECRET)
|
||||||
|
pb.environment().put("INTERNAL_SHARED_SECRET", internalSecret);
|
||||||
|
|
||||||
|
this.process = pb.start();
|
||||||
|
log.info("[Brain] Sidecar demarre (pid={}, cwd={}).",
|
||||||
|
process.pid(), workingDir != null ? workingDir : "<heritee>");
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
||||||
|
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
||||||
|
props.getCommand(), e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void stop() {
|
||||||
|
Process p = this.process;
|
||||||
|
if (p == null || !p.isAlive()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log.info("[Brain] Arret du sidecar (pid={})...", p.pid());
|
||||||
|
p.destroy();
|
||||||
|
try {
|
||||||
|
if (!p.waitFor(10, TimeUnit.SECONDS)) {
|
||||||
|
log.warn("[Brain] Arret propre depasse (10s) : kill force.");
|
||||||
|
p.destroyForcibly();
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
p.destroyForcibly();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resout (et cree au besoin) le repertoire de travail du Brain. Le Brain y
|
||||||
|
* ecrit son dossier {@code data/} (index vectoriel, settings.json).
|
||||||
|
*/
|
||||||
|
private File resolveWorkingDir() {
|
||||||
|
String dir = props.getWorkingDir();
|
||||||
|
if (dir == null || dir.isBlank()) {
|
||||||
|
return null; // herite du cwd du Core
|
||||||
|
}
|
||||||
|
Path path = Path.of(dir).toAbsolutePath().normalize();
|
||||||
|
try {
|
||||||
|
Files.createDirectories(path);
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("[Brain] Impossible de creer le repertoire de travail {} : {}. "
|
||||||
|
+ "Lancement avec le cwd herite.", path, e.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return path.toFile();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration du lancement du Brain (service IA Python) en SIDECAR, c.-a-d.
|
||||||
|
* comme sous-processus du Core, en mode local-first.
|
||||||
|
* <p>
|
||||||
|
* En deploiement Docker, le Brain est un conteneur independant : ce mecanisme
|
||||||
|
* est inactif (profil {@code local} uniquement). En application de bureau
|
||||||
|
* empaquetee, il n'y a pas de Docker : le Core demarre lui-meme le Brain.
|
||||||
|
*
|
||||||
|
* @see BrainSidecar
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Profile("local")
|
||||||
|
@ConfigurationProperties(prefix = "brain.sidecar")
|
||||||
|
public class BrainSidecarProperties {
|
||||||
|
|
||||||
|
/** Active le lancement du Brain par le Core. */
|
||||||
|
private boolean enabled = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commande de lancement (programme + arguments). Vide = ne rien lancer
|
||||||
|
* (cas du dev qui demarre le Brain a la main).
|
||||||
|
* <ul>
|
||||||
|
* <li>Mode empaquete (jpackage) : chemin de l'exe PyInstaller, ex.
|
||||||
|
* {@code C:\Program Files\LoreMind\brain\loremind-brain.exe}</li>
|
||||||
|
* <li>Dev : {@code python,-m,uvicorn,app.main:app,--host,127.0.0.1,--port,8000}</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
private List<String> command = List.of();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repertoire de travail du process Brain. Le Brain ecrit ses donnees (index
|
||||||
|
* vectoriel, settings.json) sous {@code data/} RELATIF a ce dossier : on le
|
||||||
|
* place donc sous loremind.home pour que tout vive au meme endroit.
|
||||||
|
*/
|
||||||
|
private String workingDir;
|
||||||
|
|
||||||
|
public boolean isEnabled() { return enabled; }
|
||||||
|
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||||
|
|
||||||
|
public List<String> getCommand() { return command; }
|
||||||
|
public void setCommand(List<String> command) { this.command = command; }
|
||||||
|
|
||||||
|
public String getWorkingDir() { return workingDir; }
|
||||||
|
public void setWorkingDir(String workingDir) { this.workingDir = workingDir; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* En mode bureau (profil "local"), ouvre le navigateur par defaut sur
|
||||||
|
* l'application des que le serveur est pret. L'app n'ayant pas de fenetre
|
||||||
|
* native, c'est ce qui donne a l'utilisateur un retour visuel immediat apres
|
||||||
|
* le double-clic.
|
||||||
|
* <p>
|
||||||
|
* Concerne uniquement l'instance qui a effectivement demarre le serveur :
|
||||||
|
* l'instance « perdante » du verrou unique ouvre le navigateur des le {@code main}
|
||||||
|
* puis sort (cf. {@link DesktopSingleInstance}).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Profile("local")
|
||||||
|
public class DesktopBrowserOpener {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DesktopBrowserOpener.class);
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void onReady() {
|
||||||
|
log.info("[Desktop] Application prete — ouverture du navigateur.");
|
||||||
|
DesktopSingleInstance.openAppInBrowser();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
|
import java.nio.channels.FileLock;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utilitaires du mode BUREAU (profil "local", application empaquetee jpackage).
|
||||||
|
* <p>
|
||||||
|
* Resout deux problemes specifiques au lancement par double-clic :
|
||||||
|
* <ol>
|
||||||
|
* <li><b>Instance unique</b> : un serveur web n'ouvre pas de fenetre. Un
|
||||||
|
* utilisateur qui ne voit rien re-double-clique souvent — la 2e instance
|
||||||
|
* trouvait la base H2 verrouillee et sortait en erreur, ce que le launcher
|
||||||
|
* jpackage traduit par un trompeur « Failed to launch JVM ». On detecte
|
||||||
|
* donc tres tot (avant Spring) qu'une instance tourne deja, et on se
|
||||||
|
* contente d'ouvrir le navigateur puis de sortir proprement (code 0).</li>
|
||||||
|
* <li><b>Ouverture du navigateur</b> : l'app n'ayant pas de fenetre native,
|
||||||
|
* on ouvre le navigateur par defaut sur l'URL locale pour que l'utilisateur
|
||||||
|
* voie l'application immediatement.</li>
|
||||||
|
* </ol>
|
||||||
|
* Volontairement sans dependance a {@code java.awt.Desktop} : ce module
|
||||||
|
* ({@code java.desktop}) pourrait etre absent du runtime reduit par jlink.
|
||||||
|
* On passe donc par la commande systeme d'ouverture d'URL.
|
||||||
|
*/
|
||||||
|
public final class DesktopSingleInstance {
|
||||||
|
|
||||||
|
/** Conserve le verrou ouvert pour TOUTE la duree de vie du process (sinon GC = relache). */
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private static FileChannel lockChannel;
|
||||||
|
private static FileLock lock;
|
||||||
|
|
||||||
|
private DesktopSingleInstance() {}
|
||||||
|
|
||||||
|
/** Vrai si le profil Spring actif inclut "local" (cas de l'app de bureau). */
|
||||||
|
public static boolean isLocalProfile(String[] args) {
|
||||||
|
String prop = System.getProperty("spring.profiles.active", "");
|
||||||
|
String env = System.getenv().getOrDefault("SPRING_PROFILES_ACTIVE", "");
|
||||||
|
if (containsLocal(prop) || containsLocal(env)) return true;
|
||||||
|
if (args != null) {
|
||||||
|
for (String a : args) {
|
||||||
|
if (a.startsWith("--spring.profiles.active=") && containsLocal(a)) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean containsLocal(String s) {
|
||||||
|
for (String p : s.split("[,=]")) {
|
||||||
|
if (p.trim().equals("local")) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tente de prendre le verrou d'instance unique (fichier {@code .instance.lock}
|
||||||
|
* sous loremind.home). Retourne {@code true} si on est la PREMIERE instance
|
||||||
|
* (verrou obtenu, on doit demarrer le serveur), {@code false} si une autre
|
||||||
|
* instance le detient deja.
|
||||||
|
* <p>
|
||||||
|
* En cas d'erreur d'E/S inattendue, on retourne {@code true} (degradation
|
||||||
|
* prudente : mieux vaut tenter de demarrer que bloquer l'app).
|
||||||
|
*/
|
||||||
|
public static boolean tryAcquire() {
|
||||||
|
try {
|
||||||
|
Path dir = loremindHome();
|
||||||
|
Files.createDirectories(dir);
|
||||||
|
Path lockFile = dir.resolve(".instance.lock");
|
||||||
|
lockChannel = FileChannel.open(lockFile,
|
||||||
|
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||||
|
lock = lockChannel.tryLock();
|
||||||
|
return lock != null; // null = deja verrouille par une autre instance
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("[Desktop] Verrou d'instance indisponible (" + e.getMessage()
|
||||||
|
+ ") — on tente de demarrer quand meme.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ouvre le navigateur par defaut sur l'URL de l'application locale (port reel). */
|
||||||
|
public static void openAppInBrowser() {
|
||||||
|
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */
|
||||||
|
public static void openUrl(String url) {
|
||||||
|
try {
|
||||||
|
String os = System.getProperty("os.name", "").toLowerCase();
|
||||||
|
ProcessBuilder pb;
|
||||||
|
if (os.contains("win")) {
|
||||||
|
// rundll32 : ouverture d'URL fiable sans dependance graphique Java.
|
||||||
|
pb = new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", url);
|
||||||
|
} else if (os.contains("mac")) {
|
||||||
|
pb = new ProcessBuilder("open", url);
|
||||||
|
} else {
|
||||||
|
pb = new ProcessBuilder("xdg-open", url);
|
||||||
|
}
|
||||||
|
pb.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("[Desktop] Impossible d'ouvrir le navigateur sur " + url
|
||||||
|
+ " : " + e.getMessage() + ". Ouvrez-le manuellement.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */
|
||||||
|
public static void openFolder(Path dir) {
|
||||||
|
try {
|
||||||
|
Files.createDirectories(dir);
|
||||||
|
String os = System.getProperty("os.name", "").toLowerCase();
|
||||||
|
ProcessBuilder pb;
|
||||||
|
if (os.contains("win")) {
|
||||||
|
pb = new ProcessBuilder("explorer.exe", dir.toString());
|
||||||
|
} else if (os.contains("mac")) {
|
||||||
|
pb = new ProcessBuilder("open", dir.toString());
|
||||||
|
} else {
|
||||||
|
pb = new ProcessBuilder("xdg-open", dir.toString());
|
||||||
|
}
|
||||||
|
pb.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("[Desktop] Ouverture du dossier impossible : " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ouvre un fichier texte dans l'editeur par defaut (Bloc-notes sous Windows). */
|
||||||
|
public static void openInEditor(Path file) {
|
||||||
|
try {
|
||||||
|
String os = System.getProperty("os.name", "").toLowerCase();
|
||||||
|
ProcessBuilder pb;
|
||||||
|
if (os.contains("win")) {
|
||||||
|
// notepad : toujours present, ouvre proprement un .properties
|
||||||
|
// (dont l'association par defaut n'est pas garantie).
|
||||||
|
pb = new ProcessBuilder("notepad.exe", file.toString());
|
||||||
|
} else if (os.contains("mac")) {
|
||||||
|
pb = new ProcessBuilder("open", "-t", file.toString());
|
||||||
|
} else {
|
||||||
|
pb = new ProcessBuilder("xdg-open", file.toString());
|
||||||
|
}
|
||||||
|
pb.start();
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("[Desktop] Ouverture du fichier impossible : " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path loremindHome() {
|
||||||
|
String home = System.getProperty("loremind.home");
|
||||||
|
if (home != null && !home.isBlank()) return Path.of(home);
|
||||||
|
return Path.of(System.getProperty("user.home"), ".loremind");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.info.BuildProperties;
|
||||||
|
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verification des mises a jour pour l'application de BUREAU (profil "local").
|
||||||
|
* <p>
|
||||||
|
* Contrairement au mode Docker (registry + Watchtower, cf.
|
||||||
|
* {@link com.loremind.infrastructure.updates.UpdateCheckService}), il n'y a pas
|
||||||
|
* de mise a jour automatique : on interroge l'API <b>GitHub Releases</b> pour la
|
||||||
|
* derniere release STABLE, on compare a la version courante du binaire, et si
|
||||||
|
* une version plus recente existe on le signale (via l'icone systray, cf.
|
||||||
|
* {@link SystemTrayManager}). L'utilisateur telecharge puis lance le nouvel
|
||||||
|
* installeur (MSI de meme UpgradeCode = mise a jour en place).
|
||||||
|
* <p>
|
||||||
|
* {@code /releases/latest} ne renvoie que les releases stables (pas les
|
||||||
|
* prereleases) : les utilisateurs stables ne sont donc pas notifies des betas.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@Profile("local")
|
||||||
|
public class DesktopUpdateService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DesktopUpdateService.class);
|
||||||
|
|
||||||
|
private final RestTemplate http;
|
||||||
|
private final boolean enabled;
|
||||||
|
private final String releasesApiUrl;
|
||||||
|
/** Version semver du binaire courant (ex: "0.14.0"), ou null en dev sans build-info. */
|
||||||
|
private final String currentVersion;
|
||||||
|
|
||||||
|
public DesktopUpdateService(
|
||||||
|
RestTemplateBuilder builder,
|
||||||
|
@Value("${desktop.update.enabled:true}") boolean enabled,
|
||||||
|
@Value("${desktop.update.releases-api-url:https://api.github.com/repos/IGMLcreation/LoreMind/releases/latest}") String releasesApiUrl,
|
||||||
|
@Nullable BuildProperties buildProperties) {
|
||||||
|
this.http = builder
|
||||||
|
.setConnectTimeout(Duration.ofSeconds(5))
|
||||||
|
.setReadTimeout(Duration.ofSeconds(10))
|
||||||
|
.build();
|
||||||
|
this.enabled = enabled;
|
||||||
|
this.releasesApiUrl = releasesApiUrl;
|
||||||
|
this.currentVersion = buildProperties != null ? buildProperties.getVersion() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interroge GitHub Releases. Retourne les infos de mise a jour SI une version
|
||||||
|
* plus recente que la version courante existe, sinon {@code Optional.empty()}
|
||||||
|
* (a jour, desactive, ou verification impossible — jamais d'exception propagee).
|
||||||
|
*/
|
||||||
|
public Optional<UpdateInfo> checkForUpdate() {
|
||||||
|
if (!enabled || currentVersion == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
// GitHub exige un User-Agent ; l'Accept versionne l'API.
|
||||||
|
headers.set(HttpHeaders.USER_AGENT, "LoreMind-Desktop");
|
||||||
|
headers.set(HttpHeaders.ACCEPT, "application/vnd.github+json");
|
||||||
|
|
||||||
|
ResponseEntity<JsonNode> resp = http.exchange(
|
||||||
|
releasesApiUrl, HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class);
|
||||||
|
JsonNode body = resp.getBody();
|
||||||
|
if (body == null || body.path("tag_name").isMissingNode()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
String tag = body.path("tag_name").asText(""); // ex: "v0.15.0"
|
||||||
|
String releaseUrl = body.path("html_url").asText(null); // page de la release
|
||||||
|
String latest = tag.startsWith("v") ? tag.substring(1) : tag;
|
||||||
|
|
||||||
|
if (!latest.isBlank() && compareSemver(currentVersion, latest) < 0) {
|
||||||
|
log.info("[Update] Nouvelle version disponible : {} (courante : {})", latest, currentVersion);
|
||||||
|
return Optional.of(new UpdateInfo(currentVersion, latest, releaseUrl));
|
||||||
|
}
|
||||||
|
log.info("[Update] A jour (courante : {}, derniere release : {}).", currentVersion, latest);
|
||||||
|
return Optional.empty();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Hors-ligne, rate-limit GitHub, etc. : non bloquant, on ne notifie juste pas.
|
||||||
|
log.info("[Update] Verification GitHub Releases impossible : {}", e.getMessage());
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Infos d'une mise a jour disponible. */
|
||||||
|
public record UpdateInfo(String currentVersion, String latestVersion, String releaseUrl) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare deux versions MAJOR.MINOR.PATCH (suffixe -beta/-rc ignore).
|
||||||
|
* @return <0 si a<b, 0 si egales, >0 si a>b.
|
||||||
|
*/
|
||||||
|
static int compareSemver(String a, String b) {
|
||||||
|
int[] va = parse(a);
|
||||||
|
int[] vb = parse(b);
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
int cmp = Integer.compare(va[i], vb[i]);
|
||||||
|
if (cmp != 0) return cmp;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] parse(String version) {
|
||||||
|
String core = version.split("[-+]", 2)[0]; // retire -beta, -rc, +build...
|
||||||
|
String[] parts = core.split("\\.");
|
||||||
|
int[] out = new int[3];
|
||||||
|
for (int i = 0; i < 3 && i < parts.length; i++) {
|
||||||
|
try {
|
||||||
|
out[i] = Integer.parseInt(parts[i].trim());
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
out[i] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration UTILISATEUR du mode bureau, dans un fichier éditable
|
||||||
|
* {@code ~/.loremind/loremind.properties} (port HTTP, identifiants admin).
|
||||||
|
* <p>
|
||||||
|
* Pourquoi un fichier et pas l'UI : le port et le mot de passe admin sont requis
|
||||||
|
* AVANT que le serveur (et donc l'UI web) ne démarre — impossible de les régler
|
||||||
|
* depuis l'app elle-même. Un fichier texte simple, lu au démarrage, est le
|
||||||
|
* pattern standard d'une app de bureau. Les modifs prennent effet au prochain
|
||||||
|
* lancement.
|
||||||
|
* <p>
|
||||||
|
* - {@code server.port} : lu ici (résolution du port) ET par Spring.
|
||||||
|
* - {@code admin.username} / {@code admin.password} : chargés par Spring via
|
||||||
|
* {@code spring.config.import} (cf. application-local.properties) — ils
|
||||||
|
* surchargent les défauts du profil local.
|
||||||
|
* <p>
|
||||||
|
* Repli de port : si le port configuré est occupé, on en choisit un libre
|
||||||
|
* automatiquement (évite un échec de démarrage cryptique sur conflit de port)
|
||||||
|
* et on écrit le port réellement utilisé dans {@code ~/.loremind/.port} pour que
|
||||||
|
* l'ouverture du navigateur (instance gagnante OU 2e double-clic) cible la bonne URL.
|
||||||
|
*/
|
||||||
|
public final class DesktopUserConfig {
|
||||||
|
|
||||||
|
private DesktopUserConfig() {}
|
||||||
|
|
||||||
|
private static final String DEFAULT_TEMPLATE = """
|
||||||
|
# ============================================================
|
||||||
|
# Configuration locale de LoreMind (mode bureau)
|
||||||
|
# ------------------------------------------------------------
|
||||||
|
# Modifiez ces valeurs puis RELANCEZ LoreMind pour appliquer.
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
# Port HTTP local de l'application (http://localhost:<port>).
|
||||||
|
# Si ce port est deja occupe par une autre application, LoreMind
|
||||||
|
# choisira automatiquement un autre port libre au demarrage.
|
||||||
|
server.port=8080
|
||||||
|
|
||||||
|
# Identifiants de la page Parametres (acces admin).
|
||||||
|
# Accessible uniquement en local sur cette machine.
|
||||||
|
admin.username=admin
|
||||||
|
admin.password=admin
|
||||||
|
""";
|
||||||
|
|
||||||
|
/** Chemin du fichier de config utilisateur (pour l'ouvrir depuis le menu systray). */
|
||||||
|
public static Path getConfigFile() {
|
||||||
|
return configFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dossier de données/config de l'instance ({@code ~/.loremind}). */
|
||||||
|
public static Path getHomeDir() {
|
||||||
|
return loremindHome();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Crée le fichier de config avec des valeurs par défaut commentées s'il n'existe pas. */
|
||||||
|
public static void ensureExists() {
|
||||||
|
Path file = configFile();
|
||||||
|
if (Files.exists(file)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Files.createDirectories(file.getParent());
|
||||||
|
Files.writeString(file, DEFAULT_TEMPLATE);
|
||||||
|
System.out.println("[Desktop] Config utilisateur creee : " + file);
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("[Desktop] Impossible de creer " + file + " : " + e.getMessage()
|
||||||
|
+ " — defauts utilises (port 8080, admin/admin).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout le port à utiliser : le port configuré s'il est libre, sinon un port
|
||||||
|
* libre choisi automatiquement. Publie le résultat dans la propriété système
|
||||||
|
* {@code server.port} (que Spring lira en priorité) et dans {@code ~/.loremind/.port}.
|
||||||
|
*
|
||||||
|
* @return le port effectivement retenu.
|
||||||
|
*/
|
||||||
|
public static int resolveAndPublishPort() {
|
||||||
|
int wanted = configuredPort();
|
||||||
|
int chosen = isPortFree(wanted) ? wanted : findFreePort(wanted);
|
||||||
|
if (chosen != wanted) {
|
||||||
|
System.out.println("[Desktop] Port " + wanted + " occupe — repli sur le port libre " + chosen + ".");
|
||||||
|
}
|
||||||
|
System.setProperty("server.port", String.valueOf(chosen));
|
||||||
|
try {
|
||||||
|
Files.writeString(portFile(), String.valueOf(chosen));
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.err.println("[Desktop] Ecriture du port impossible (" + e.getMessage() + ").");
|
||||||
|
}
|
||||||
|
return chosen;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port sur lequel l'application répond réellement (pour ouvrir le navigateur).
|
||||||
|
* Ordre : propriété système (instance gagnante) → fichier .port (2e double-clic)
|
||||||
|
* → port configuré → 8080.
|
||||||
|
*/
|
||||||
|
public static int runningPort() {
|
||||||
|
String sys = System.getProperty("server.port");
|
||||||
|
if (sys != null && !sys.isBlank()) {
|
||||||
|
try { return Integer.parseInt(sys.trim()); } catch (NumberFormatException ignored) { /* fallthrough */ }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Path p = portFile();
|
||||||
|
if (Files.exists(p)) {
|
||||||
|
return Integer.parseInt(Files.readString(p).trim());
|
||||||
|
}
|
||||||
|
} catch (IOException | NumberFormatException ignored) { /* fallthrough */ }
|
||||||
|
return configuredPort();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Port lu dans le fichier de config utilisateur (défaut 8080). */
|
||||||
|
private static int configuredPort() {
|
||||||
|
Path file = configFile();
|
||||||
|
if (Files.exists(file)) {
|
||||||
|
Properties props = new Properties();
|
||||||
|
try (InputStream in = Files.newInputStream(file)) {
|
||||||
|
props.load(in);
|
||||||
|
String v = props.getProperty("server.port");
|
||||||
|
if (v != null && !v.isBlank()) {
|
||||||
|
return Integer.parseInt(v.trim());
|
||||||
|
}
|
||||||
|
} catch (IOException | NumberFormatException ignored) { /* défaut */ }
|
||||||
|
}
|
||||||
|
return 8080;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isPortFree(int port) {
|
||||||
|
try (ServerSocket s = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"))) {
|
||||||
|
s.setReuseAddress(true);
|
||||||
|
return true;
|
||||||
|
} catch (IOException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int findFreePort(int fallbackIfNone) {
|
||||||
|
try (ServerSocket s = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) {
|
||||||
|
return s.getLocalPort();
|
||||||
|
} catch (IOException e) {
|
||||||
|
return fallbackIfNone; // tres improbable ; on retente le port voulu
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path configFile() {
|
||||||
|
return loremindHome().resolve("loremind.properties");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path portFile() {
|
||||||
|
return loremindHome().resolve(".port");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path loremindHome() {
|
||||||
|
String home = System.getProperty("loremind.home");
|
||||||
|
if (home != null && !home.isBlank()) return Path.of(home);
|
||||||
|
return Path.of(System.getProperty("user.home"), ".loremind");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
package com.loremind.infrastructure.desktop;
|
||||||
|
|
||||||
|
import jakarta.annotation.PreDestroy;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.ConfigurableApplicationContext;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.awt.Color;
|
||||||
|
import java.awt.Font;
|
||||||
|
import java.awt.Graphics2D;
|
||||||
|
import java.awt.Image;
|
||||||
|
import java.awt.MenuItem;
|
||||||
|
import java.awt.PopupMenu;
|
||||||
|
import java.awt.RenderingHints;
|
||||||
|
import java.awt.SystemTray;
|
||||||
|
import java.awt.TrayIcon;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Icone dans la zone de notification (barre des taches) en mode bureau
|
||||||
|
* (profil "local"). Donne a l'utilisateur un controle visible de l'application,
|
||||||
|
* qui tourne sinon en serveur sans fenetre : impossible autrement de la fermer
|
||||||
|
* proprement (fermer l'onglet du navigateur laisse le Core et le Brain tourner).
|
||||||
|
* <p>
|
||||||
|
* Menu : « Ouvrir LoreMind » (ouvre le navigateur) et « Quitter LoreMind »
|
||||||
|
* (ferme le contexte Spring — ce qui declenche le {@code @PreDestroy} de
|
||||||
|
* {@link com.loremind.infrastructure.ai.BrainSidecar} et arrete donc aussi le
|
||||||
|
* Brain — puis termine le process).
|
||||||
|
* <p>
|
||||||
|
* Necessite que le mode headless soit desactive (cf. LoreMindApplication.main,
|
||||||
|
* qui appelle {@code setHeadless(false)} en profil local). Le module
|
||||||
|
* {@code java.desktop} est embarque dans le runtime jpackage.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Profile("local")
|
||||||
|
public class SystemTrayManager {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(SystemTrayManager.class);
|
||||||
|
|
||||||
|
private final ConfigurableApplicationContext context;
|
||||||
|
private final DesktopUpdateService updateService;
|
||||||
|
private TrayIcon trayIcon;
|
||||||
|
private PopupMenu popup;
|
||||||
|
|
||||||
|
public SystemTrayManager(ConfigurableApplicationContext context,
|
||||||
|
DesktopUpdateService updateService) {
|
||||||
|
this.context = context;
|
||||||
|
this.updateService = updateService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void install() {
|
||||||
|
if (!SystemTray.isSupported()) {
|
||||||
|
log.warn("[Tray] Zone de notification non supportee sur ce systeme — "
|
||||||
|
+ "pas d'icone. Pour quitter : menu de la fenetre console, ou gestionnaire des taches.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
popup = new PopupMenu();
|
||||||
|
|
||||||
|
MenuItem open = new MenuItem("Ouvrir LoreMind");
|
||||||
|
open.addActionListener(e -> DesktopSingleInstance.openAppInBrowser());
|
||||||
|
popup.add(open);
|
||||||
|
|
||||||
|
popup.addSeparator();
|
||||||
|
|
||||||
|
// Reglages : ouvre loremind.properties (port, identifiants admin) dans
|
||||||
|
// l'editeur. Les changements prennent effet au prochain demarrage.
|
||||||
|
MenuItem editConfig = new MenuItem("Modifier la configuration (port, identifiants…)");
|
||||||
|
editConfig.addActionListener(e -> {
|
||||||
|
DesktopUserConfig.ensureExists();
|
||||||
|
DesktopSingleInstance.openInEditor(DesktopUserConfig.getConfigFile());
|
||||||
|
});
|
||||||
|
popup.add(editConfig);
|
||||||
|
|
||||||
|
// Acces au dossier de donnees (~/.loremind : base, images, config…).
|
||||||
|
MenuItem openFolder = new MenuItem("Ouvrir le dossier LoreMind");
|
||||||
|
openFolder.addActionListener(e -> DesktopSingleInstance.openFolder(DesktopUserConfig.getHomeDir()));
|
||||||
|
popup.add(openFolder);
|
||||||
|
|
||||||
|
popup.addSeparator();
|
||||||
|
|
||||||
|
MenuItem quit = new MenuItem("Quitter LoreMind");
|
||||||
|
quit.addActionListener(e -> quit());
|
||||||
|
popup.add(quit);
|
||||||
|
|
||||||
|
trayIcon = new TrayIcon(createIcon(), "LoreMind", popup);
|
||||||
|
trayIcon.setImageAutoSize(true);
|
||||||
|
// Double-clic sur l'icone : ouvre l'application dans le navigateur.
|
||||||
|
trayIcon.addActionListener(e -> DesktopSingleInstance.openAppInBrowser());
|
||||||
|
|
||||||
|
SystemTray.getSystemTray().add(trayIcon);
|
||||||
|
log.info("[Tray] Icone installee dans la zone de notification.");
|
||||||
|
|
||||||
|
// Verification de mise a jour en arriere-plan (appel reseau GitHub) :
|
||||||
|
// ne bloque pas le demarrage ; met a jour le menu/notifie si dispo.
|
||||||
|
new Thread(this::checkForUpdate, "loremind-update-check").start();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Echec non bloquant : l'app reste utilisable, seul le confort de l'icone manque.
|
||||||
|
log.warn("[Tray] Installation de l'icone impossible : {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interroge GitHub Releases ; si une version plus recente existe, ajoute un
|
||||||
|
* item de menu « Telecharger » et affiche une bulle de notification. L'item
|
||||||
|
* ouvre la page de la release dans le navigateur (telechargement manuel du
|
||||||
|
* nouvel installeur).
|
||||||
|
*/
|
||||||
|
private void checkForUpdate() {
|
||||||
|
updateService.checkForUpdate().ifPresent(info -> {
|
||||||
|
String label = "⬇ Telecharger la mise a jour (v" + info.latestVersion() + ")";
|
||||||
|
MenuItem update = new MenuItem(label);
|
||||||
|
update.addActionListener(e -> DesktopSingleInstance.openUrl(info.releaseUrl()));
|
||||||
|
// En tete de menu pour la visibilite, suivi d'un separateur.
|
||||||
|
popup.insert(update, 0);
|
||||||
|
popup.insertSeparator(1);
|
||||||
|
|
||||||
|
trayIcon.displayMessage(
|
||||||
|
"LoreMind — mise a jour disponible",
|
||||||
|
"Version " + info.latestVersion() + " disponible (vous avez " + info.currentVersion()
|
||||||
|
+ "). Menu de l'icone → Telecharger.",
|
||||||
|
TrayIcon.MessageType.INFO);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Arret propre depuis le menu « Quitter » : on retire l'icone puis on ferme
|
||||||
|
* le contexte Spring dans un thread dedie (l'action s'execute sur l'EDT AWT ;
|
||||||
|
* fermer le contexte + arreter Tomcat/Brain depuis l'EDT pourrait le bloquer).
|
||||||
|
*/
|
||||||
|
private void quit() {
|
||||||
|
log.info("[Tray] Demande de fermeture de l'application.");
|
||||||
|
new Thread(() -> {
|
||||||
|
int code = SpringApplication.exit(context, () -> 0);
|
||||||
|
System.exit(code);
|
||||||
|
}, "loremind-shutdown").start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Retire l'icone si le contexte se ferme par une autre voie (ex. Ctrl+C). */
|
||||||
|
@PreDestroy
|
||||||
|
public void remove() {
|
||||||
|
if (trayIcon != null) {
|
||||||
|
SystemTray.getSystemTray().remove(trayIcon);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Genere une petite icone (carre arrondi violet « L ») sans dependre d'un
|
||||||
|
* fichier image — robuste quel que soit l'empaquetage.
|
||||||
|
*/
|
||||||
|
private Image createIcon() {
|
||||||
|
int size = 16;
|
||||||
|
BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
|
||||||
|
Graphics2D g = img.createGraphics();
|
||||||
|
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||||
|
g.setColor(new Color(0x8B, 0x5C, 0xF6)); // violet de marque LoreMind
|
||||||
|
g.fillRoundRect(0, 0, size, size, 5, 5);
|
||||||
|
g.setColor(Color.WHITE);
|
||||||
|
g.setFont(new Font("SansSerif", Font.BOLD, 12));
|
||||||
|
g.drawString("L", 4, 13);
|
||||||
|
g.dispose();
|
||||||
|
return img;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,10 +4,14 @@ import com.loremind.infrastructure.persistence.entity.ImageJpaEntity;
|
|||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Repository Spring Data JPA pour ImageJpaEntity.
|
* Repository Spring Data JPA pour ImageJpaEntity.
|
||||||
* Ne contient aucune requete custom pour l'instant : CRUD standard suffit.
|
|
||||||
*/
|
*/
|
||||||
@Repository
|
@Repository
|
||||||
public interface ImageJpaRepository extends JpaRepository<ImageJpaEntity, Long> {
|
public interface ImageJpaRepository extends JpaRepository<ImageJpaEntity, Long> {
|
||||||
|
|
||||||
|
/** Recherche par cle de stockage (unique). Utilise par l'import de contenu. */
|
||||||
|
Optional<ImageJpaEntity> findByStorageKey(String storageKey);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package com.loremind.infrastructure.storage;
|
||||||
|
|
||||||
|
import com.loremind.domain.images.ports.ImageStorage;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adaptateur d'infrastructure : implemente le port ImageStorage en stockant
|
||||||
|
* les binaires sur le SYSTEME DE FICHIERS local.
|
||||||
|
* <p>
|
||||||
|
* Pendant a {@link MinioImageStorageAdapter} pour le mode "local-first"
|
||||||
|
* (application de bureau empaquetee via jpackage, sans Docker ni MinIO).
|
||||||
|
* Active uniquement quand {@code storage.backend=filesystem} ; en l'absence
|
||||||
|
* de cette propriete, c'est l'adaptateur MinIO qui prend le relais (defaut).
|
||||||
|
* <p>
|
||||||
|
* On reutilise EXACTEMENT le meme schema de cle que MinIO ({@code images/UUID.ext})
|
||||||
|
* pour que les cles restent interchangeables entre les deux backends : une base
|
||||||
|
* migree de l'un vers l'autre continue de fonctionner sans reecriture.
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "storage.backend", havingValue = "filesystem")
|
||||||
|
public class FilesystemImageStorageAdapter implements ImageStorage {
|
||||||
|
|
||||||
|
private final Path root;
|
||||||
|
|
||||||
|
public FilesystemImageStorageAdapter(@Value("${storage.filesystem.path}") String basePath) {
|
||||||
|
this.root = Path.of(basePath).toAbsolutePath().normalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
void ensureRootExists() {
|
||||||
|
try {
|
||||||
|
Files.createDirectories(root);
|
||||||
|
System.out.println("[Storage] Backend filesystem actif — racine : " + root);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Impossible de creer le dossier de stockage : " + root, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String upload(String filename, String contentType, InputStream data, long sizeBytes) {
|
||||||
|
String storageKey = generateStorageKey(filename);
|
||||||
|
Path target = resolveKey(storageKey);
|
||||||
|
try {
|
||||||
|
Files.createDirectories(target.getParent());
|
||||||
|
Files.copy(data, target);
|
||||||
|
return storageKey;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Echec de l'ecriture de l'image sur disque : " + target, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void store(String storageKey, String contentType, InputStream data, long sizeBytes) {
|
||||||
|
Path target = resolveKey(storageKey);
|
||||||
|
try {
|
||||||
|
Files.createDirectories(target.getParent());
|
||||||
|
// Ecrase si la cle existe deja (contrat de store-avec-cle).
|
||||||
|
Files.copy(data, target, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Echec de l'ecriture de l'image sur disque (cle imposee) : " + target, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public InputStream download(String storageKey) {
|
||||||
|
Path source = resolveKey(storageKey);
|
||||||
|
if (!Files.exists(source)) {
|
||||||
|
// Cle orpheline : meme contrat que MinIO (null plutot qu'exception).
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Files.newInputStream(source);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Echec de la lecture de l'image : " + source, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(String storageKey) {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(resolveKey(storageKey));
|
||||||
|
} catch (IOException e) {
|
||||||
|
// Suppression idempotente : on loggue mais on ne propage pas (cf. MinIO).
|
||||||
|
System.err.println("[Storage] Erreur suppression (non bloquante) : " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resout une cle opaque en chemin physique, en se premunissant contre la
|
||||||
|
* traversee de repertoire : le chemin resolu DOIT rester sous {@code root}
|
||||||
|
* (une cle malveillante du type {@code ../../etc/passwd} est rejetee).
|
||||||
|
*/
|
||||||
|
private Path resolveKey(String storageKey) {
|
||||||
|
Path resolved = root.resolve(storageKey).normalize();
|
||||||
|
if (!resolved.startsWith(root)) {
|
||||||
|
throw new IllegalArgumentException("Cle de stockage invalide (hors racine) : " + storageKey);
|
||||||
|
}
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Identique a MinioImageStorageAdapter : cle unique + extension d'origine. */
|
||||||
|
private String generateStorageKey(String originalFilename) {
|
||||||
|
return "images/" + UUID.randomUUID() + extractExtension(originalFilename);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractExtension(String filename) {
|
||||||
|
if (filename == null) return "";
|
||||||
|
int dot = filename.lastIndexOf('.');
|
||||||
|
if (dot < 0 || dot == filename.length() - 1) return "";
|
||||||
|
String ext = filename.substring(dot).toLowerCase();
|
||||||
|
// On n'accepte que les extensions connues pour eviter les injections de path.
|
||||||
|
return ext.matches("\\.(jpg|jpeg|png|webp|gif)") ? ext : "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import io.minio.MakeBucketArgs;
|
|||||||
import io.minio.MinioClient;
|
import io.minio.MinioClient;
|
||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
@@ -14,8 +15,13 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
* Expose un bean MinioClient singleton injecte dans MinioImageStorageAdapter.
|
* Expose un bean MinioClient singleton injecte dans MinioImageStorageAdapter.
|
||||||
* S'assure au demarrage que le bucket configure existe (filet de securite :
|
* S'assure au demarrage que le bucket configure existe (filet de securite :
|
||||||
* normalement docker-compose/minio-init l'a deja cree).
|
* normalement docker-compose/minio-init l'a deja cree).
|
||||||
|
* <p>
|
||||||
|
* Desactive en mode local-first ({@code storage.backend=filesystem}) : aucun
|
||||||
|
* client MinIO n'est alors instancie, donc aucune tentative de connexion au
|
||||||
|
* boot. Defaut = actif (propriete absente ou {@code minio}).
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration
|
||||||
|
@ConditionalOnProperty(name = "storage.backend", havingValue = "minio", matchIfMissing = true)
|
||||||
public class MinioConfig {
|
public class MinioConfig {
|
||||||
|
|
||||||
@Value("${minio.endpoint}")
|
@Value("${minio.endpoint}")
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import io.minio.PutObjectArgs;
|
|||||||
import io.minio.RemoveObjectArgs;
|
import io.minio.RemoveObjectArgs;
|
||||||
import io.minio.errors.ErrorResponseException;
|
import io.minio.errors.ErrorResponseException;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -17,8 +18,13 @@ import java.util.UUID;
|
|||||||
* MinIO (compatible S3) comme backend de stockage d'objets.
|
* MinIO (compatible S3) comme backend de stockage d'objets.
|
||||||
* <p>
|
* <p>
|
||||||
* Le domaine ne sait rien de MinIO : il manipule juste des cles opaques.
|
* Le domaine ne sait rien de MinIO : il manipule juste des cles opaques.
|
||||||
|
* <p>
|
||||||
|
* Backend par defaut ({@code storage.backend=minio} ou propriete absente).
|
||||||
|
* Le mode local-first le remplace par {@link FilesystemImageStorageAdapter}
|
||||||
|
* via {@code storage.backend=filesystem}.
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "storage.backend", havingValue = "minio", matchIfMissing = true)
|
||||||
public class MinioImageStorageAdapter implements ImageStorage {
|
public class MinioImageStorageAdapter implements ImageStorage {
|
||||||
|
|
||||||
private final MinioClient minioClient;
|
private final MinioClient minioClient;
|
||||||
@@ -48,6 +54,22 @@ public class MinioImageStorageAdapter implements ImageStorage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void store(String storageKey, String contentType, InputStream data, long sizeBytes) {
|
||||||
|
try {
|
||||||
|
minioClient.putObject(
|
||||||
|
PutObjectArgs.builder()
|
||||||
|
.bucket(bucket)
|
||||||
|
.object(storageKey)
|
||||||
|
.stream(data, sizeBytes, -1)
|
||||||
|
.contentType(contentType)
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Echec du store MinIO (cle imposee) : " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public InputStream download(String storageKey) {
|
public InputStream download(String storageKey) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,350 @@
|
|||||||
|
package com.loremind.infrastructure.transfer;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
|
import com.loremind.domain.images.ports.ImageStorage;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.*;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.*;
|
||||||
|
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||||
|
import org.springframework.boot.info.BuildProperties;
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service d'EXPORT du "contenu" en format logique (JSON) portable.
|
||||||
|
* <p>
|
||||||
|
* Construit un {@link ContentExport} a partir des entites JPA puis le serialise
|
||||||
|
* dans un .zip contenant :
|
||||||
|
* <ul>
|
||||||
|
* <li>{@code manifest.json} — metadonnees (version de format, version app, date)</li>
|
||||||
|
* <li>{@code data.json} — tout le contenu (pretty-printed)</li>
|
||||||
|
* <li>{@code images/<storageKey>} — un binaire par image referencee</li>
|
||||||
|
* </ul>
|
||||||
|
* Volontairement DECOUPLE de la base : c'est un export logique, pas un dump,
|
||||||
|
* pour fonctionner entre Postgres (Docker) et H2 (local).
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class ExportService {
|
||||||
|
|
||||||
|
private static final int FORMAT_VERSION = 1;
|
||||||
|
|
||||||
|
// Réutilise le converter JPA pour (dé)sérialiser les prérequis dans le MÊME
|
||||||
|
// format que la base (discriminant "kind"), au lieu de Jackson polymorphe.
|
||||||
|
private static final PrerequisiteListJsonConverter PREREQ_CONVERTER = new PrerequisiteListJsonConverter();
|
||||||
|
|
||||||
|
private final GameSystemJpaRepository gameSystemRepo;
|
||||||
|
private final LoreJpaRepository loreRepo;
|
||||||
|
private final LoreNodeJpaRepository loreNodeRepo;
|
||||||
|
private final TemplateJpaRepository templateRepo;
|
||||||
|
private final PageJpaRepository pageRepo;
|
||||||
|
private final CampaignJpaRepository campaignRepo;
|
||||||
|
private final ArcJpaRepository arcRepo;
|
||||||
|
private final ChapterJpaRepository chapterRepo;
|
||||||
|
private final SceneJpaRepository sceneRepo;
|
||||||
|
private final CharacterJpaRepository characterRepo;
|
||||||
|
private final NpcJpaRepository npcRepo;
|
||||||
|
private final EnemyJpaRepository enemyRepo;
|
||||||
|
private final ItemCatalogJpaRepository itemCatalogRepo;
|
||||||
|
private final RandomTableJpaRepository randomTableRepo;
|
||||||
|
private final ImageJpaRepository imageRepo;
|
||||||
|
private final ImageStorage imageStorage;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final String appVersion;
|
||||||
|
|
||||||
|
public ExportService(GameSystemJpaRepository gameSystemRepo,
|
||||||
|
LoreJpaRepository loreRepo,
|
||||||
|
LoreNodeJpaRepository loreNodeRepo,
|
||||||
|
TemplateJpaRepository templateRepo,
|
||||||
|
PageJpaRepository pageRepo,
|
||||||
|
CampaignJpaRepository campaignRepo,
|
||||||
|
ArcJpaRepository arcRepo,
|
||||||
|
ChapterJpaRepository chapterRepo,
|
||||||
|
SceneJpaRepository sceneRepo,
|
||||||
|
CharacterJpaRepository characterRepo,
|
||||||
|
NpcJpaRepository npcRepo,
|
||||||
|
EnemyJpaRepository enemyRepo,
|
||||||
|
ItemCatalogJpaRepository itemCatalogRepo,
|
||||||
|
RandomTableJpaRepository randomTableRepo,
|
||||||
|
ImageJpaRepository imageRepo,
|
||||||
|
ImageStorage imageStorage,
|
||||||
|
ObjectMapper objectMapper,
|
||||||
|
@Nullable BuildProperties buildProperties) {
|
||||||
|
this.gameSystemRepo = gameSystemRepo;
|
||||||
|
this.loreRepo = loreRepo;
|
||||||
|
this.loreNodeRepo = loreNodeRepo;
|
||||||
|
this.templateRepo = templateRepo;
|
||||||
|
this.pageRepo = pageRepo;
|
||||||
|
this.campaignRepo = campaignRepo;
|
||||||
|
this.arcRepo = arcRepo;
|
||||||
|
this.chapterRepo = chapterRepo;
|
||||||
|
this.sceneRepo = sceneRepo;
|
||||||
|
this.characterRepo = characterRepo;
|
||||||
|
this.npcRepo = npcRepo;
|
||||||
|
this.enemyRepo = enemyRepo;
|
||||||
|
this.itemCatalogRepo = itemCatalogRepo;
|
||||||
|
this.randomTableRepo = randomTableRepo;
|
||||||
|
this.imageRepo = imageRepo;
|
||||||
|
this.imageStorage = imageStorage;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
this.appVersion = buildProperties != null ? buildProperties.getVersion() : "dev";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Charge toutes les entites du perimetre et les mappe vers les DTO plats.
|
||||||
|
*
|
||||||
|
* @param exportedAt horodatage ISO stampe par la couche appelante (controller)
|
||||||
|
*/
|
||||||
|
public ContentExport buildExport(String exportedAt) {
|
||||||
|
ContentExport.Manifest manifest =
|
||||||
|
new ContentExport.Manifest(FORMAT_VERSION, appVersion, exportedAt);
|
||||||
|
|
||||||
|
List<ContentExport.GameSystemDto> gameSystems = gameSystemRepo.findAll().stream()
|
||||||
|
.map(this::toGameSystemDto).toList();
|
||||||
|
List<ContentExport.LoreDto> lores = loreRepo.findAll().stream()
|
||||||
|
.map(this::toLoreDto).toList();
|
||||||
|
List<ContentExport.LoreNodeDto> loreNodes = loreNodeRepo.findAll().stream()
|
||||||
|
.map(this::toLoreNodeDto).toList();
|
||||||
|
List<ContentExport.TemplateDto> templates = templateRepo.findAll().stream()
|
||||||
|
.map(this::toTemplateDto).toList();
|
||||||
|
List<ContentExport.PageDto> pages = pageRepo.findAll().stream()
|
||||||
|
.map(this::toPageDto).toList();
|
||||||
|
List<ContentExport.CampaignDto> campaigns = campaignRepo.findAll().stream()
|
||||||
|
.map(this::toCampaignDto).toList();
|
||||||
|
List<ContentExport.ArcDto> arcs = arcRepo.findAll().stream()
|
||||||
|
.map(this::toArcDto).toList();
|
||||||
|
List<ContentExport.ChapterDto> chapters = chapterRepo.findAll().stream()
|
||||||
|
.map(this::toChapterDto).toList();
|
||||||
|
List<ContentExport.SceneDto> scenes = sceneRepo.findAll().stream()
|
||||||
|
.map(this::toSceneDto).toList();
|
||||||
|
List<ContentExport.CharacterDto> characters = characterRepo.findAll().stream()
|
||||||
|
.map(this::toCharacterDto).toList();
|
||||||
|
List<ContentExport.NpcDto> npcs = npcRepo.findAll().stream()
|
||||||
|
.map(this::toNpcDto).toList();
|
||||||
|
List<ContentExport.EnemyDto> enemies = enemyRepo.findAll().stream()
|
||||||
|
.map(this::toEnemyDto).toList();
|
||||||
|
List<ContentExport.ItemCatalogDto> itemCatalogs = itemCatalogRepo.findAll().stream()
|
||||||
|
.map(this::toItemCatalogDto).toList();
|
||||||
|
List<ContentExport.RandomTableDto> randomTables = randomTableRepo.findAll().stream()
|
||||||
|
.map(this::toRandomTableDto).toList();
|
||||||
|
List<ContentExport.ImageDto> images = imageRepo.findAll().stream()
|
||||||
|
.map(this::toImageDto).toList();
|
||||||
|
|
||||||
|
return new ContentExport(manifest, gameSystems, lores, loreNodes, templates,
|
||||||
|
pages, campaigns, arcs, chapters, scenes, characters, npcs, enemies,
|
||||||
|
itemCatalogs, randomTables, images);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serialise un export dans le flux fourni au format .zip.
|
||||||
|
* <p>
|
||||||
|
* Les binaires d'images ne sont ecrits que pour les storageKeys REFERENCES
|
||||||
|
* par les entites exportees (illustration/map/portrait/header/imageValues),
|
||||||
|
* pas pour toute la table images — on evite de trimballer des orphelins.
|
||||||
|
*/
|
||||||
|
public void writeZip(ContentExport export, OutputStream out) {
|
||||||
|
try (ZipOutputStream zip = new ZipOutputStream(out)) {
|
||||||
|
// manifest.json
|
||||||
|
zip.putNextEntry(new ZipEntry("manifest.json"));
|
||||||
|
zip.write(objectMapper.writerWithDefaultPrettyPrinter()
|
||||||
|
.writeValueAsBytes(export.manifest()));
|
||||||
|
zip.closeEntry();
|
||||||
|
|
||||||
|
// data.json
|
||||||
|
zip.putNextEntry(new ZipEntry("data.json"));
|
||||||
|
zip.write(objectMapper.copy()
|
||||||
|
.enable(SerializationFeature.INDENT_OUTPUT)
|
||||||
|
.writeValueAsBytes(export));
|
||||||
|
zip.closeEntry();
|
||||||
|
|
||||||
|
// Binaires images : uniquement ceux reellement references.
|
||||||
|
Set<String> referenced = collectReferencedStorageKeys(export);
|
||||||
|
Set<String> written = new LinkedHashSet<>();
|
||||||
|
for (String key : referenced) {
|
||||||
|
if (key == null || key.isBlank() || !written.add(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try (InputStream data = imageStorage.download(key)) {
|
||||||
|
if (data == null) {
|
||||||
|
continue; // cle orpheline : on ignore silencieusement
|
||||||
|
}
|
||||||
|
zip.putNextEntry(new ZipEntry("images/" + key));
|
||||||
|
data.transferTo(zip);
|
||||||
|
zip.closeEntry();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Echec de la generation du zip d'export", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collecte tous les storageKeys references par le contenu exporte :
|
||||||
|
* Arc/Chapter/Scene (illustration + map), Character/Npc/Enemy
|
||||||
|
* (portrait + header + imageValues), Page (imageValues).
|
||||||
|
*/
|
||||||
|
private Set<String> collectReferencedStorageKeys(ContentExport export) {
|
||||||
|
Set<String> keys = new LinkedHashSet<>();
|
||||||
|
for (ContentExport.ArcDto a : export.arcs()) {
|
||||||
|
addAll(keys, a.illustrationImageIds());
|
||||||
|
addAll(keys, a.mapImageIds());
|
||||||
|
}
|
||||||
|
for (ContentExport.ChapterDto c : export.chapters()) {
|
||||||
|
addAll(keys, c.illustrationImageIds());
|
||||||
|
addAll(keys, c.mapImageIds());
|
||||||
|
}
|
||||||
|
for (ContentExport.SceneDto s : export.scenes()) {
|
||||||
|
addAll(keys, s.illustrationImageIds());
|
||||||
|
addAll(keys, s.mapImageIds());
|
||||||
|
}
|
||||||
|
for (ContentExport.CharacterDto c : export.characters()) {
|
||||||
|
add(keys, c.portraitImageId());
|
||||||
|
add(keys, c.headerImageId());
|
||||||
|
addImageValues(keys, c.imageValues());
|
||||||
|
}
|
||||||
|
for (ContentExport.NpcDto n : export.npcs()) {
|
||||||
|
add(keys, n.portraitImageId());
|
||||||
|
add(keys, n.headerImageId());
|
||||||
|
addImageValues(keys, n.imageValues());
|
||||||
|
}
|
||||||
|
for (ContentExport.EnemyDto e : export.enemies()) {
|
||||||
|
add(keys, e.portraitImageId());
|
||||||
|
add(keys, e.headerImageId());
|
||||||
|
addImageValues(keys, e.imageValues());
|
||||||
|
}
|
||||||
|
for (ContentExport.PageDto p : export.pages()) {
|
||||||
|
addImageValues(keys, p.imageValues());
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void add(Set<String> keys, String key) {
|
||||||
|
if (key != null && !key.isBlank()) keys.add(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addAll(Set<String> keys, List<String> list) {
|
||||||
|
if (list != null) list.forEach(k -> add(keys, k));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addImageValues(Set<String> keys, java.util.Map<String, List<String>> imageValues) {
|
||||||
|
if (imageValues != null) imageValues.values().forEach(l -> addAll(keys, l));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Mappers entite -> DTO -----
|
||||||
|
|
||||||
|
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
||||||
|
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
||||||
|
e.getEnemyTemplate(), e.getAuthor(), e.isPublic());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
||||||
|
return new ContentExport.LoreDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getNodeCount(), e.getPageCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.LoreNodeDto toLoreNodeDto(LoreNodeJpaEntity e) {
|
||||||
|
return new ContentExport.LoreNodeDto(e.getId(), e.getName(), e.getIcon(),
|
||||||
|
e.getParentId(), e.getLoreId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.TemplateDto toTemplateDto(TemplateJpaEntity e) {
|
||||||
|
return new ContentExport.TemplateDto(e.getId(), e.getLoreId(), e.getName(),
|
||||||
|
e.getDescription(), e.getDefaultNodeId(), e.getFields());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.PageDto toPageDto(PageJpaEntity e) {
|
||||||
|
return new ContentExport.PageDto(e.getId(), e.getLoreId(), e.getNodeId(),
|
||||||
|
e.getTemplateId(), e.getTitle(), e.getValues(), e.getImageValues(),
|
||||||
|
e.getKeyValueValues(), e.getTableValues(), e.getNotes(), e.getTags(),
|
||||||
|
e.getRelatedPageIds());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.CampaignDto toCampaignDto(CampaignJpaEntity e) {
|
||||||
|
return new ContentExport.CampaignDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getArcsCount(), e.getLoreId(), e.getGameSystemId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.ArcDto toArcDto(ArcJpaEntity e) {
|
||||||
|
return new ContentExport.ArcDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getCampaignId(), e.getOrder(),
|
||||||
|
e.getType() != null ? e.getType().name() : null,
|
||||||
|
e.getIcon(), e.getThemes(), e.getStakes(), e.getGmNotes(),
|
||||||
|
e.getRewards(), e.getResolution(), e.getRelatedPageIds(),
|
||||||
|
e.getIllustrationImageIds(), e.getMapImageIds());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.ChapterDto toChapterDto(ChapterJpaEntity e) {
|
||||||
|
return new ContentExport.ChapterDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getArcId(), e.getOrder(), PREREQ_CONVERTER.convertToDatabaseColumn(e.getPrerequisites()), e.getIcon(),
|
||||||
|
e.getGmNotes(), e.getPlayerObjectives(), e.getNarrativeStakes(),
|
||||||
|
e.getRelatedPageIds(), e.getIllustrationImageIds(), e.getMapImageIds());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.SceneDto toSceneDto(SceneJpaEntity e) {
|
||||||
|
return new ContentExport.SceneDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getChapterId(), e.getOrder(), e.getIcon(), e.getLocation(),
|
||||||
|
e.getTiming(), e.getAtmosphere(), e.getPlayerNarration(),
|
||||||
|
e.getGmSecretNotes(), e.getChoicesConsequences(), e.getCombatDifficulty(),
|
||||||
|
e.getEnemies(), e.getEnemyIds(), e.getRelatedPageIds(),
|
||||||
|
e.getIllustrationImageIds(), e.getMapImageIds(), e.getBranches(), e.getRooms());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.CharacterDto toCharacterDto(CharacterJpaEntity e) {
|
||||||
|
return new ContentExport.CharacterDto(e.getId(), e.getName(), e.getPortraitImageId(),
|
||||||
|
e.getHeaderImageId(), e.getValues(), e.getImageValues(), e.getKeyValueValues(),
|
||||||
|
e.getCampaignId(), e.getPlaythroughId(), e.getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.NpcDto toNpcDto(NpcJpaEntity e) {
|
||||||
|
return new ContentExport.NpcDto(e.getId(), e.getName(), e.getPortraitImageId(),
|
||||||
|
e.getHeaderImageId(), e.getValues(), e.getImageValues(), e.getKeyValueValues(),
|
||||||
|
e.getCampaignId(), e.getRelatedPageIds(), e.getFolder(), e.getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.EnemyDto toEnemyDto(EnemyJpaEntity e) {
|
||||||
|
return new ContentExport.EnemyDto(e.getId(), e.getName(), e.getLevel(), e.getFolder(),
|
||||||
|
e.getPortraitImageId(), e.getHeaderImageId(), e.getValues(), e.getImageValues(),
|
||||||
|
e.getKeyValueValues(), e.getCampaignId(), e.getOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.ItemCatalogDto toItemCatalogDto(ItemCatalogJpaEntity e) {
|
||||||
|
List<ContentExport.CatalogItemDto> items = new ArrayList<>();
|
||||||
|
if (e.getItems() != null) {
|
||||||
|
for (CatalogItemJpaEntity i : e.getItems()) {
|
||||||
|
items.add(new ContentExport.CatalogItemDto(i.getId(), i.getName(),
|
||||||
|
i.getPrice(), i.getCategory(), i.getDescription(), i.getPosition()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new ContentExport.ItemCatalogDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getIcon(), e.getCampaignId(), e.getOrder(), items);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.RandomTableDto toRandomTableDto(RandomTableJpaEntity e) {
|
||||||
|
List<ContentExport.RandomTableEntryDto> entries = new ArrayList<>();
|
||||||
|
if (e.getEntries() != null) {
|
||||||
|
for (RandomTableEntryJpaEntity en : e.getEntries()) {
|
||||||
|
entries.add(new ContentExport.RandomTableEntryDto(en.getId(), en.getMinRoll(),
|
||||||
|
en.getMaxRoll(), en.getLabel(), en.getDetail(), en.getPosition()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new ContentExport.RandomTableDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
|
e.getDiceFormula(), e.getIcon(), e.getCampaignId(), e.getOrder(), entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ContentExport.ImageDto toImageDto(ImageJpaEntity e) {
|
||||||
|
return new ContentExport.ImageDto(e.getId(), e.getFilename(), e.getContentType(),
|
||||||
|
e.getSizeBytes(), e.getStorageKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.loremind.infrastructure.transfer;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resume d'un import : nombre d'entites creees par type, + nombre d'images
|
||||||
|
* reuploadees / reutilisees.
|
||||||
|
*/
|
||||||
|
public record ImportResult(Map<String, Integer> created, int imagesUploaded, int imagesReused) {
|
||||||
|
|
||||||
|
public static class Builder {
|
||||||
|
private final Map<String, Integer> created = new LinkedHashMap<>();
|
||||||
|
private int imagesUploaded;
|
||||||
|
private int imagesReused;
|
||||||
|
|
||||||
|
public void count(String type, int n) {
|
||||||
|
created.merge(type, n, Integer::sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void imageUploaded() { imagesUploaded++; }
|
||||||
|
|
||||||
|
public void imageReused() { imagesReused++; }
|
||||||
|
|
||||||
|
public ImportResult build() {
|
||||||
|
return new ImportResult(created, imagesUploaded, imagesReused);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,616 @@
|
|||||||
|
package com.loremind.infrastructure.transfer;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.domain.campaigncontext.Prerequisite;
|
||||||
|
import com.loremind.domain.campaigncontext.SceneBranch;
|
||||||
|
import com.loremind.domain.images.ports.ImageStorage;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.*;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.*;
|
||||||
|
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipInputStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service d'IMPORT de contenu en mode FUSION.
|
||||||
|
* <p>
|
||||||
|
* On NE remplace PAS l'existant : chaque entite importee est reinseree avec un
|
||||||
|
* NOUVEL id auto-genere, et toutes les references (FK Long et refs faibles
|
||||||
|
* String) sont remappees oldId -> newId. Cela permet d'agreger plusieurs exports
|
||||||
|
* dans une meme base sans collision, entre Postgres et H2.
|
||||||
|
* <p>
|
||||||
|
* Algorithme :
|
||||||
|
* <ol>
|
||||||
|
* <li>Parse le zip : {@code data.json} -> {@link ContentExport}, binaires gardes en memoire.</li>
|
||||||
|
* <li>Reecrit les images sous LEUR CLE D'ORIGINE (pas de remapping de cle) ;
|
||||||
|
* skip si une ImageJpaEntity avec cette cle existe deja.</li>
|
||||||
|
* <li>Insere top-down en construisant les maps de remapping par type.</li>
|
||||||
|
* <li>2e passe : remappe les references qui pointent vers des types inserees
|
||||||
|
* plus tard (parentId, defaultNodeId, refs faibles String) puis re-save.</li>
|
||||||
|
* </ol>
|
||||||
|
* Les references vers un id absent des maps (ex. relatedPageId hors export) sont
|
||||||
|
* CONSERVEES telles quelles (choix : ne pas perdre d'info, ne jamais planter).
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class ImportService {
|
||||||
|
|
||||||
|
// (Dé)sérialise les prérequis dans le format "kind" du converter JPA (Prerequisite
|
||||||
|
// est scellé, non sérialisable en polymorphe par l'ObjectMapper standard).
|
||||||
|
private static final PrerequisiteListJsonConverter PREREQ_CONVERTER = new PrerequisiteListJsonConverter();
|
||||||
|
|
||||||
|
private final GameSystemJpaRepository gameSystemRepo;
|
||||||
|
private final LoreJpaRepository loreRepo;
|
||||||
|
private final LoreNodeJpaRepository loreNodeRepo;
|
||||||
|
private final TemplateJpaRepository templateRepo;
|
||||||
|
private final PageJpaRepository pageRepo;
|
||||||
|
private final CampaignJpaRepository campaignRepo;
|
||||||
|
private final ArcJpaRepository arcRepo;
|
||||||
|
private final ChapterJpaRepository chapterRepo;
|
||||||
|
private final SceneJpaRepository sceneRepo;
|
||||||
|
private final CharacterJpaRepository characterRepo;
|
||||||
|
private final NpcJpaRepository npcRepo;
|
||||||
|
private final EnemyJpaRepository enemyRepo;
|
||||||
|
private final ItemCatalogJpaRepository itemCatalogRepo;
|
||||||
|
private final RandomTableJpaRepository randomTableRepo;
|
||||||
|
private final ImageJpaRepository imageRepo;
|
||||||
|
private final ImageStorage imageStorage;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public ImportService(GameSystemJpaRepository gameSystemRepo,
|
||||||
|
LoreJpaRepository loreRepo,
|
||||||
|
LoreNodeJpaRepository loreNodeRepo,
|
||||||
|
TemplateJpaRepository templateRepo,
|
||||||
|
PageJpaRepository pageRepo,
|
||||||
|
CampaignJpaRepository campaignRepo,
|
||||||
|
ArcJpaRepository arcRepo,
|
||||||
|
ChapterJpaRepository chapterRepo,
|
||||||
|
SceneJpaRepository sceneRepo,
|
||||||
|
CharacterJpaRepository characterRepo,
|
||||||
|
NpcJpaRepository npcRepo,
|
||||||
|
EnemyJpaRepository enemyRepo,
|
||||||
|
ItemCatalogJpaRepository itemCatalogRepo,
|
||||||
|
RandomTableJpaRepository randomTableRepo,
|
||||||
|
ImageJpaRepository imageRepo,
|
||||||
|
ImageStorage imageStorage,
|
||||||
|
ObjectMapper objectMapper) {
|
||||||
|
this.gameSystemRepo = gameSystemRepo;
|
||||||
|
this.loreRepo = loreRepo;
|
||||||
|
this.loreNodeRepo = loreNodeRepo;
|
||||||
|
this.templateRepo = templateRepo;
|
||||||
|
this.pageRepo = pageRepo;
|
||||||
|
this.campaignRepo = campaignRepo;
|
||||||
|
this.arcRepo = arcRepo;
|
||||||
|
this.chapterRepo = chapterRepo;
|
||||||
|
this.sceneRepo = sceneRepo;
|
||||||
|
this.characterRepo = characterRepo;
|
||||||
|
this.npcRepo = npcRepo;
|
||||||
|
this.enemyRepo = enemyRepo;
|
||||||
|
this.itemCatalogRepo = itemCatalogRepo;
|
||||||
|
this.randomTableRepo = randomTableRepo;
|
||||||
|
this.imageRepo = imageRepo;
|
||||||
|
this.imageStorage = imageStorage;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public ImportResult importZip(InputStream zipStream) {
|
||||||
|
// 1. Parse du zip.
|
||||||
|
ContentExport export = null;
|
||||||
|
Map<String, byte[]> imageBinaries = new LinkedHashMap<>(); // storageKey -> binaire
|
||||||
|
try (ZipInputStream zip = new ZipInputStream(zipStream)) {
|
||||||
|
ZipEntry entry;
|
||||||
|
while ((entry = zip.getNextEntry()) != null) {
|
||||||
|
String name = entry.getName();
|
||||||
|
if ("data.json".equals(name)) {
|
||||||
|
export = objectMapper.readValue(readAll(zip), ContentExport.class);
|
||||||
|
} else if (name.startsWith("images/") && !entry.isDirectory()) {
|
||||||
|
// La cle de stockage est le chemin sans le prefixe "images/" du zip,
|
||||||
|
// c'est-a-dire EXACTEMENT le storageKey d'origine ("images/UUID.ext").
|
||||||
|
String storageKey = name.substring("images/".length());
|
||||||
|
imageBinaries.put(storageKey, readAll(zip));
|
||||||
|
}
|
||||||
|
// manifest.json : ignore a l'import (info seulement).
|
||||||
|
zip.closeEntry();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Echec de lecture du zip d'import", e);
|
||||||
|
}
|
||||||
|
if (export == null) {
|
||||||
|
throw new IllegalArgumentException("Archive invalide : data.json introuvable");
|
||||||
|
}
|
||||||
|
|
||||||
|
ImportResult.Builder result = new ImportResult.Builder();
|
||||||
|
|
||||||
|
// 2. Reecriture des images (cle preservee).
|
||||||
|
importImages(export, imageBinaries, result);
|
||||||
|
|
||||||
|
// 3. Insertion top-down + maps de remapping.
|
||||||
|
Map<Long, Long> gameSystemMap = new HashMap<>();
|
||||||
|
Map<Long, Long> loreMap = new HashMap<>();
|
||||||
|
Map<Long, Long> loreNodeMap = new HashMap<>();
|
||||||
|
Map<Long, Long> templateMap = new HashMap<>();
|
||||||
|
Map<Long, Long> pageMap = new HashMap<>();
|
||||||
|
Map<Long, Long> campaignMap = new HashMap<>();
|
||||||
|
Map<Long, Long> arcMap = new HashMap<>();
|
||||||
|
Map<Long, Long> chapterMap = new HashMap<>();
|
||||||
|
Map<Long, Long> npcMap = new HashMap<>();
|
||||||
|
Map<Long, Long> enemyMap = new HashMap<>();
|
||||||
|
Map<Long, Long> characterMap = new HashMap<>();
|
||||||
|
Map<Long, Long> sceneMap = new HashMap<>();
|
||||||
|
|
||||||
|
// -- GameSystem
|
||||||
|
for (ContentExport.GameSystemDto d : nullSafe(export.gameSystems())) {
|
||||||
|
GameSystemJpaEntity e = new GameSystemJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setRulesMarkdown(d.rulesMarkdown());
|
||||||
|
e.setCharacterTemplate(d.characterTemplate());
|
||||||
|
e.setNpcTemplate(d.npcTemplate());
|
||||||
|
e.setEnemyTemplate(d.enemyTemplate());
|
||||||
|
e.setAuthor(d.author());
|
||||||
|
e.setPublic(d.isPublic());
|
||||||
|
gameSystemMap.put(d.id(), gameSystemRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("gameSystems", gameSystemMap.size());
|
||||||
|
|
||||||
|
// -- Lore
|
||||||
|
for (ContentExport.LoreDto d : nullSafe(export.lores())) {
|
||||||
|
LoreJpaEntity e = new LoreJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setNodeCount(d.nodeCount());
|
||||||
|
e.setPageCount(d.pageCount());
|
||||||
|
loreMap.put(d.id(), loreRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("lores", loreMap.size());
|
||||||
|
|
||||||
|
// -- LoreNode (parentId remappe en 2e passe)
|
||||||
|
List<LoreNodeJpaEntity> loreNodesToFix = new ArrayList<>();
|
||||||
|
for (ContentExport.LoreNodeDto d : nullSafe(export.loreNodes())) {
|
||||||
|
LoreNodeJpaEntity e = new LoreNodeJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setIcon(d.icon());
|
||||||
|
e.setParentId(d.parentId()); // remappe plus bas
|
||||||
|
e.setLoreId(remapRequired(loreMap, d.loreId()));
|
||||||
|
LoreNodeJpaEntity saved = loreNodeRepo.save(e);
|
||||||
|
loreNodeMap.put(d.id(), saved.getId());
|
||||||
|
if (d.parentId() != null) loreNodesToFix.add(saved);
|
||||||
|
}
|
||||||
|
result.count("loreNodes", loreNodeMap.size());
|
||||||
|
|
||||||
|
// -- Template (defaultNodeId remappe en 2e passe)
|
||||||
|
List<ContentExport.TemplateDto> templatesWithDefaultNode = new ArrayList<>();
|
||||||
|
for (ContentExport.TemplateDto d : nullSafe(export.templates())) {
|
||||||
|
TemplateJpaEntity e = new TemplateJpaEntity();
|
||||||
|
e.setLoreId(remapRequired(loreMap, d.loreId()));
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setDefaultNodeId(d.defaultNodeId()); // remappe plus bas
|
||||||
|
e.setFields(d.fields());
|
||||||
|
templateMap.put(d.id(), templateRepo.save(e).getId());
|
||||||
|
if (d.defaultNodeId() != null) templatesWithDefaultNode.add(d);
|
||||||
|
}
|
||||||
|
result.count("templates", templateMap.size());
|
||||||
|
|
||||||
|
// -- Page (relatedPageIds remappe en 2e passe)
|
||||||
|
for (ContentExport.PageDto d : nullSafe(export.pages())) {
|
||||||
|
PageJpaEntity e = new PageJpaEntity();
|
||||||
|
e.setLoreId(remapRequired(loreMap, d.loreId()));
|
||||||
|
e.setNodeId(remapRequired(loreNodeMap, d.nodeId()));
|
||||||
|
e.setTemplateId(remapNullable(templateMap, d.templateId()));
|
||||||
|
e.setTitle(d.title());
|
||||||
|
e.setValues(d.values());
|
||||||
|
e.setImageValues(d.imageValues());
|
||||||
|
e.setKeyValueValues(d.keyValueValues());
|
||||||
|
e.setTableValues(d.tableValues());
|
||||||
|
e.setNotes(d.notes());
|
||||||
|
e.setTags(d.tags());
|
||||||
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||||
|
pageMap.put(d.id(), pageRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("pages", pageMap.size());
|
||||||
|
|
||||||
|
// -- Campaign (loreId/gameSystemId String remappes en 2e passe)
|
||||||
|
for (ContentExport.CampaignDto d : nullSafe(export.campaigns())) {
|
||||||
|
CampaignJpaEntity e = new CampaignJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setArcsCount(d.arcsCount());
|
||||||
|
e.setLoreId(d.loreId()); // remappe plus bas
|
||||||
|
e.setGameSystemId(d.gameSystemId()); // remappe plus bas
|
||||||
|
campaignMap.put(d.id(), campaignRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("campaigns", campaignMap.size());
|
||||||
|
|
||||||
|
// -- Arc (relatedPageIds remappe en 2e passe)
|
||||||
|
for (ContentExport.ArcDto d : nullSafe(export.arcs())) {
|
||||||
|
ArcJpaEntity e = new ArcJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||||
|
e.setOrder(d.order());
|
||||||
|
e.setType(parseArcType(d.type()));
|
||||||
|
e.setIcon(d.icon());
|
||||||
|
e.setThemes(d.themes());
|
||||||
|
e.setStakes(d.stakes());
|
||||||
|
e.setGmNotes(d.gmNotes());
|
||||||
|
e.setRewards(d.rewards());
|
||||||
|
e.setResolution(d.resolution());
|
||||||
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||||
|
e.setIllustrationImageIds(d.illustrationImageIds());
|
||||||
|
e.setMapImageIds(d.mapImageIds());
|
||||||
|
arcMap.put(d.id(), arcRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("arcs", arcMap.size());
|
||||||
|
|
||||||
|
// -- ItemCatalog (+ items en cascade)
|
||||||
|
int catalogCount = 0, itemCount = 0;
|
||||||
|
for (ContentExport.ItemCatalogDto d : nullSafe(export.itemCatalogs())) {
|
||||||
|
ItemCatalogJpaEntity e = new ItemCatalogJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setIcon(d.icon());
|
||||||
|
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||||
|
e.setOrder(d.order());
|
||||||
|
List<CatalogItemJpaEntity> items = new ArrayList<>();
|
||||||
|
for (ContentExport.CatalogItemDto i : nullSafe(d.items())) {
|
||||||
|
CatalogItemJpaEntity item = new CatalogItemJpaEntity();
|
||||||
|
item.setName(i.name());
|
||||||
|
item.setPrice(i.price());
|
||||||
|
item.setCategory(i.category());
|
||||||
|
item.setDescription(i.description());
|
||||||
|
item.setPosition(i.position());
|
||||||
|
item.setCatalog(e); // lien parent requis pour la cascade
|
||||||
|
items.add(item);
|
||||||
|
itemCount++;
|
||||||
|
}
|
||||||
|
e.setItems(items);
|
||||||
|
itemCatalogRepo.save(e);
|
||||||
|
catalogCount++;
|
||||||
|
}
|
||||||
|
result.count("itemCatalogs", catalogCount);
|
||||||
|
result.count("catalogItems", itemCount);
|
||||||
|
|
||||||
|
// -- RandomTable (+ entries en cascade)
|
||||||
|
int tableCount = 0, entryCount = 0;
|
||||||
|
for (ContentExport.RandomTableDto d : nullSafe(export.randomTables())) {
|
||||||
|
RandomTableJpaEntity e = new RandomTableJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setDiceFormula(d.diceFormula());
|
||||||
|
e.setIcon(d.icon());
|
||||||
|
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||||
|
e.setOrder(d.order());
|
||||||
|
List<RandomTableEntryJpaEntity> entries = new ArrayList<>();
|
||||||
|
for (ContentExport.RandomTableEntryDto en : nullSafe(d.entries())) {
|
||||||
|
RandomTableEntryJpaEntity entryE = new RandomTableEntryJpaEntity();
|
||||||
|
entryE.setMinRoll(en.minRoll());
|
||||||
|
entryE.setMaxRoll(en.maxRoll());
|
||||||
|
entryE.setLabel(en.label());
|
||||||
|
entryE.setDetail(en.detail());
|
||||||
|
entryE.setPosition(en.position());
|
||||||
|
entryE.setRandomTable(e);
|
||||||
|
entries.add(entryE);
|
||||||
|
entryCount++;
|
||||||
|
}
|
||||||
|
e.setEntries(entries);
|
||||||
|
randomTableRepo.save(e);
|
||||||
|
tableCount++;
|
||||||
|
}
|
||||||
|
result.count("randomTables", tableCount);
|
||||||
|
result.count("randomTableEntries", entryCount);
|
||||||
|
|
||||||
|
// -- Chapter (prerequisites + relatedPageIds remappes en 2e passe)
|
||||||
|
for (ContentExport.ChapterDto d : nullSafe(export.chapters())) {
|
||||||
|
ChapterJpaEntity e = new ChapterJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setArcId(remapRequired(arcMap, d.arcId()));
|
||||||
|
e.setOrder(d.order());
|
||||||
|
e.setPrerequisites(PREREQ_CONVERTER.convertToEntityAttribute(d.prerequisitesJson())); // remappe plus bas
|
||||||
|
e.setIcon(d.icon());
|
||||||
|
e.setGmNotes(d.gmNotes());
|
||||||
|
e.setPlayerObjectives(d.playerObjectives());
|
||||||
|
e.setNarrativeStakes(d.narrativeStakes());
|
||||||
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||||
|
e.setIllustrationImageIds(d.illustrationImageIds());
|
||||||
|
e.setMapImageIds(d.mapImageIds());
|
||||||
|
chapterMap.put(d.id(), chapterRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("chapters", chapterMap.size());
|
||||||
|
|
||||||
|
// -- Npc (relatedPageIds remappe en 2e passe)
|
||||||
|
for (ContentExport.NpcDto d : nullSafe(export.npcs())) {
|
||||||
|
NpcJpaEntity e = new NpcJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setPortraitImageId(d.portraitImageId());
|
||||||
|
e.setHeaderImageId(d.headerImageId());
|
||||||
|
e.setValues(d.values());
|
||||||
|
e.setImageValues(d.imageValues());
|
||||||
|
e.setKeyValueValues(d.keyValueValues());
|
||||||
|
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||||
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||||
|
e.setFolder(d.folder());
|
||||||
|
e.setOrder(d.order());
|
||||||
|
npcMap.put(d.id(), npcRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("npcs", npcMap.size());
|
||||||
|
|
||||||
|
// -- Enemy
|
||||||
|
for (ContentExport.EnemyDto d : nullSafe(export.enemies())) {
|
||||||
|
EnemyJpaEntity e = new EnemyJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setLevel(d.level());
|
||||||
|
e.setFolder(d.folder());
|
||||||
|
e.setPortraitImageId(d.portraitImageId());
|
||||||
|
e.setHeaderImageId(d.headerImageId());
|
||||||
|
e.setValues(d.values());
|
||||||
|
e.setImageValues(d.imageValues());
|
||||||
|
e.setKeyValueValues(d.keyValueValues());
|
||||||
|
e.setCampaignId(remapRequired(campaignMap, d.campaignId()));
|
||||||
|
e.setOrder(d.order());
|
||||||
|
enemyMap.put(d.id(), enemyRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("enemies", enemyMap.size());
|
||||||
|
|
||||||
|
// -- Character (playthroughId mis a null : hors perimetre)
|
||||||
|
for (ContentExport.CharacterDto d : nullSafe(export.characters())) {
|
||||||
|
CharacterJpaEntity e = new CharacterJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setPortraitImageId(d.portraitImageId());
|
||||||
|
e.setHeaderImageId(d.headerImageId());
|
||||||
|
e.setValues(d.values());
|
||||||
|
e.setImageValues(d.imageValues());
|
||||||
|
e.setKeyValueValues(d.keyValueValues());
|
||||||
|
e.setCampaignId(remapNullable(campaignMap, d.campaignId()));
|
||||||
|
e.setPlaythroughId(null); // Playthrough hors perimetre d'export
|
||||||
|
e.setOrder(d.order());
|
||||||
|
characterMap.put(d.id(), characterRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("characters", characterMap.size());
|
||||||
|
|
||||||
|
// -- Scene (enemyIds + relatedPageIds + branches remappes en 2e passe)
|
||||||
|
for (ContentExport.SceneDto d : nullSafe(export.scenes())) {
|
||||||
|
SceneJpaEntity e = new SceneJpaEntity();
|
||||||
|
e.setName(d.name());
|
||||||
|
e.setDescription(d.description());
|
||||||
|
e.setChapterId(remapRequired(chapterMap, d.chapterId()));
|
||||||
|
e.setOrder(d.order());
|
||||||
|
e.setIcon(d.icon());
|
||||||
|
e.setLocation(d.location());
|
||||||
|
e.setTiming(d.timing());
|
||||||
|
e.setAtmosphere(d.atmosphere());
|
||||||
|
e.setPlayerNarration(d.playerNarration());
|
||||||
|
e.setGmSecretNotes(d.gmSecretNotes());
|
||||||
|
e.setChoicesConsequences(d.choicesConsequences());
|
||||||
|
e.setCombatDifficulty(d.combatDifficulty());
|
||||||
|
e.setEnemies(d.enemies());
|
||||||
|
e.setEnemyIds(d.enemyIds()); // remappe plus bas
|
||||||
|
e.setRelatedPageIds(d.relatedPageIds()); // remappe plus bas
|
||||||
|
e.setIllustrationImageIds(d.illustrationImageIds());
|
||||||
|
e.setMapImageIds(d.mapImageIds());
|
||||||
|
e.setBranches(d.branches()); // remappe plus bas
|
||||||
|
e.setRooms(d.rooms()); // Rooms: UUID, non remappes
|
||||||
|
sceneMap.put(d.id(), sceneRepo.save(e).getId());
|
||||||
|
}
|
||||||
|
result.count("scenes", sceneMap.size());
|
||||||
|
|
||||||
|
// 4. 2e PASSE de remapping.
|
||||||
|
|
||||||
|
// LoreNode.parentId
|
||||||
|
for (LoreNodeJpaEntity e : loreNodesToFix) {
|
||||||
|
Long newParent = loreNodeMap.get(e.getParentId());
|
||||||
|
if (newParent != null) {
|
||||||
|
e.setParentId(newParent);
|
||||||
|
loreNodeRepo.save(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Template.defaultNodeId
|
||||||
|
for (ContentExport.TemplateDto d : templatesWithDefaultNode) {
|
||||||
|
Long newTemplateId = templateMap.get(d.id());
|
||||||
|
Long newNode = loreNodeMap.get(d.defaultNodeId());
|
||||||
|
if (newTemplateId != null && newNode != null) {
|
||||||
|
templateRepo.findById(newTemplateId).ifPresent(t -> {
|
||||||
|
t.setDefaultNodeId(newNode);
|
||||||
|
templateRepo.save(t);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Campaign.loreId & gameSystemId (refs faibles String -> remap via maps Long).
|
||||||
|
for (Long newCampaignId : campaignMap.values()) {
|
||||||
|
campaignRepo.findById(newCampaignId).ifPresent(c -> {
|
||||||
|
String newLore = remapStringId(loreMap, c.getLoreId());
|
||||||
|
String newGs = remapStringId(gameSystemMap, c.getGameSystemId());
|
||||||
|
c.setLoreId(newLore);
|
||||||
|
c.setGameSystemId(newGs);
|
||||||
|
campaignRepo.save(c);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page.relatedPageIds
|
||||||
|
for (Long newPageId : pageMap.values()) {
|
||||||
|
pageRepo.findById(newPageId).ifPresent(p -> {
|
||||||
|
p.setRelatedPageIds(remapStringList(pageMap, p.getRelatedPageIds()));
|
||||||
|
pageRepo.save(p);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Arc.relatedPageIds
|
||||||
|
for (Long newArcId : arcMap.values()) {
|
||||||
|
arcRepo.findById(newArcId).ifPresent(a -> {
|
||||||
|
a.setRelatedPageIds(remapStringList(pageMap, a.getRelatedPageIds()));
|
||||||
|
arcRepo.save(a);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chapter.relatedPageIds + prerequisites(QuestCompleted -> map Chapter)
|
||||||
|
for (Long newChapterId : chapterMap.values()) {
|
||||||
|
chapterRepo.findById(newChapterId).ifPresent(c -> {
|
||||||
|
c.setRelatedPageIds(remapStringList(pageMap, c.getRelatedPageIds()));
|
||||||
|
c.setPrerequisites(remapPrerequisites(chapterMap, c.getPrerequisites()));
|
||||||
|
chapterRepo.save(c);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Npc.relatedPageIds
|
||||||
|
for (Long newNpcId : npcMap.values()) {
|
||||||
|
npcRepo.findById(newNpcId).ifPresent(n -> {
|
||||||
|
n.setRelatedPageIds(remapStringList(pageMap, n.getRelatedPageIds()));
|
||||||
|
npcRepo.save(n);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scene.relatedPageIds + enemyIds(map Enemy) + branches.targetSceneId(map Scene)
|
||||||
|
for (Long newSceneId : sceneMap.values()) {
|
||||||
|
sceneRepo.findById(newSceneId).ifPresent(s -> {
|
||||||
|
s.setRelatedPageIds(remapStringList(pageMap, s.getRelatedPageIds()));
|
||||||
|
s.setEnemyIds(remapStringList(enemyMap, s.getEnemyIds()));
|
||||||
|
s.setBranches(remapBranches(sceneMap, s.getBranches()));
|
||||||
|
sceneRepo.save(s);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Images -----
|
||||||
|
|
||||||
|
private void importImages(ContentExport export,
|
||||||
|
Map<String, byte[]> imageBinaries,
|
||||||
|
ImportResult.Builder result) {
|
||||||
|
// Index des metadonnees d'image par cle (depuis le data.json).
|
||||||
|
Map<String, ContentExport.ImageDto> metaByKey = new HashMap<>();
|
||||||
|
for (ContentExport.ImageDto img : nullSafe(export.images())) {
|
||||||
|
if (img.storageKey() != null) metaByKey.put(img.storageKey(), img);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Map.Entry<String, byte[]> bin : imageBinaries.entrySet()) {
|
||||||
|
String storageKey = bin.getKey();
|
||||||
|
byte[] data = bin.getValue();
|
||||||
|
if (imageRepo.findByStorageKey(storageKey).isPresent()) {
|
||||||
|
// Image deja presente : on reutilise, pas de reupload (eviter doublon).
|
||||||
|
result.imageReused();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ContentExport.ImageDto meta = metaByKey.get(storageKey);
|
||||||
|
String contentType = meta != null && meta.contentType() != null
|
||||||
|
? meta.contentType() : guessContentType(storageKey);
|
||||||
|
long size = meta != null ? meta.sizeBytes() : data.length;
|
||||||
|
|
||||||
|
imageStorage.store(storageKey, contentType, new ByteArrayInputStream(data), data.length);
|
||||||
|
|
||||||
|
ImageJpaEntity e = new ImageJpaEntity();
|
||||||
|
e.setFilename(meta != null && meta.filename() != null
|
||||||
|
? meta.filename() : fileNameOf(storageKey));
|
||||||
|
e.setContentType(contentType);
|
||||||
|
e.setSizeBytes(size);
|
||||||
|
e.setStorageKey(storageKey);
|
||||||
|
imageRepo.save(e);
|
||||||
|
result.imageUploaded();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Helpers de remapping -----
|
||||||
|
|
||||||
|
/** Remap obligatoire d'une FK Long : si absente de la map, on garde l'ancienne valeur. */
|
||||||
|
private Long remapRequired(Map<Long, Long> map, Long oldId) {
|
||||||
|
if (oldId == null) return null;
|
||||||
|
return map.getOrDefault(oldId, oldId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remap d'une FK Long nullable : null reste null. */
|
||||||
|
private Long remapNullable(Map<Long, Long> map, Long oldId) {
|
||||||
|
if (oldId == null) return null;
|
||||||
|
return map.getOrDefault(oldId, oldId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remap d'un id stocke en String ("oldLong" -> "newLong") via une map Long. */
|
||||||
|
private String remapStringId(Map<Long, Long> map, String oldId) {
|
||||||
|
if (oldId == null || oldId.isBlank()) return oldId;
|
||||||
|
try {
|
||||||
|
Long newId = map.get(Long.parseLong(oldId.trim()));
|
||||||
|
return newId != null ? String.valueOf(newId) : oldId;
|
||||||
|
} catch (NumberFormatException ex) {
|
||||||
|
return oldId; // pas un Long : on laisse tel quel
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> remapStringList(Map<Long, Long> map, List<String> ids) {
|
||||||
|
if (ids == null) return null;
|
||||||
|
List<String> out = new ArrayList<>(ids.size());
|
||||||
|
for (String id : ids) out.add(remapStringId(map, id));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Prerequisite> remapPrerequisites(Map<Long, Long> chapterMap, List<Prerequisite> prereqs) {
|
||||||
|
if (prereqs == null) return null;
|
||||||
|
List<Prerequisite> out = new ArrayList<>(prereqs.size());
|
||||||
|
for (Prerequisite p : prereqs) {
|
||||||
|
if (p instanceof Prerequisite.QuestCompleted qc) {
|
||||||
|
out.add(new Prerequisite.QuestCompleted(remapStringId(chapterMap, qc.questId())));
|
||||||
|
} else {
|
||||||
|
out.add(p); // FlagSet / SessionReached : inchanges
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<SceneBranch> remapBranches(Map<Long, Long> sceneMap, List<SceneBranch> branches) {
|
||||||
|
if (branches == null) return null;
|
||||||
|
List<SceneBranch> out = new ArrayList<>(branches.size());
|
||||||
|
for (SceneBranch b : branches) {
|
||||||
|
out.add(new SceneBranch(b.label(), remapStringId(sceneMap, b.targetSceneId()), b.condition()));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private com.loremind.domain.campaigncontext.ArcType parseArcType(String type) {
|
||||||
|
if (type == null) return com.loremind.domain.campaigncontext.ArcType.LINEAR;
|
||||||
|
try {
|
||||||
|
return com.loremind.domain.campaigncontext.ArcType.valueOf(type);
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
return com.loremind.domain.campaigncontext.ArcType.LINEAR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- Helpers divers -----
|
||||||
|
|
||||||
|
private static <T> List<T> nullSafe(List<T> list) {
|
||||||
|
return list != null ? list : List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] readAll(InputStream in) throws IOException {
|
||||||
|
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||||
|
in.transferTo(buffer);
|
||||||
|
return buffer.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String fileNameOf(String storageKey) {
|
||||||
|
int slash = storageKey.lastIndexOf('/');
|
||||||
|
return slash >= 0 ? storageKey.substring(slash + 1) : storageKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String guessContentType(String storageKey) {
|
||||||
|
String lower = storageKey.toLowerCase();
|
||||||
|
if (lower.endsWith(".png")) return "image/png";
|
||||||
|
if (lower.endsWith(".gif")) return "image/gif";
|
||||||
|
if (lower.endsWith(".webp")) return "image/webp";
|
||||||
|
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
|
||||||
|
return "application/octet-stream";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.dto;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Room;
|
||||||
|
import com.loremind.domain.campaigncontext.SceneBranch;
|
||||||
|
import com.loremind.domain.shared.template.TemplateField;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format d'export LOGIQUE (JSON) du "contenu" de LoreMind.
|
||||||
|
* <p>
|
||||||
|
* Records plats, miroirs des champs des entites JPA — volontairement DECOUPLES
|
||||||
|
* des entites pour la stabilite inter-versions (le schema JPA peut bouger sans
|
||||||
|
* casser un .zip exporte). Chaque record porte son {@code id} d'origine (Long)
|
||||||
|
* afin que l'import puisse construire les maps de remapping oldId -> newId.
|
||||||
|
* <p>
|
||||||
|
* Les sous-objets riches (TemplateField, Prerequisite, SceneBranch, Room)
|
||||||
|
* reutilisent les types domaine existants : Jackson sait les (de)serialiser
|
||||||
|
* (records ou Lombok), et on evite de dupliquer la structure.
|
||||||
|
*/
|
||||||
|
public record ContentExport(
|
||||||
|
Manifest manifest,
|
||||||
|
List<GameSystemDto> gameSystems,
|
||||||
|
List<LoreDto> lores,
|
||||||
|
List<LoreNodeDto> loreNodes,
|
||||||
|
List<TemplateDto> templates,
|
||||||
|
List<PageDto> pages,
|
||||||
|
List<CampaignDto> campaigns,
|
||||||
|
List<ArcDto> arcs,
|
||||||
|
List<ChapterDto> chapters,
|
||||||
|
List<SceneDto> scenes,
|
||||||
|
List<CharacterDto> characters,
|
||||||
|
List<NpcDto> npcs,
|
||||||
|
List<EnemyDto> enemies,
|
||||||
|
List<ItemCatalogDto> itemCatalogs,
|
||||||
|
List<RandomTableDto> randomTables,
|
||||||
|
List<ImageDto> images
|
||||||
|
) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Metadonnees de l'export. {@code exportedAt} est passe en parametre depuis
|
||||||
|
* la couche requete (PAS Instant.now() ici, pour rester deterministe et
|
||||||
|
* testable).
|
||||||
|
*/
|
||||||
|
public record Manifest(
|
||||||
|
int formatVersion,
|
||||||
|
String appVersion,
|
||||||
|
String exportedAt
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record GameSystemDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
String rulesMarkdown,
|
||||||
|
List<TemplateField> characterTemplate,
|
||||||
|
List<TemplateField> npcTemplate,
|
||||||
|
List<TemplateField> enemyTemplate,
|
||||||
|
String author,
|
||||||
|
boolean isPublic
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record LoreDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
int nodeCount,
|
||||||
|
int pageCount
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record LoreNodeDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String icon,
|
||||||
|
Long parentId,
|
||||||
|
Long loreId
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record TemplateDto(
|
||||||
|
Long id,
|
||||||
|
Long loreId,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
Long defaultNodeId,
|
||||||
|
List<TemplateField> fields
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record PageDto(
|
||||||
|
Long id,
|
||||||
|
Long loreId,
|
||||||
|
Long nodeId,
|
||||||
|
Long templateId,
|
||||||
|
String title,
|
||||||
|
Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues,
|
||||||
|
Map<String, Map<String, String>> keyValueValues,
|
||||||
|
Map<String, List<Map<String, String>>> tableValues,
|
||||||
|
String notes,
|
||||||
|
List<String> tags,
|
||||||
|
List<String> relatedPageIds
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record CampaignDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
int arcsCount,
|
||||||
|
String loreId,
|
||||||
|
String gameSystemId
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record ArcDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
Long campaignId,
|
||||||
|
int order,
|
||||||
|
String type,
|
||||||
|
String icon,
|
||||||
|
String themes,
|
||||||
|
String stakes,
|
||||||
|
String gmNotes,
|
||||||
|
String rewards,
|
||||||
|
String resolution,
|
||||||
|
List<String> relatedPageIds,
|
||||||
|
List<String> illustrationImageIds,
|
||||||
|
List<String> mapImageIds
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record ChapterDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
Long arcId,
|
||||||
|
int order,
|
||||||
|
// Prerequisites en JSON brut (format "kind" du converter JPA) : Prerequisite
|
||||||
|
// est un type scellé SANS annotations Jackson, donc impossible à (dé)sérialiser
|
||||||
|
// en polymorphe via l'ObjectMapper standard. On réutilise
|
||||||
|
// PrerequisiteListJsonConverter (format on-disk stable, identique à la base).
|
||||||
|
String prerequisitesJson,
|
||||||
|
String icon,
|
||||||
|
String gmNotes,
|
||||||
|
String playerObjectives,
|
||||||
|
String narrativeStakes,
|
||||||
|
List<String> relatedPageIds,
|
||||||
|
List<String> illustrationImageIds,
|
||||||
|
List<String> mapImageIds
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record SceneDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
Long chapterId,
|
||||||
|
int order,
|
||||||
|
String icon,
|
||||||
|
String location,
|
||||||
|
String timing,
|
||||||
|
String atmosphere,
|
||||||
|
String playerNarration,
|
||||||
|
String gmSecretNotes,
|
||||||
|
String choicesConsequences,
|
||||||
|
String combatDifficulty,
|
||||||
|
String enemies,
|
||||||
|
List<String> enemyIds,
|
||||||
|
List<String> relatedPageIds,
|
||||||
|
List<String> illustrationImageIds,
|
||||||
|
List<String> mapImageIds,
|
||||||
|
List<SceneBranch> branches,
|
||||||
|
List<Room> rooms
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record CharacterDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String portraitImageId,
|
||||||
|
String headerImageId,
|
||||||
|
Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues,
|
||||||
|
Map<String, Map<String, String>> keyValueValues,
|
||||||
|
Long campaignId,
|
||||||
|
Long playthroughId,
|
||||||
|
int order
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record NpcDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String portraitImageId,
|
||||||
|
String headerImageId,
|
||||||
|
Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues,
|
||||||
|
Map<String, Map<String, String>> keyValueValues,
|
||||||
|
Long campaignId,
|
||||||
|
List<String> relatedPageIds,
|
||||||
|
String folder,
|
||||||
|
int order
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record EnemyDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String level,
|
||||||
|
String folder,
|
||||||
|
String portraitImageId,
|
||||||
|
String headerImageId,
|
||||||
|
Map<String, String> values,
|
||||||
|
Map<String, List<String>> imageValues,
|
||||||
|
Map<String, Map<String, String>> keyValueValues,
|
||||||
|
Long campaignId,
|
||||||
|
int order
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record ItemCatalogDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
String icon,
|
||||||
|
Long campaignId,
|
||||||
|
int order,
|
||||||
|
List<CatalogItemDto> items
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record CatalogItemDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String price,
|
||||||
|
String category,
|
||||||
|
String description,
|
||||||
|
int position
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record RandomTableDto(
|
||||||
|
Long id,
|
||||||
|
String name,
|
||||||
|
String description,
|
||||||
|
String diceFormula,
|
||||||
|
String icon,
|
||||||
|
Long campaignId,
|
||||||
|
int order,
|
||||||
|
List<RandomTableEntryDto> entries
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public record RandomTableEntryDto(
|
||||||
|
Long id,
|
||||||
|
int minRoll,
|
||||||
|
int maxRoll,
|
||||||
|
String label,
|
||||||
|
String detail,
|
||||||
|
int position
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Metadonnees d'une image. Le binaire voyage a part dans le zip sous
|
||||||
|
* {@code images/<storageKey>}. La cle est PRESERVEE telle quelle a l'import.
|
||||||
|
*/
|
||||||
|
public record ImageDto(
|
||||||
|
Long id,
|
||||||
|
String filename,
|
||||||
|
String contentType,
|
||||||
|
long sizeBytes,
|
||||||
|
String storageKey
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.core.io.ClassPathResource;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.http.CacheControl;
|
||||||
|
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
import org.springframework.web.servlet.resource.PathResourceResolver;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service du front Angular en statique par le Core, en mode local-first.
|
||||||
|
* <p>
|
||||||
|
* En deploiement Docker, le front est servi par un conteneur nginx dedie
|
||||||
|
* (service {@code web}) et le Core reste une API pure. En mode local
|
||||||
|
* (application de bureau empaquetee), il n'y a pas de nginx : le build Angular
|
||||||
|
* est copie dans {@code classpath:/static/} (cf. profil Maven de packaging) et
|
||||||
|
* le Core le sert lui-meme sur la meme origine que l'API.
|
||||||
|
* <p>
|
||||||
|
* Active uniquement sous le profil {@code local} pour ne RIEN changer au
|
||||||
|
* comportement du conteneur Core en production.
|
||||||
|
* <p>
|
||||||
|
* Fallback SPA : toute route qui ne correspond pas a un fichier statique reel
|
||||||
|
* (et qui n'est pas une route d'API) renvoie {@code index.html}, afin que le
|
||||||
|
* routing cote Angular (deep links, rechargement de page) fonctionne.
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
@Profile("local")
|
||||||
|
public class LocalWebConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||||
|
// Fichiers de traduction (assets/i18n/*.json) : nom STABLE (non hashe),
|
||||||
|
// donc jamais mis en cache, sinon le navigateur ressert un JSON perime
|
||||||
|
// (voire un 304 sur un corps en cache obsolete) apres une mise a jour.
|
||||||
|
// Symptome observe : les libelles restent en cles brutes pour une langue.
|
||||||
|
// Motif plus specifique que "/**" => prioritaire pour ces chemins.
|
||||||
|
registry.addResourceHandler("/assets/i18n/**")
|
||||||
|
.addResourceLocations("classpath:/static/assets/i18n/")
|
||||||
|
.setCacheControl(CacheControl.noStore());
|
||||||
|
|
||||||
|
registry.addResourceHandler("/**")
|
||||||
|
.addResourceLocations("classpath:/static/")
|
||||||
|
.resourceChain(true)
|
||||||
|
.addResolver(new PathResourceResolver() {
|
||||||
|
@Override
|
||||||
|
protected Resource getResource(String resourcePath, Resource location) throws IOException {
|
||||||
|
Resource requested = location.createRelative(resourcePath);
|
||||||
|
if (requested.exists() && requested.isReadable()) {
|
||||||
|
return requested;
|
||||||
|
}
|
||||||
|
// Ne JAMAIS rabattre les routes techniques sur index.html :
|
||||||
|
// une API inexistante doit rester un 404, pas du HTML.
|
||||||
|
if (resourcePath.startsWith("api/") || resourcePath.startsWith("actuator/")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// Un ASSET manquant (chemin avec extension : .json, .js, .css,
|
||||||
|
// .png...) doit renvoyer 404 — surtout PAS index.html. Sinon un
|
||||||
|
// loader JSON (ex. ngx-translate chargeant assets/i18n/fr.json)
|
||||||
|
// recevrait du HTML en 200 et echouerait au parse, donnant des
|
||||||
|
// cles brutes a l'ecran. On ne rabat sur la coquille SPA que les
|
||||||
|
// vraies routes applicatives (sans extension de fichier).
|
||||||
|
if (hasFileExtension(resourcePath)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// Route applicative Angular -> on sert la coquille SPA.
|
||||||
|
Resource index = new ClassPathResource("/static/index.html");
|
||||||
|
return index.exists() ? index : null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vrai si le dernier segment du chemin contient un point (donc une extension
|
||||||
|
* de fichier : {@code assets/i18n/fr.json}, {@code main.js}...). Les routes
|
||||||
|
* applicatives Angular ({@code settings}, {@code campaigns/42}) n'en ont pas.
|
||||||
|
*/
|
||||||
|
private static boolean hasFileExtension(String resourcePath) {
|
||||||
|
int lastSlash = resourcePath.lastIndexOf('/');
|
||||||
|
String lastSegment = resourcePath.substring(lastSlash + 1);
|
||||||
|
return lastSegment.contains(".");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.transfer.ExportService;
|
||||||
|
import com.loremind.infrastructure.transfer.ImportResult;
|
||||||
|
import com.loremind.infrastructure.transfer.ImportService;
|
||||||
|
import com.loremind.infrastructure.transfer.dto.ContentExport;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Endpoints d'EXPORT / IMPORT du "contenu" (admin).
|
||||||
|
* <p>
|
||||||
|
* - {@code GET /api/admin/data/export} : telecharge un .zip portable.<br>
|
||||||
|
* - {@code POST /api/admin/data/import} : importe un .zip en mode FUSION.
|
||||||
|
* <p>
|
||||||
|
* Garde le mode demo coherent avec {@code SettingsController} : ces operations
|
||||||
|
* sont desactivees en demo (donnees partagees, pas d'ecriture massive).
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin/data")
|
||||||
|
public class DataTransferController {
|
||||||
|
|
||||||
|
private final ExportService exportService;
|
||||||
|
private final ImportService importService;
|
||||||
|
private final boolean demoMode;
|
||||||
|
|
||||||
|
public DataTransferController(ExportService exportService,
|
||||||
|
ImportService importService,
|
||||||
|
@Value("${app.demo-mode:false}") boolean demoMode) {
|
||||||
|
this.exportService = exportService;
|
||||||
|
this.importService = importService;
|
||||||
|
this.demoMode = demoMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = "/export", produces = "application/zip")
|
||||||
|
public ResponseEntity<StreamingResponseBody> export() {
|
||||||
|
guardDemoMode();
|
||||||
|
// Stamp de l'horodatage cote requete (PAS dans un init statique).
|
||||||
|
String exportedAt = Instant.now().toString();
|
||||||
|
ContentExport content = exportService.buildExport(exportedAt);
|
||||||
|
|
||||||
|
StreamingResponseBody body = out -> exportService.writeZip(content, out);
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||||
|
"attachment; filename=\"loremind-export.zip\"")
|
||||||
|
.contentType(MediaType.parseMediaType("application/zip"))
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
|
public ResponseEntity<ImportResult> importData(@RequestParam("file") MultipartFile file) {
|
||||||
|
guardDemoMode();
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Fichier d'import vide");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
ImportResult result = importService.importZip(file.getInputStream());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException("Echec de lecture du fichier d'import", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void guardDemoMode() {
|
||||||
|
if (demoMode) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Data transfer disabled in demo mode");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
103
core/src/main/resources/application-local.properties
Normal file
103
core/src/main/resources/application-local.properties
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
# ============================================================================
|
||||||
|
# Profil "local" — mode local-first (application de bureau, sans Docker)
|
||||||
|
# ============================================================================
|
||||||
|
# Active via : --spring.profiles.active=local (ou SPRING_PROFILES_ACTIVE=local)
|
||||||
|
#
|
||||||
|
# Objectif : faire tourner le Core sur le poste de l'utilisateur SANS aucune
|
||||||
|
# infrastructure externe (ni Postgres, ni MinIO, ni Docker). Toutes les donnees
|
||||||
|
# vivent sous loremind.home (defaut : ~/.loremind).
|
||||||
|
#
|
||||||
|
# Surcharge UNIQUEMENT ce qui differe du profil par defaut (application.properties) :
|
||||||
|
# le reste (timeouts, multipart, licensing...) est herite tel quel.
|
||||||
|
|
||||||
|
# --- Config utilisateur editable (port + identifiants admin) ----------------
|
||||||
|
# Charge ~/.loremind/loremind.properties s'il existe (cree au 1er lancement par
|
||||||
|
# DesktopUserConfig). "optional:" = pas d'erreur s'il manque. Les valeurs y
|
||||||
|
# definies (server.port, admin.username, admin.password) SURCHARGENT les defauts
|
||||||
|
# ci-dessous (un import a une priorite superieure au fichier qui l'importe).
|
||||||
|
# NB : le port effectif est de toute facon fixe par DesktopUserConfig au demarrage
|
||||||
|
# (propriete systeme server.port, avec repli si le port est occupe).
|
||||||
|
spring.config.import=optional:file:${user.home}/.loremind/loremind.properties
|
||||||
|
|
||||||
|
# --- Serveur : ecoute UNIQUEMENT sur la boucle locale -----------------------
|
||||||
|
# App de bureau mono-utilisateur : jamais exposee au reseau (securite). Et ca
|
||||||
|
# rend coherent le test "port libre" de DesktopUserConfig (qui teste 127.0.0.1)
|
||||||
|
# avec l'adresse de bind reelle de Tomcat -> le repli sur port libre fonctionne
|
||||||
|
# meme si une autre appli occupe le port sur une autre interface.
|
||||||
|
server.address=127.0.0.1
|
||||||
|
|
||||||
|
# --- Base de donnees : H2 en mode fichier, compatibilite PostgreSQL ---------
|
||||||
|
# MODE=PostgreSQL : H2 interprete le SQL PostgreSQL -> les MEMES migrations
|
||||||
|
# Flyway (ecrites en SQL Postgres) tournent ici comme sur la prod Postgres.
|
||||||
|
# Aligne aussi la casse des identifiants (minuscules, comme PG).
|
||||||
|
# DB_CLOSE_ON_EXIT=FALSE : Spring/Hikari pilote la fermeture (pas le shutdown
|
||||||
|
# hook H2). AUTO_SERVER volontairement absent (interdit avec DB_CLOSE_ON_EXIT,
|
||||||
|
# et inutile pour un process unique).
|
||||||
|
# NON_KEYWORDS=VALUE : PostgreSQL accepte `value` comme nom de colonne non-quote
|
||||||
|
# (colonne de playthrough_flag), mais H2 le reserve par defaut -> on le relache
|
||||||
|
# pour que le baseline SQL Postgres (non-quote) passe aussi sur H2. Ajouter
|
||||||
|
# d'autres mots ici si une migration future utilise un identifiant reserve H2.
|
||||||
|
spring.datasource.url=jdbc:h2:file:${loremind.home}/db/loremind;MODE=PostgreSQL;DB_CLOSE_ON_EXIT=FALSE;NON_KEYWORDS=VALUE
|
||||||
|
spring.datasource.username=sa
|
||||||
|
spring.datasource.password=
|
||||||
|
spring.datasource.driver-class-name=org.h2.Driver
|
||||||
|
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||||
|
# Schema gere par Flyway (cf. application.properties) ; Hibernate valide seulement.
|
||||||
|
spring.jpa.hibernate.ddl-auto=validate
|
||||||
|
spring.jpa.show-sql=false
|
||||||
|
|
||||||
|
# --- Stockage des images : systeme de fichiers -----------------------------
|
||||||
|
storage.backend=filesystem
|
||||||
|
storage.filesystem.path=${loremind.home}/images
|
||||||
|
|
||||||
|
# --- Brain : service IA Python lance en sidecar sur le poste ---------------
|
||||||
|
brain.base-url=http://localhost:8000
|
||||||
|
# Secret partage Core <-> Brain. En local il n'a pas de role securitaire fort
|
||||||
|
# (tout est sur localhost, mono-utilisateur) mais le Brain est fail-closed :
|
||||||
|
# il DOIT etre defini des deux cotes. Le lanceur de sidecar (BrainSidecar)
|
||||||
|
# propage cette meme valeur au process Brain via la variable BRAIN_INTERNAL_SECRET.
|
||||||
|
brain.internal-secret=${BRAIN_INTERNAL_SECRET:loremind-local-secret}
|
||||||
|
|
||||||
|
# --- Brain en sidecar (lance par le Core) ----------------------------------
|
||||||
|
# Le Core demarre lui-meme le process Brain (pas de Docker en local).
|
||||||
|
brain.sidecar.enabled=${BRAIN_SIDECAR_ENABLED:true}
|
||||||
|
# Le Brain ecrit son dossier data/ (index vectoriel, settings) sous ce dossier.
|
||||||
|
brain.sidecar.working-dir=${loremind.home}/brain
|
||||||
|
# Commande de lancement. VIDE par defaut : le dev qui lance le Brain a la main
|
||||||
|
# n'est pas perturbe. Le packaging (jpackage) la renseigne vers l'exe PyInstaller.
|
||||||
|
# - Empaquete : chemin de l'exe, ex. C:/Program Files/LoreMind/brain/loremind-brain.exe
|
||||||
|
# - Dev : python,-m,uvicorn,app.main:app,--host,127.0.0.1,--port,8000
|
||||||
|
# (avec brain.sidecar.working-dir pointant sur le dossier brain/)
|
||||||
|
brain.sidecar.command=${BRAIN_SIDECAR_COMMAND:}
|
||||||
|
|
||||||
|
# --- Admin (localhost uniquement) ------------------------------------------
|
||||||
|
# Application mono-utilisateur sur le poste : l'utilisateur EST l'admin.
|
||||||
|
# Defauts admin/admin, SURCHARGEABLES par l'utilisateur dans
|
||||||
|
# ~/.loremind/loremind.properties (cf. spring.config.import ci-dessus).
|
||||||
|
admin.username=${ADMIN_USERNAME:admin}
|
||||||
|
admin.password=${ADMIN_PASSWORD:admin}
|
||||||
|
|
||||||
|
# --- Front servi par le Core (meme origine) --------------------------------
|
||||||
|
# Le front Angular est servi en statique par le Core (cf. LocalWebConfig),
|
||||||
|
# donc tout est sur http://localhost:8080 : CORS sans objet, mais on autorise
|
||||||
|
# l'origine locale par securite si un dev lance Angular separement.
|
||||||
|
spring.web.cors.allowed-origins=http://localhost:8080,http://localhost:4200
|
||||||
|
|
||||||
|
# Mode demo desactive (instance personnelle complete).
|
||||||
|
app.demo-mode=false
|
||||||
|
|
||||||
|
# --- Licensing / Patreon : desactive en mode bureau ------------------------
|
||||||
|
# Le gating par IMAGE Docker (canal beta tire d'un registry prive) n'a aucun
|
||||||
|
# sens hors Docker. On coupe toute la machinerie : daemon de refresh no-op,
|
||||||
|
# /api/license/* renvoie enabled=false, et l'UI masque la section Patreon.
|
||||||
|
# La distribution beta desktop se fait par installeur beta via Patreon, pas
|
||||||
|
# par une connexion in-app.
|
||||||
|
licensing.enabled=false
|
||||||
|
|
||||||
|
# --- Verification des mises a jour (bureau) --------------------------------
|
||||||
|
# Interroge l'API GitHub Releases (derniere release STABLE) au demarrage ; si
|
||||||
|
# une version plus recente existe, l'icone systray le signale (bulle + item
|
||||||
|
# « Telecharger »). Pas de mise a jour auto : l'utilisateur telecharge et lance
|
||||||
|
# le nouvel installeur. Mettre a false pour desactiver toute requete sortante.
|
||||||
|
desktop.update.enabled=${DESKTOP_UPDATE_CHECK:true}
|
||||||
|
desktop.update.releases-api-url=https://api.github.com/repos/IGMLcreation/LoreMind/releases/latest
|
||||||
@@ -22,10 +22,26 @@ spring.datasource.driver-class-name=org.postgresql.Driver
|
|||||||
|
|
||||||
# Configuration JPA / Hibernate
|
# Configuration JPA / Hibernate
|
||||||
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
||||||
spring.jpa.hibernate.ddl-auto=update
|
# Le schema est desormais gere par Flyway (migrations versionnees), plus par
|
||||||
|
# Hibernate. ddl-auto=validate : Hibernate ne MODIFIE plus le schema, il verifie
|
||||||
|
# juste au demarrage que les entites correspondent au schema cree par Flyway
|
||||||
|
# (filet de securite contre les derives entites<->migrations).
|
||||||
|
spring.jpa.hibernate.ddl-auto=validate
|
||||||
spring.jpa.show-sql=true
|
spring.jpa.show-sql=true
|
||||||
spring.jpa.properties.hibernate.format_sql=true
|
spring.jpa.properties.hibernate.format_sql=true
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Flyway : migrations de schema versionnees (src/main/resources/db/migration).
|
||||||
|
# ============================================================================
|
||||||
|
# baseline-on-migrate : sur une base EXISTANTE (prod deja peuplee, sans table
|
||||||
|
# d'historique Flyway), Flyway l'estampille a la version baseline SANS rejouer
|
||||||
|
# V1 -> les donnees existantes sont preservees. Sur une base VIDE (install
|
||||||
|
# neuve), Flyway joue V1__baseline.sql normalement pour creer le schema.
|
||||||
|
spring.flyway.enabled=true
|
||||||
|
spring.flyway.baseline-on-migrate=true
|
||||||
|
spring.flyway.baseline-version=1
|
||||||
|
spring.flyway.baseline-description=Baseline (schema pre-Flyway, gere jusque-la par ddl-auto)
|
||||||
|
|
||||||
# Configuration CORS pour autoriser le Frontend Angular
|
# Configuration CORS pour autoriser le Frontend Angular
|
||||||
spring.web.cors.allowed-origins=${CORS_ALLOWED_ORIGINS:http://localhost:4200}
|
spring.web.cors.allowed-origins=${CORS_ALLOWED_ORIGINS:http://localhost:4200}
|
||||||
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
|
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
|
||||||
@@ -48,6 +64,17 @@ brain.internal-secret=${BRAIN_INTERNAL_SECRET:}
|
|||||||
admin.username=${ADMIN_USERNAME:admin}
|
admin.username=${ADMIN_USERNAME:admin}
|
||||||
admin.password=${ADMIN_PASSWORD:}
|
admin.password=${ADMIN_PASSWORD:}
|
||||||
|
|
||||||
|
# Repertoire de base de l'instance (donnees locales hors Docker).
|
||||||
|
# Utilise par le profil "local" (H2 fichier, stockage images filesystem...).
|
||||||
|
loremind.home=${LOREMIND_HOME:${user.home}/.loremind}
|
||||||
|
|
||||||
|
# Backend de stockage des binaires d'images (port ImageStorage) :
|
||||||
|
# - minio : MinIO/S3 (defaut — deploiement Docker/serveur)
|
||||||
|
# - filesystem : systeme de fichiers local (mode local-first / jpackage)
|
||||||
|
storage.backend=${STORAGE_BACKEND:minio}
|
||||||
|
# Racine du stockage filesystem (ignoree si storage.backend=minio).
|
||||||
|
storage.filesystem.path=${STORAGE_FS_PATH:${loremind.home}/images}
|
||||||
|
|
||||||
# Configuration MinIO (Shared Kernel images - Object Storage)
|
# Configuration MinIO (Shared Kernel images - Object Storage)
|
||||||
# Le bucket est cree automatiquement par le service minio-init (docker-compose up -d).
|
# Le bucket est cree automatiquement par le service minio-init (docker-compose up -d).
|
||||||
# Defaults OK pour dev local ; overrides en prod via env.
|
# Defaults OK pour dev local ; overrides en prod via env.
|
||||||
|
|||||||
424
core/src/main/resources/db/migration/V1__baseline.sql
Normal file
424
core/src/main/resources/db/migration/V1__baseline.sql
Normal file
@@ -0,0 +1,424 @@
|
|||||||
|
|
||||||
|
create table arcs (
|
||||||
|
"order" integer not null,
|
||||||
|
campaign_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
type varchar(16) default 'LINEAR' not null check (type in ('LINEAR','HUB')),
|
||||||
|
description TEXT,
|
||||||
|
gm_notes TEXT,
|
||||||
|
icon varchar(255),
|
||||||
|
illustration_image_ids TEXT,
|
||||||
|
map_image_ids TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
related_page_ids TEXT,
|
||||||
|
resolution TEXT,
|
||||||
|
rewards TEXT,
|
||||||
|
stakes TEXT,
|
||||||
|
themes TEXT,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table campaigns (
|
||||||
|
arcs_count integer not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
description TEXT,
|
||||||
|
game_system_id varchar(255),
|
||||||
|
lore_id varchar(255),
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table catalog_items (
|
||||||
|
position integer not null,
|
||||||
|
catalog_id bigint not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
price varchar(64),
|
||||||
|
category varchar(128),
|
||||||
|
description TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table chapters (
|
||||||
|
"order" integer not null,
|
||||||
|
arc_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
description TEXT,
|
||||||
|
gm_notes TEXT,
|
||||||
|
icon varchar(255),
|
||||||
|
illustration_image_ids TEXT,
|
||||||
|
map_image_ids TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
narrative_stakes TEXT,
|
||||||
|
player_objectives TEXT,
|
||||||
|
prerequisites TEXT,
|
||||||
|
related_page_ids TEXT,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table characters (
|
||||||
|
"order" integer not null,
|
||||||
|
campaign_id bigint,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
playthrough_id bigint,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
field_values TEXT,
|
||||||
|
header_image_id varchar(255),
|
||||||
|
image_values TEXT,
|
||||||
|
key_value_values TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
portrait_image_id varchar(255),
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table conversation_messages (
|
||||||
|
conversation_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
role varchar(16) not null,
|
||||||
|
content TEXT not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table conversations (
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
campaign_id varchar(255),
|
||||||
|
entity_id varchar(255),
|
||||||
|
entity_type varchar(255),
|
||||||
|
lore_id varchar(255),
|
||||||
|
title varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table enemies (
|
||||||
|
"order" integer not null,
|
||||||
|
campaign_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
field_values TEXT,
|
||||||
|
folder varchar(255),
|
||||||
|
header_image_id varchar(255),
|
||||||
|
image_values TEXT,
|
||||||
|
key_value_values TEXT,
|
||||||
|
level varchar(255),
|
||||||
|
name varchar(255) not null,
|
||||||
|
portrait_image_id varchar(255),
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table game_systems (
|
||||||
|
is_public boolean not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
author varchar(255),
|
||||||
|
character_template TEXT,
|
||||||
|
description TEXT,
|
||||||
|
enemy_template TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
npc_template TEXT,
|
||||||
|
rules_markdown TEXT,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table images (
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
size_bytes bigint not null,
|
||||||
|
uploaded_at timestamp(6) not null,
|
||||||
|
content_type varchar(255) not null,
|
||||||
|
filename varchar(255) not null,
|
||||||
|
storage_key varchar(255) not null unique,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table item_catalogs (
|
||||||
|
"order" integer not null,
|
||||||
|
campaign_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
icon varchar(64),
|
||||||
|
description TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table licenses (
|
||||||
|
beta_channel_enabled boolean not null,
|
||||||
|
last_refresh_succeeded boolean not null,
|
||||||
|
created_at timestamp(6) with time zone not null,
|
||||||
|
expires_at timestamp(6) with time zone not null,
|
||||||
|
issued_at timestamp(6) with time zone not null,
|
||||||
|
last_refresh_attempt_at timestamp(6) with time zone,
|
||||||
|
updated_at timestamp(6) with time zone not null,
|
||||||
|
id varchar(255) not null,
|
||||||
|
instance_id varchar(255) not null,
|
||||||
|
patreon_user_id varchar(255) not null,
|
||||||
|
raw_jwt TEXT not null,
|
||||||
|
tier_id varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table lore_nodes (
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
lore_id bigint not null,
|
||||||
|
parent_id bigint,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
icon varchar(64),
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table lores (
|
||||||
|
node_count integer not null,
|
||||||
|
page_count integer not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
description TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table notebook_messages (
|
||||||
|
archived_at timestamp(6),
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
notebook_id bigint not null,
|
||||||
|
role varchar(16) not null,
|
||||||
|
content TEXT not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table notebook_sources (
|
||||||
|
chunk_count integer not null,
|
||||||
|
page_count integer not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
notebook_id bigint not null,
|
||||||
|
status varchar(16) not null,
|
||||||
|
filename varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table notebooks (
|
||||||
|
campaign_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table npcs (
|
||||||
|
"order" integer not null,
|
||||||
|
campaign_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
field_values TEXT,
|
||||||
|
folder varchar(255),
|
||||||
|
header_image_id varchar(255),
|
||||||
|
image_values TEXT,
|
||||||
|
key_value_values TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
portrait_image_id varchar(255),
|
||||||
|
related_page_ids TEXT,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table pages (
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
lore_id bigint not null,
|
||||||
|
node_id bigint not null,
|
||||||
|
template_id bigint,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
image_values_json TEXT,
|
||||||
|
key_value_values TEXT,
|
||||||
|
notes TEXT,
|
||||||
|
related_page_ids TEXT,
|
||||||
|
table_values TEXT,
|
||||||
|
tags TEXT,
|
||||||
|
title varchar(255) not null,
|
||||||
|
values_json TEXT,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table playthrough_flag (
|
||||||
|
value boolean not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
playthrough_id bigint not null,
|
||||||
|
name varchar(128) not null,
|
||||||
|
primary key (id),
|
||||||
|
constraint uk_playthrough_flag_name unique (playthrough_id, name)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table playthroughs (
|
||||||
|
campaign_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
description TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table quest_progression (
|
||||||
|
chapter_id bigint not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
playthrough_id bigint not null,
|
||||||
|
status varchar(16) not null check (status in ('NOT_STARTED','IN_PROGRESS','COMPLETED')),
|
||||||
|
primary key (id),
|
||||||
|
constraint uk_quest_progression_unique unique (playthrough_id, chapter_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table random_table_entries (
|
||||||
|
max_roll integer not null,
|
||||||
|
min_roll integer not null,
|
||||||
|
position integer not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
random_table_id bigint not null,
|
||||||
|
detail TEXT,
|
||||||
|
label varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table random_tables (
|
||||||
|
"order" integer not null,
|
||||||
|
campaign_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
dice_formula varchar(32) not null,
|
||||||
|
icon varchar(64),
|
||||||
|
description TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table scenes (
|
||||||
|
"order" integer not null,
|
||||||
|
chapter_id bigint not null,
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
atmosphere TEXT,
|
||||||
|
branches TEXT,
|
||||||
|
choices_consequences TEXT,
|
||||||
|
combat_difficulty TEXT,
|
||||||
|
description TEXT,
|
||||||
|
enemies TEXT,
|
||||||
|
enemy_ids TEXT,
|
||||||
|
gm_secret_notes TEXT,
|
||||||
|
icon varchar(255),
|
||||||
|
illustration_image_ids TEXT,
|
||||||
|
location TEXT,
|
||||||
|
map_image_ids TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
player_narration TEXT,
|
||||||
|
related_page_ids TEXT,
|
||||||
|
rooms TEXT,
|
||||||
|
timing TEXT,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table session_entries (
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
occurred_at timestamp(6) not null,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
type varchar(32) not null check (type in ('NOTE','EVENT','DICE_ROLL','PLAYER_ACTION')),
|
||||||
|
content TEXT not null,
|
||||||
|
session_id varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table sessions (
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
ended_at timestamp(6),
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
playthrough_id bigint,
|
||||||
|
started_at timestamp(6) not null,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
campaign_id varchar(255),
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create table templates (
|
||||||
|
created_at timestamp(6) not null,
|
||||||
|
default_node_id bigint,
|
||||||
|
id bigint generated by default as identity,
|
||||||
|
lore_id bigint not null,
|
||||||
|
updated_at timestamp(6) not null,
|
||||||
|
description TEXT,
|
||||||
|
fields TEXT,
|
||||||
|
name varchar(255) not null,
|
||||||
|
primary key (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
create index idx_catalog_items_catalog_id
|
||||||
|
on catalog_items (catalog_id);
|
||||||
|
|
||||||
|
create index idx_conv_lore_entity
|
||||||
|
on conversations (lore_id, entity_type, entity_id, updated_at);
|
||||||
|
|
||||||
|
create index idx_conv_campaign_entity
|
||||||
|
on conversations (campaign_id, entity_type, entity_id, updated_at);
|
||||||
|
|
||||||
|
create index idx_enemies_campaign_id
|
||||||
|
on enemies (campaign_id);
|
||||||
|
|
||||||
|
create index idx_item_catalogs_campaign_id
|
||||||
|
on item_catalogs (campaign_id);
|
||||||
|
|
||||||
|
create index idx_notebook_messages_notebook_id
|
||||||
|
on notebook_messages (notebook_id);
|
||||||
|
|
||||||
|
create index idx_notebook_sources_notebook_id
|
||||||
|
on notebook_sources (notebook_id);
|
||||||
|
|
||||||
|
create index idx_notebooks_campaign_id
|
||||||
|
on notebooks (campaign_id);
|
||||||
|
|
||||||
|
create index ix_playthrough_flag_playthrough
|
||||||
|
on playthrough_flag (playthrough_id);
|
||||||
|
|
||||||
|
create index ix_playthrough_campaign
|
||||||
|
on playthroughs (campaign_id);
|
||||||
|
|
||||||
|
create index ix_quest_progression_playthrough
|
||||||
|
on quest_progression (playthrough_id);
|
||||||
|
|
||||||
|
create index idx_random_table_entries_table_id
|
||||||
|
on random_table_entries (random_table_id);
|
||||||
|
|
||||||
|
create index idx_session_entries_session_id
|
||||||
|
on session_entries (session_id);
|
||||||
|
|
||||||
|
alter table if exists catalog_items
|
||||||
|
add constraint FK7tuoq6mwuc00yv0hhpiw4aoni
|
||||||
|
foreign key (catalog_id)
|
||||||
|
references item_catalogs;
|
||||||
|
|
||||||
|
alter table if exists conversation_messages
|
||||||
|
add constraint FKcr8qqgnqnaqq2hw3gr4wtfe2a
|
||||||
|
foreign key (conversation_id)
|
||||||
|
references conversations;
|
||||||
|
|
||||||
|
alter table if exists random_table_entries
|
||||||
|
add constraint FKly4syvpfit2kibfjut67xxrrq
|
||||||
|
foreign key (random_table_id)
|
||||||
|
references random_tables;
|
||||||
@@ -14,6 +14,10 @@ spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
|||||||
spring.jpa.hibernate.ddl-auto=create-drop
|
spring.jpa.hibernate.ddl-auto=create-drop
|
||||||
spring.jpa.show-sql=false
|
spring.jpa.show-sql=false
|
||||||
|
|
||||||
|
# Flyway desactive en test : le schema est gere par Hibernate create-drop
|
||||||
|
# (recree a chaque run), pas par les migrations. Evite tout conflit Flyway/DDL.
|
||||||
|
spring.flyway.enabled=false
|
||||||
|
|
||||||
# Pool Hikari volontairement minuscule en test : la suite cree de nombreux
|
# Pool Hikari volontairement minuscule en test : la suite cree de nombreux
|
||||||
# contextes Spring distincts (combinaisons de @MockBean / @TestPropertySource),
|
# contextes Spring distincts (combinaisons de @MockBean / @TestPropertySource),
|
||||||
# tous gardes en cache simultanement. Avec le pool par defaut (10), on epuisait
|
# tous gardes en cache simultanement. Avec le pool par defaut (10), on epuisait
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
# Copie en .env sur le serveur (jamais commite).
|
# Copie en .env sur le serveur (jamais commite).
|
||||||
|
|
||||||
# Registre et tag des images core / brain a spawner par session.
|
# Registre, namespace et tag des images core / brain a spawner par session.
|
||||||
REGISTRY=git.igmlcreation.fr
|
# Doit pointer sur le registre ou la CI publie reellement (ghcr.io).
|
||||||
|
# Le slash final de IMAGE_NAMESPACE est important : image = REGISTRY/NAMESPACEcore:TAG
|
||||||
|
REGISTRY=ghcr.io
|
||||||
|
IMAGE_NAMESPACE=igmlcreation/loremind-
|
||||||
TAG=latest
|
TAG=latest
|
||||||
|
|
||||||
# Secret partage entre core et brain (genere aleatoirement au build de chaque
|
# Secret partage entre core et brain (genere aleatoirement au build de chaque
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
// Config centralise les parametres lus depuis les variables d'env au boot.
|
// Config centralise les parametres lus depuis les variables d'env au boot.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Registry string
|
Registry string
|
||||||
|
Namespace string
|
||||||
Tag string
|
Tag string
|
||||||
MaxSessions int
|
MaxSessions int
|
||||||
SessionTTL time.Duration
|
SessionTTL time.Duration
|
||||||
@@ -27,7 +28,12 @@ type Config struct {
|
|||||||
|
|
||||||
func loadConfig() *Config {
|
func loadConfig() *Config {
|
||||||
return &Config{
|
return &Config{
|
||||||
Registry: envStr("REGISTRY", "git.igmlcreation.fr"),
|
// Aligne sur la nouvelle convention de publication des images
|
||||||
|
// (ghcr.io/igmlcreation/loremind-{core,brain}). L'ancien registre Gitea
|
||||||
|
// (git.igmlcreation.fr/ietm64/*) n'est plus republie : il restait gele
|
||||||
|
// sur une vieille version. Le slash final de Namespace est volontaire.
|
||||||
|
Registry: envStr("REGISTRY", "ghcr.io"),
|
||||||
|
Namespace: envStr("IMAGE_NAMESPACE", "igmlcreation/loremind-"),
|
||||||
Tag: envStr("TAG", "latest"),
|
Tag: envStr("TAG", "latest"),
|
||||||
MaxSessions: envInt("MAX_SESSIONS", 10),
|
MaxSessions: envInt("MAX_SESSIONS", 10),
|
||||||
SessionTTL: time.Duration(envInt("SESSION_TTL_MINUTES", 20)) * time.Minute,
|
SessionTTL: time.Duration(envInt("SESSION_TTL_MINUTES", 20)) * time.Minute,
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ func (d *DockerClient) SpawnTrio(ctx context.Context, sessionID string, cfg *Con
|
|||||||
|
|
||||||
if err := d.runContainer(ctx, runSpec{
|
if err := d.runContainer(ctx, runSpec{
|
||||||
Name: brainName,
|
Name: brainName,
|
||||||
Image: cfg.Registry + "/ietm64/brain:" + cfg.Tag,
|
Image: cfg.Registry + "/" + cfg.Namespace + "brain:" + cfg.Tag,
|
||||||
Env: []string{
|
Env: []string{
|
||||||
"INTERNAL_SHARED_SECRET=" + brainSecret,
|
"INTERNAL_SHARED_SECRET=" + brainSecret,
|
||||||
// Pas de provider LLM configure en demo : les features IA echoueront
|
// Pas de provider LLM configure en demo : les features IA echoueront
|
||||||
@@ -129,7 +129,7 @@ func (d *DockerClient) SpawnTrio(ctx context.Context, sessionID string, cfg *Con
|
|||||||
|
|
||||||
if err := d.runContainer(ctx, runSpec{
|
if err := d.runContainer(ctx, runSpec{
|
||||||
Name: coreName,
|
Name: coreName,
|
||||||
Image: cfg.Registry + "/ietm64/core:" + cfg.Tag,
|
Image: cfg.Registry + "/" + cfg.Namespace + "core:" + cfg.Tag,
|
||||||
Env: []string{
|
Env: []string{
|
||||||
"SPRING_DATASOURCE_URL=jdbc:postgresql://" + pgName + ":5432/loremind",
|
"SPRING_DATASOURCE_URL=jdbc:postgresql://" + pgName + ":5432/loremind",
|
||||||
"SPRING_DATASOURCE_USERNAME=loremind",
|
"SPRING_DATASOURCE_USERNAME=loremind",
|
||||||
|
|||||||
@@ -252,7 +252,11 @@ services:
|
|||||||
# API HTTP pour declenchement manuel via le bouton UI (Core -> Watchtower).
|
# API HTTP pour declenchement manuel via le bouton UI (Core -> Watchtower).
|
||||||
WATCHTOWER_HTTP_API_UPDATE: "true"
|
WATCHTOWER_HTTP_API_UPDATE: "true"
|
||||||
WATCHTOWER_HTTP_API_PERIODIC_POLLS: "true"
|
WATCHTOWER_HTTP_API_PERIODIC_POLLS: "true"
|
||||||
WATCHTOWER_HTTP_API_TOKEN: "${WATCHTOWER_TOKEN:?set WATCHTOWER_TOKEN in .env (re-run installer)}"
|
# Pas de ":?" ici : Compose interpole TOUT le fichier avant de filtrer
|
||||||
|
# par profile, donc un ":?" planterait le "up" meme quand autoupdate est
|
||||||
|
# inactif. L'installeur genere toujours WATCHTOWER_TOKEN ; defaut vide
|
||||||
|
# pour ne rien casser sur les deploiements sans autoupdate.
|
||||||
|
WATCHTOWER_HTTP_API_TOKEN: "${WATCHTOWER_TOKEN:-}"
|
||||||
WATCHTOWER_TIMEOUT: 60s
|
WATCHTOWER_TIMEOUT: 60s
|
||||||
WATCHTOWER_NOTIFICATIONS_LEVEL: info
|
WATCHTOWER_NOTIFICATIONS_LEVEL: info
|
||||||
TZ: ${TZ:-Europe/Paris}
|
TZ: ${TZ:-Europe/Paris}
|
||||||
|
|||||||
214
installers/desktop/build-windows.ps1
Normal file
214
installers/desktop/build-windows.ps1
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
#Requires -Version 5.1
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Construit l'installeur de BUREAU Windows de LoreMind (.msi), sans Docker.
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Pipeline complet "local-first" :
|
||||||
|
1. Build du front Angular (web/ -> web/dist/web)
|
||||||
|
2. Prep du Brain (Python embeddable) (brain/ -> dist-embed : python.exe signe PSF + deps + sources)
|
||||||
|
3. Build du Core en fat jar + front (core/ -> target/*.jar, profil Maven "desktop")
|
||||||
|
4. Assemblage de la charge utile (jar + brain) dans un dossier d'entree jpackage
|
||||||
|
5. jpackage -> installeur .msi avec JRE embarque
|
||||||
|
|
||||||
|
L'app resultante se lance d'un double-clic : le Core demarre en profil Spring
|
||||||
|
"local" (H2 fichier + stockage filesystem) et lance lui-meme le Brain en sidecar.
|
||||||
|
Aucune dependance externe a installer cote utilisateur (ni Docker, ni Java, ni Python).
|
||||||
|
L'IA fonctionne via le cloud (1min.ai / Gemini / Mistral...) ou via Ollama si present.
|
||||||
|
|
||||||
|
.PARAMETER Version
|
||||||
|
Version de l'installeur (X.Y.Z, numerique). Defaut : derivee de core/pom.xml
|
||||||
|
(le suffixe -beta est retire car les MSI n'acceptent qu'une version numerique).
|
||||||
|
|
||||||
|
.PARAMETER SkipFront / SkipBrain / SkipJar
|
||||||
|
Sauter une etape (build incrementaux pendant la mise au point).
|
||||||
|
|
||||||
|
.PREREQUIS (sur la machine de build uniquement, PAS chez l'utilisateur final)
|
||||||
|
- JDK 21+ avec jpackage dans le PATH (Temurin OK).
|
||||||
|
- WiX Toolset v3 (https://github.com/wixtoolset/wix3/releases) — requis par
|
||||||
|
jpackage pour produire un .msi sur Windows.
|
||||||
|
- Node.js + npm (build Angular).
|
||||||
|
- Python + pip (telecharge les wheels cp312 du Brain ; toute version 3.x convient,
|
||||||
|
on cible explicitement 3.12 via --python-version) + acces Internet (python.org).
|
||||||
|
|
||||||
|
.NOTES
|
||||||
|
Projet : LoreMind — assistant pour Maitres de Jeu de JDR
|
||||||
|
Licence : AGPL-3.0
|
||||||
|
#>
|
||||||
|
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[string]$Version,
|
||||||
|
[switch]$SkipFront,
|
||||||
|
[switch]$SkipBrain,
|
||||||
|
[switch]$SkipJar
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
function Write-Step($m) { Write-Host "==> $m" -ForegroundColor Cyan }
|
||||||
|
function Write-Ok($m) { Write-Host " OK $m" -ForegroundColor Green }
|
||||||
|
function Write-Err($m) { Write-Host " XX $m" -ForegroundColor Red }
|
||||||
|
|
||||||
|
# --- Chemins ---------------------------------------------------------------
|
||||||
|
$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||||
|
$WebDir = Join-Path $RepoRoot 'web'
|
||||||
|
$BrainDir = Join-Path $RepoRoot 'brain'
|
||||||
|
$CoreDir = Join-Path $RepoRoot 'core'
|
||||||
|
$StageDir = Join-Path $CoreDir 'target\dist-input' # charge utile jpackage
|
||||||
|
$OutDir = Join-Path $CoreDir 'target\dist-out' # .msi produit
|
||||||
|
|
||||||
|
# --- Version (numerique pour MSI) ------------------------------------------
|
||||||
|
if (-not $Version) {
|
||||||
|
$pom = Get-Content (Join-Path $CoreDir 'pom.xml') -Raw
|
||||||
|
# IMPORTANT : viser la version DU PROJET, pas le premier <version> du fichier
|
||||||
|
# (qui est celui du parent spring-boot-starter-parent). On l'ancre sur
|
||||||
|
# l'artifactId du projet, puis on garde la partie numerique (MSI = X.Y.Z).
|
||||||
|
if ($pom -match '<artifactId>loremind-core</artifactId>\s*<version>([0-9]+\.[0-9]+\.[0-9]+)') {
|
||||||
|
$Version = $Matches[1]
|
||||||
|
} else {
|
||||||
|
$Version = '0.0.0'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "============================================================" -ForegroundColor Magenta
|
||||||
|
Write-Host " LoreMind - Build installeur bureau Windows (v$Version)" -ForegroundColor Magenta
|
||||||
|
Write-Host "============================================================" -ForegroundColor Magenta
|
||||||
|
|
||||||
|
# --- Verif outils ----------------------------------------------------------
|
||||||
|
if (-not (Get-Command jpackage -ErrorAction SilentlyContinue)) {
|
||||||
|
Write-Err "jpackage introuvable dans le PATH. Installez un JDK 21+ (Temurin)."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 1. Front Angular ------------------------------------------------------
|
||||||
|
if (-not $SkipFront) {
|
||||||
|
Write-Step "Build du front Angular"
|
||||||
|
Push-Location $WebDir
|
||||||
|
try {
|
||||||
|
if (-not (Test-Path 'node_modules')) { npm ci }
|
||||||
|
npm run build
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Echec du build Angular" }
|
||||||
|
} finally { Pop-Location }
|
||||||
|
Write-Ok "Front construit (web/dist/web)"
|
||||||
|
} else { Write-Step "Front : saute (--SkipFront)" }
|
||||||
|
|
||||||
|
# --- 2. Brain (Python embeddable officiel, PAS d'exe gele) -----------------
|
||||||
|
# On embarque le Python *embeddable* de python.org (python.exe SIGNE par la PSF)
|
||||||
|
# + les dependances + les sources .py. Aucun executable "gele" type PyInstaller
|
||||||
|
# -> plus de faux positif antivirus (le bootloader packe etait pris pour un
|
||||||
|
# trojan). Le Core lancera : brain\python\python.exe brain\run_local.py
|
||||||
|
$PyVersion = '3.12.8' # doit matcher python:3.12 du Docker
|
||||||
|
$PyTag = 'python312' # prefixe du fichier ._pth
|
||||||
|
$BrainEmbed = Join-Path $BrainDir 'dist-embed' # staging du brain empaquete
|
||||||
|
if (-not $SkipBrain) {
|
||||||
|
Write-Step "Preparation du Brain (Python embeddable $PyVersion)"
|
||||||
|
if (Test-Path $BrainEmbed) { Remove-Item $BrainEmbed -Recurse -Force }
|
||||||
|
$PyDir = Join-Path $BrainEmbed 'python'
|
||||||
|
New-Item -ItemType Directory -Force -Path $PyDir | Out-Null
|
||||||
|
|
||||||
|
# a) Telecharger + extraire le Python embeddable (zip officiel).
|
||||||
|
$zip = Join-Path $BrainEmbed 'python-embed.zip'
|
||||||
|
$url = "https://www.python.org/ftp/python/$PyVersion/python-$PyVersion-embed-amd64.zip"
|
||||||
|
Write-Host " Telechargement $url"
|
||||||
|
Invoke-WebRequest -Uri $url -OutFile $zip -UseBasicParsing
|
||||||
|
Expand-Archive -Path $zip -DestinationPath $PyDir -Force
|
||||||
|
Remove-Item $zip -Force
|
||||||
|
|
||||||
|
# b) Activer site-packages dans le ._pth (sinon les deps ne sont pas importees).
|
||||||
|
$pth = Join-Path $PyDir "$PyTag._pth"
|
||||||
|
Set-Content -Path $pth -Encoding ascii -Value @(
|
||||||
|
"$PyTag.zip", '.', 'Lib\site-packages', 'import site'
|
||||||
|
)
|
||||||
|
|
||||||
|
# c) Installer les deps en wheels cp312 dans python\Lib\site-packages.
|
||||||
|
# --python-version 3.12 + --only-binary : on telecharge les roues 3.12
|
||||||
|
# meme si le pip courant tourne sous une autre version de Python.
|
||||||
|
$site = Join-Path $PyDir 'Lib\site-packages'
|
||||||
|
New-Item -ItemType Directory -Force -Path $site | Out-Null
|
||||||
|
Push-Location $BrainDir
|
||||||
|
try {
|
||||||
|
python -m pip install --upgrade pip *> $null
|
||||||
|
python -m pip install --target $site --only-binary=:all: --python-version 3.12 -r requirements.txt
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Echec pip install (deps Brain)" }
|
||||||
|
} finally { Pop-Location }
|
||||||
|
|
||||||
|
# d) Copier les sources du Brain + le point d'entree.
|
||||||
|
Copy-Item (Join-Path $BrainDir 'app') (Join-Path $BrainEmbed 'app') -Recurse
|
||||||
|
Copy-Item (Join-Path $BrainDir 'run_local.py') (Join-Path $BrainEmbed 'run_local.py')
|
||||||
|
|
||||||
|
Write-Ok "Brain prepare (brain/dist-embed : python embeddable + deps + sources)"
|
||||||
|
} else { Write-Step "Brain : saute (--SkipBrain)" }
|
||||||
|
|
||||||
|
# --- 3. Core (fat jar avec front embarque) ---------------------------------
|
||||||
|
if (-not $SkipJar) {
|
||||||
|
Write-Step "Build du Core (fat jar, profil desktop)"
|
||||||
|
Push-Location $CoreDir
|
||||||
|
try {
|
||||||
|
# -Pdesktop : copie web/dist/web dans le jar (classpath:/static).
|
||||||
|
cmd /c "mvn -q -Pdesktop -DskipTests clean package"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Echec du build Maven" }
|
||||||
|
} finally { Pop-Location }
|
||||||
|
Write-Ok "Core construit (core/target)"
|
||||||
|
} else { Write-Step "Core : saute (--SkipJar)" }
|
||||||
|
|
||||||
|
# --- 4. Assemblage de la charge utile --------------------------------------
|
||||||
|
Write-Step "Assemblage de la charge utile jpackage"
|
||||||
|
if (Test-Path $StageDir) { Remove-Item $StageDir -Recurse -Force }
|
||||||
|
New-Item -ItemType Directory -Force -Path $StageDir | Out-Null
|
||||||
|
|
||||||
|
# Le jar repackage Spring Boot (executable) — on ignore le *.jar.original.
|
||||||
|
$jar = Get-ChildItem (Join-Path $CoreDir 'target') -Filter 'loremind-core-*.jar' |
|
||||||
|
Where-Object { $_.Name -notlike '*.original' } | Select-Object -First 1
|
||||||
|
if (-not $jar) { Write-Err "Jar introuvable dans core/target. Lancez sans --SkipJar."; exit 1 }
|
||||||
|
Copy-Item $jar.FullName (Join-Path $StageDir 'loremind-core.jar')
|
||||||
|
|
||||||
|
# Le Brain (python embeddable + deps + sources) -> stage/brain/
|
||||||
|
# stage/brain/python/python.exe , stage/brain/app , stage/brain/run_local.py
|
||||||
|
if (-not (Test-Path $BrainEmbed)) { Write-Err "Brain introuvable (brain/dist-embed). Lancez sans --SkipBrain."; exit 1 }
|
||||||
|
$stageBrain = Join-Path $StageDir 'brain'
|
||||||
|
New-Item -ItemType Directory -Force -Path $stageBrain | Out-Null
|
||||||
|
Copy-Item (Join-Path $BrainEmbed '*') $stageBrain -Recurse
|
||||||
|
Write-Ok "Charge utile prete ($StageDir)"
|
||||||
|
|
||||||
|
# --- 5. jpackage -> .msi ---------------------------------------------------
|
||||||
|
Write-Step "Generation de l'installeur (.msi) via jpackage"
|
||||||
|
if (Test-Path $OutDir) { Remove-Item $OutDir -Recurse -Force }
|
||||||
|
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
|
||||||
|
|
||||||
|
# $APPDIR est substitue par jpackage au LANCEMENT par le dossier 'app' de
|
||||||
|
# l'install (qui contient le jar ET le dossier brain copie depuis --input).
|
||||||
|
# Le Brain se lance via le python embeddable + run_local.py. brain.sidecar.command
|
||||||
|
# est une liste : les deux chemins separes par une virgule (aucun chemin Windows
|
||||||
|
# ne contient de virgule) sont bindes en List<String> par Spring.
|
||||||
|
$brainCmd = '$APPDIR\brain\python\python.exe,$APPDIR\brain\run_local.py'
|
||||||
|
|
||||||
|
# Note : pas de --win-console (app de bureau). Les logs Spring/Brain peuvent
|
||||||
|
# etre rediriges vers un fichier via une option ulterieure si besoin de debug.
|
||||||
|
jpackage `
|
||||||
|
--type msi `
|
||||||
|
--name LoreMind `
|
||||||
|
--app-version $Version `
|
||||||
|
--vendor 'IGML Creation' `
|
||||||
|
--input $StageDir `
|
||||||
|
--main-jar loremind-core.jar `
|
||||||
|
--main-class org.springframework.boot.loader.launch.JarLauncher `
|
||||||
|
--dest $OutDir `
|
||||||
|
--java-options '-Dspring.profiles.active=local' `
|
||||||
|
--java-options "-Dbrain.sidecar.command=$brainCmd" `
|
||||||
|
--win-per-user-install `
|
||||||
|
--win-menu --win-menu-group 'LoreMind' `
|
||||||
|
--win-shortcut --win-dir-chooser
|
||||||
|
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Err "Echec jpackage. Cause probable : WiX Toolset v3 absent."
|
||||||
|
Write-Err "Installez-le : https://github.com/wixtoolset/wix3/releases"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$msi = Get-ChildItem $OutDir -Filter '*.msi' | Select-Object -First 1
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "============================================================" -ForegroundColor Green
|
||||||
|
Write-Host " Installeur genere !" -ForegroundColor Green
|
||||||
|
Write-Host " $($msi.FullName)" -ForegroundColor Green
|
||||||
|
Write-Host "============================================================" -ForegroundColor Green
|
||||||
4
web/package-lock.json
generated
4
web/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "0.14.0-beta",
|
"version": "0.16.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "0.14.0-beta",
|
"version": "0.16.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular/animations": "^21.2.16",
|
"@angular/animations": "^21.2.16",
|
||||||
"@angular/common": "^21.2.16",
|
"@angular/common": "^21.2.16",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "loremind-web",
|
"name": "loremind-web",
|
||||||
"version": "0.14.0-beta",
|
"version": "0.16.0",
|
||||||
"description": "LoreMind Frontend - Angular",
|
"description": "LoreMind Frontend - Angular",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"ng": "ng",
|
"ng": "ng",
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { HttpInterceptorFn } from '@angular/common/http';
|
import { HttpInterceptorFn } from '@angular/common/http';
|
||||||
import { inject } from '@angular/core';
|
import { STORAGE_KEY } from '../services/language.service';
|
||||||
import { LanguageService } from '../services/language.service';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ajoute l'entête `X-User-Language` (langue choisie dans l'UI : `fr`/`en`) à
|
* Ajoute l'entête `X-User-Language` (langue choisie dans l'UI : `fr`/`en`) à
|
||||||
@@ -9,10 +8,27 @@ import { LanguageService } from '../services/language.service';
|
|||||||
*
|
*
|
||||||
* NB : les appels SSE en `fetch()` (chat, imports, notebooks) ne passent PAS par
|
* NB : les appels SSE en `fetch()` (chat, imports, notebooks) ne passent PAS par
|
||||||
* les intercepteurs Angular — ils ajoutent l'entête manuellement de leur côté.
|
* les intercepteurs Angular — ils ajoutent l'entête manuellement de leur côté.
|
||||||
|
*
|
||||||
|
* IMPORTANT — on lit la langue directement depuis localStorage et NON via
|
||||||
|
* LanguageService/TranslateService. Injecter ces services ici créerait une
|
||||||
|
* dépendance circulaire fatale au démarrage : provideTranslateService charge la
|
||||||
|
* langue de repli (`fr.json`) PENDANT la construction de TranslateService ; cette
|
||||||
|
* requête passe par cet intercepteur ; si l'intercepteur injectait LanguageService
|
||||||
|
* (qui injecte TranslateService, en cours de construction) → cycle → la requête
|
||||||
|
* `fr.json` échoue → ngx-translate marque `fr` comme chargé-mais-vide → toutes les
|
||||||
|
* clés s'affichent brutes (l'anglais, n'étant pas la langue de repli, se chargeait
|
||||||
|
* après la construction et fonctionnait). localStorage est de toute façon la
|
||||||
|
* source de vérité (persistée par LanguageService.use()).
|
||||||
*/
|
*/
|
||||||
export const languageInterceptor: HttpInterceptorFn = (req, next) => {
|
export const languageInterceptor: HttpInterceptorFn = (req, next) => {
|
||||||
const language = inject(LanguageService);
|
let language = 'fr';
|
||||||
return next(
|
try {
|
||||||
req.clone({ setHeaders: { 'X-User-Language': language.current } })
|
const stored = localStorage.getItem(STORAGE_KEY);
|
||||||
);
|
if (stored) {
|
||||||
|
language = stored;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// localStorage indisponible (mode privé strict) : on garde le défaut.
|
||||||
|
}
|
||||||
|
return next(req.clone({ setHeaders: { 'X-User-Language': language } }));
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -22,7 +22,13 @@ export interface AppLanguage {
|
|||||||
flag: string;
|
flag: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STORAGE_KEY = 'loremind.lang';
|
/**
|
||||||
|
* Clé localStorage du choix de langue (par appareil). Exportée pour que le
|
||||||
|
* languageInterceptor lise la langue SANS injecter LanguageService/TranslateService
|
||||||
|
* (sinon dépendance circulaire au démarrage : le chargement initial de la langue
|
||||||
|
* de repli passe par l'intercepteur pendant la construction de TranslateService).
|
||||||
|
*/
|
||||||
|
export const STORAGE_KEY = 'loremind.lang';
|
||||||
|
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
export class LanguageService {
|
export class LanguageService {
|
||||||
|
|||||||
@@ -66,6 +66,13 @@ export interface OllamaModelInfo {
|
|||||||
context_length: number;
|
context_length: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resultat d'un import de donnees (compteurs par type + images). */
|
||||||
|
export interface ImportResult {
|
||||||
|
created: Record<string, number>;
|
||||||
|
imagesUploaded: number;
|
||||||
|
imagesReused: number;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
export class SettingsService {
|
export class SettingsService {
|
||||||
private readonly apiUrl = '/api/settings';
|
private readonly apiUrl = '/api/settings';
|
||||||
@@ -85,6 +92,21 @@ export class SettingsService {
|
|||||||
return this.http.put<AppSettings>(this.apiUrl, patch, this.authOptions);
|
return this.http.put<AppSettings>(this.apiUrl, patch, this.authOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Export / Import des donnees (sauvegarde & transfert d'instance) -------
|
||||||
|
|
||||||
|
/** Telecharge l'export complet du contenu (zip : data.json + images). */
|
||||||
|
exportData(): Observable<Blob> {
|
||||||
|
return this.http.get('/api/admin/data/export',
|
||||||
|
{ withCredentials: true, responseType: 'blob' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Importe un zip d'export en mode FUSION (ajoute, ne remplace pas). */
|
||||||
|
importData(file: File): Observable<ImportResult> {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('file', file);
|
||||||
|
return this.http.post<ImportResult>('/api/admin/data/import', form, this.authOptions);
|
||||||
|
}
|
||||||
|
|
||||||
listOllamaModels(): Observable<{ models: string[] }> {
|
listOllamaModels(): Observable<{ models: string[] }> {
|
||||||
return this.http.get<{ models: string[] }>(`${this.apiUrl}/models/ollama`, this.authOptions);
|
return this.http.get<{ models: string[] }>(`${this.apiUrl}/models/ollama`, this.authOptions);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -112,7 +112,7 @@
|
|||||||
<label for="onemin-key">{{ 'settings.apiKey.label' | translate }}</label>
|
<label for="onemin-key">{{ 'settings.apiKey.label' | translate }}</label>
|
||||||
<input
|
<input
|
||||||
id="onemin-key"
|
id="onemin-key"
|
||||||
type="password"
|
type="password" autocomplete="new-password" data-1p-ignore data-lpignore="true" data-bwignore
|
||||||
[(ngModel)]="oneminApiKeyInput"
|
[(ngModel)]="oneminApiKeyInput"
|
||||||
[placeholder]="(settings.onemin_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderOnemin') | translate">
|
[placeholder]="(settings.onemin_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderOnemin') | translate">
|
||||||
@if (settings.onemin_api_key_set) {
|
@if (settings.onemin_api_key_set) {
|
||||||
@@ -149,7 +149,7 @@
|
|||||||
<label for="openrouter-key">{{ 'settings.apiKey.label' | translate }}</label>
|
<label for="openrouter-key">{{ 'settings.apiKey.label' | translate }}</label>
|
||||||
<input
|
<input
|
||||||
id="openrouter-key"
|
id="openrouter-key"
|
||||||
type="password"
|
type="password" autocomplete="new-password" data-1p-ignore data-lpignore="true" data-bwignore
|
||||||
[(ngModel)]="openrouterApiKeyInput"
|
[(ngModel)]="openrouterApiKeyInput"
|
||||||
[placeholder]="(settings.openrouter_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderOpenrouter') | translate">
|
[placeholder]="(settings.openrouter_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderOpenrouter') | translate">
|
||||||
@if (settings.openrouter_api_key_set) {
|
@if (settings.openrouter_api_key_set) {
|
||||||
@@ -183,7 +183,7 @@
|
|||||||
<label for="mistral-key">{{ 'settings.apiKey.label' | translate }}</label>
|
<label for="mistral-key">{{ 'settings.apiKey.label' | translate }}</label>
|
||||||
<input
|
<input
|
||||||
id="mistral-key"
|
id="mistral-key"
|
||||||
type="password"
|
type="password" autocomplete="new-password" data-1p-ignore data-lpignore="true" data-bwignore
|
||||||
[(ngModel)]="mistralApiKeyInput"
|
[(ngModel)]="mistralApiKeyInput"
|
||||||
[placeholder]="(settings.mistral_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderMistral') | translate">
|
[placeholder]="(settings.mistral_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderMistral') | translate">
|
||||||
@if (settings.mistral_api_key_set) {
|
@if (settings.mistral_api_key_set) {
|
||||||
@@ -213,7 +213,7 @@
|
|||||||
<label for="gemini-key">{{ 'settings.apiKey.label' | translate }}</label>
|
<label for="gemini-key">{{ 'settings.apiKey.label' | translate }}</label>
|
||||||
<input
|
<input
|
||||||
id="gemini-key"
|
id="gemini-key"
|
||||||
type="password"
|
type="password" autocomplete="new-password" data-1p-ignore data-lpignore="true" data-bwignore
|
||||||
[(ngModel)]="geminiApiKeyInput"
|
[(ngModel)]="geminiApiKeyInput"
|
||||||
[placeholder]="(settings.gemini_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderGemini') | translate">
|
[placeholder]="(settings.gemini_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderGemini') | translate">
|
||||||
@if (settings.gemini_api_key_set) {
|
@if (settings.gemini_api_key_set) {
|
||||||
@@ -285,7 +285,7 @@
|
|||||||
<span class="key-state">{{ 'settings.apiKey.configured' | translate }}</span>
|
<span class="key-state">{{ 'settings.apiKey.configured' | translate }}</span>
|
||||||
}
|
}
|
||||||
</label>
|
</label>
|
||||||
<input id="emb-mistral-key" type="password" [(ngModel)]="mistralApiKeyInput"
|
<input id="emb-mistral-key" type="password" autocomplete="new-password" data-1p-ignore data-lpignore="true" data-bwignore [(ngModel)]="mistralApiKeyInput"
|
||||||
[placeholder]="(settings.mistral_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderMistral') | translate">
|
[placeholder]="(settings.mistral_api_key_set ? 'settings.apiKey.placeholderSet' : 'settings.apiKey.placeholderMistral') | translate">
|
||||||
@if (settings.mistral_api_key_set) {
|
@if (settings.mistral_api_key_set) {
|
||||||
<label class="checkbox">
|
<label class="checkbox">
|
||||||
@@ -372,6 +372,33 @@
|
|||||||
<!-- Mises a jour conteneurs + licence Patreon + canal beta (sous-composant) -->
|
<!-- Mises a jour conteneurs + licence Patreon + canal beta (sous-composant) -->
|
||||||
<app-settings-updates-section></app-settings-updates-section>
|
<app-settings-updates-section></app-settings-updates-section>
|
||||||
|
|
||||||
|
<!-- Sauvegarde / Restauration des donnees (export & import) -->
|
||||||
|
<section class="card">
|
||||||
|
<h2>{{ 'settings.data.title' | translate }}</h2>
|
||||||
|
<p class="hint" [innerHTML]="'settings.data.hint' | translate"></p>
|
||||||
|
<div class="actions">
|
||||||
|
<button type="button" class="btn-secondary" (click)="exportData()" [disabled]="exporting || importing">
|
||||||
|
<span>{{ (exporting ? 'settings.data.exporting' : 'settings.data.exportBtn') | translate }}</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-secondary" (click)="importInput.click()" [disabled]="exporting || importing">
|
||||||
|
<span>{{ (importing ? 'settings.data.importing' : 'settings.data.importBtn') | translate }}</span>
|
||||||
|
</button>
|
||||||
|
<input #importInput type="file" accept=".zip,application/zip" hidden (change)="onImportFileSelected($event)">
|
||||||
|
</div>
|
||||||
|
@if (dataError) {
|
||||||
|
<div class="alert alert-error">
|
||||||
|
<lucide-icon [img]="AlertCircle" [size]="16"></lucide-icon>
|
||||||
|
<span>{{ dataError }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (dataMessage) {
|
||||||
|
<div class="alert alert-success">
|
||||||
|
<lucide-icon [img]="Check" [size]="16"></lucide-icon>
|
||||||
|
<span>{{ dataMessage }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
@if (settings) {
|
@if (settings) {
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn-primary" (click)="save()" [disabled]="saving">
|
<button class="btn-primary" (click)="save()" [disabled]="saving">
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { FormsModule } from '@angular/forms';
|
|||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { LucideAngularModule, ArrowLeft, RefreshCw, Save, Check, AlertCircle, Plus } from 'lucide-angular';
|
import { LucideAngularModule, ArrowLeft, RefreshCw, Save, Check, AlertCircle, Plus } from 'lucide-angular';
|
||||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||||
import { SettingsService, AppSettings, AppSettingsUpdate, OneMinModelGroup, OpenRouterModel, MistralModel, GeminiModel } from '../services/settings.service';
|
import { SettingsService, AppSettings, AppSettingsUpdate, OneMinModelGroup, OpenRouterModel, MistralModel, GeminiModel, ImportResult } from '../services/settings.service';
|
||||||
import { LayoutService } from '../services/layout.service';
|
import { LayoutService } from '../services/layout.service';
|
||||||
import { UpdatesSectionComponent } from './updates-section/updates-section.component';
|
import { UpdatesSectionComponent } from './updates-section/updates-section.component';
|
||||||
import { OllamaModelManagerComponent } from './ollama-model-manager/ollama-model-manager.component';
|
import { OllamaModelManagerComponent } from './ollama-model-manager/ollama-model-manager.component';
|
||||||
@@ -332,6 +332,60 @@ export class SettingsComponent implements OnInit {
|
|||||||
this.router.navigate(['/lore']);
|
this.router.navigate(['/lore']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Sauvegarde / Restauration des donnees --------------------------------
|
||||||
|
|
||||||
|
exporting = false;
|
||||||
|
importing = false;
|
||||||
|
dataMessage = '';
|
||||||
|
dataError = '';
|
||||||
|
|
||||||
|
/** Telecharge l'export complet (zip) via un lien temporaire. */
|
||||||
|
exportData(): void {
|
||||||
|
this.exporting = true;
|
||||||
|
this.dataMessage = '';
|
||||||
|
this.dataError = '';
|
||||||
|
this.settingsService.exportData().subscribe({
|
||||||
|
next: (blob) => {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = 'loremind-export.zip';
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
this.exporting = false;
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
this.dataError = this.extractError(err, this.translate.instant('settings.data.exportError'));
|
||||||
|
this.exporting = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Déclenché par le sélecteur de fichier : importe le zip choisi (fusion). */
|
||||||
|
onImportFileSelected(event: Event): void {
|
||||||
|
const input = event.target as HTMLInputElement;
|
||||||
|
const file = input.files?.[0];
|
||||||
|
input.value = ''; // permet de re-sélectionner le même fichier
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
if (!confirm(this.translate.instant('settings.data.importConfirm'))) return;
|
||||||
|
|
||||||
|
this.importing = true;
|
||||||
|
this.dataMessage = '';
|
||||||
|
this.dataError = '';
|
||||||
|
this.settingsService.importData(file).subscribe({
|
||||||
|
next: (result: ImportResult) => {
|
||||||
|
const total = Object.values(result.created).reduce((a, b) => a + b, 0);
|
||||||
|
this.dataMessage = this.translate.instant('settings.data.importSuccess', { count: total });
|
||||||
|
this.importing = false;
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
this.dataError = this.extractError(err, this.translate.instant('settings.data.importError'));
|
||||||
|
this.importing = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private extractError(err: any, fallback: string): string {
|
private extractError(err: any, fallback: string): string {
|
||||||
if (err?.error?.detail) return String(err.error.detail);
|
if (err?.error?.detail) return String(err.error.detail);
|
||||||
if (err?.message) return err.message;
|
if (err?.message) return err.message;
|
||||||
|
|||||||
@@ -50,6 +50,18 @@
|
|||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"title": "Settings",
|
"title": "Settings",
|
||||||
|
"data": {
|
||||||
|
"title": "Data backup",
|
||||||
|
"hint": "Export all your content (game systems, lores, campaigns + images) to a file, to back it up or move it to another instance. Importing <strong>adds</strong> the content without deleting what's already there.",
|
||||||
|
"exportBtn": "Export data",
|
||||||
|
"exporting": "Exporting…",
|
||||||
|
"importBtn": "Import a file",
|
||||||
|
"importing": "Importing…",
|
||||||
|
"importConfirm": "Import this file? Its content will be added to your instance (nothing is deleted).",
|
||||||
|
"importSuccess": "Import successful: {{count}} item(s) added.",
|
||||||
|
"exportError": "Export failed.",
|
||||||
|
"importError": "Import failed (invalid file?)."
|
||||||
|
},
|
||||||
"language": {
|
"language": {
|
||||||
"title": "Interface language",
|
"title": "Interface language",
|
||||||
"hint": "Choose the application display language. The change is applied instantly and remembered on this device."
|
"hint": "Choose the application display language. The change is applied instantly and remembered on this device."
|
||||||
|
|||||||
@@ -50,6 +50,18 @@
|
|||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"title": "Paramètres",
|
"title": "Paramètres",
|
||||||
|
"data": {
|
||||||
|
"title": "Sauvegarde des données",
|
||||||
|
"hint": "Exportez tout votre contenu (systèmes de jeu, lores, campagnes + images) dans un fichier, pour le sauvegarder ou le transférer vers une autre instance. L'import <strong>ajoute</strong> le contenu sans supprimer l'existant.",
|
||||||
|
"exportBtn": "Exporter les données",
|
||||||
|
"exporting": "Export en cours…",
|
||||||
|
"importBtn": "Importer un fichier",
|
||||||
|
"importing": "Import en cours…",
|
||||||
|
"importConfirm": "Importer ce fichier ? Le contenu sera ajouté à votre instance (rien n'est supprimé).",
|
||||||
|
"importSuccess": "Import réussi : {{count}} élément(s) ajouté(s).",
|
||||||
|
"exportError": "Échec de l'export.",
|
||||||
|
"importError": "Échec de l'import (fichier invalide ?)."
|
||||||
|
},
|
||||||
"language": {
|
"language": {
|
||||||
"title": "Langue de l'interface",
|
"title": "Langue de l'interface",
|
||||||
"hint": "Choix de la langue d'affichage de l'application. Le changement est immédiat et mémorisé sur cet appareil."
|
"hint": "Choix de la langue d'affichage de l'application. Le changement est immédiat et mémorisé sur cet appareil."
|
||||||
|
|||||||
Reference in New Issue
Block a user