mirror of
https://github.com/IliesAllali/parenthese.git
synced 2026-11-17 16:42:23 +00:00
Merge pull request #58 from coutadeurf/feat/immich-face-integration-clean
Integrates Immich face recognition with Parenthèse to associate Immich people with family-tree members and synchronize their portraits.
This commit is contained in:
32 files changed
+3797
-18
No files matched your search
@@ -34,6 +34,17 @@ CORS_ORIGIN=http://localhost
|
||||
# MEDIA_QUOTA_PER_TREE_MB=5120
|
||||
# MEDIA_PENDING_QUOTA_PER_TREE_MB=500
|
||||
|
||||
# ── Immich (reconnaissance des visages, désactivé par défaut) ────────────────
|
||||
# Instances Immich autorisées sur ce serveur, séparées par des virgules. Chaque entrée
|
||||
# peut recevoir un libellé, « Libellé=https://adresse » ; sans libellé, c'est le nom
|
||||
# d'hôte qui sert (un même nom d'hôte ne peut pas servir à deux instances : donnez-leur
|
||||
# un libellé). Les administrateurs de chaque arbre choisissent l'instance par son nom
|
||||
# et donnent leur propre clé d'API (créée dans Immich, Paramètres > Clés d'API) ; la
|
||||
# clé est chiffrée en base. L'adresse n'est jamais montrée aux administrateurs : seul
|
||||
# le libellé l'est. Sans cette liste, la fonction reste éteinte, et une adresse retirée
|
||||
# de la liste coupe aussitôt les arbres qui l'utilisent.
|
||||
# IMMICH_ALLOWED_API_URLS=Maison=http://immich.maison.lan:2283,https://immich.example.org
|
||||
|
||||
# ── Images ────────────────────────────────────────────────────────────────────
|
||||
# Version des images ghcr.io/iliesallali/parenthese-api et parenthese-web : latest (dernière
|
||||
# version de main), ou une version figée, par exemple 1.0.
|
||||
|
||||
@@ -6,3 +6,8 @@ JWT_EXPIRES_IN="7d"
|
||||
JWT_TREE_ACCESS_EXPIRES_IN="24h"
|
||||
CORS_ORIGIN="http://localhost:5173,http://localhost:5174,http://localhost:5175,http://localhost:5176"
|
||||
MEDIA_STORAGE_PATH="./storage/media"
|
||||
# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des
|
||||
# virgules. Entrée « Libellé=https://adresse » ou « https://adresse » (nom d'hôte comme libellé,
|
||||
# donc un libellé si deux instances partagent un nom). Les administrateurs de chaque arbre choisissent
|
||||
# l'instance par son nom et donnent leur propre clé d'API. Sans cette liste, la fonction reste éteinte.
|
||||
IMMICH_ALLOWED_API_URLS=""
|
||||
@@ -23,3 +23,9 @@ CORS_ORIGIN="https://arbre.example.org"
|
||||
|
||||
# Dossier des médias envoyés. Un chemin relatif part du dossier backend/.
|
||||
MEDIA_STORAGE_PATH="/var/lib/parenthese/media"
|
||||
|
||||
# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des
|
||||
# virgules. Entrée « Libellé=https://adresse » ou « https://adresse » (nom d'hôte comme libellé,
|
||||
# donc un libellé si deux instances partagent un nom). Les administrateurs de chaque arbre choisissent
|
||||
# l'instance par son nom et donnent leur propre clé d'API. Sans cette liste, la fonction reste éteinte.
|
||||
IMMICH_ALLOWED_API_URLS=""
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Association d'une personne à une personne Immich (reconnaissance des visages).
|
||||
ALTER TABLE "persons" ADD COLUMN "immichPersonId" TEXT;
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Connexion Immich propre à chaque arbre : adresse de l'instance et clé d'API chiffrée.
|
||||
-- Aucune ligne n'est créée pour les arbres existants : ils restent sans accès Immich
|
||||
-- jusqu'à ce que leurs administrateurs configurent la connexion.
|
||||
CREATE TABLE "tree_immich_configs" (
|
||||
"treeId" TEXT NOT NULL,
|
||||
"apiUrl" TEXT NOT NULL,
|
||||
"apiKeyEnc" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
CONSTRAINT "tree_immich_configs_pkey" PRIMARY KEY ("treeId")
|
||||
);
|
||||
|
||||
ALTER TABLE "tree_immich_configs" ADD CONSTRAINT "tree_immich_configs_treeId_fkey"
|
||||
FOREIGN KEY ("treeId") REFERENCES "trees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -114,6 +114,7 @@ model Tree {
|
||||
memberships TreeMembership[]
|
||||
sharedUserAccesses UserTreeAccess[]
|
||||
settings TreeSettings?
|
||||
immichConfig TreeImmichConfig?
|
||||
persons Person[]
|
||||
unions Union[]
|
||||
parentChildLinks ParentChildLink[]
|
||||
@@ -190,6 +191,19 @@ model TreeSettings {
|
||||
@@map("tree_settings")
|
||||
}
|
||||
|
||||
// Connexion Immich propre à chaque arbre (reconnaissance des visages) : l'adresse et la clé de
|
||||
// l'instance sont choisies par ses administrateurs, jamais héritées du serveur. La clé est
|
||||
// chiffrée au repos ; une ligne absente signifie « aucun accès Immich » pour cet arbre.
|
||||
model TreeImmichConfig {
|
||||
treeId String @id
|
||||
apiUrl String
|
||||
apiKeyEnc String
|
||||
updatedAt DateTime @updatedAt
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("tree_immich_configs")
|
||||
}
|
||||
|
||||
model Person {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
@@ -208,6 +222,8 @@ model Person {
|
||||
notes String?
|
||||
createdBy String?
|
||||
updatedBy String?
|
||||
// Personne Immich associée (reconnaissance des visages) : identifiant côté Immich, ou null.
|
||||
immichPersonId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
|
||||
@@ -10,6 +10,7 @@ import { isUserTokenRevoked } from './lib/token-revocation.js'
|
||||
import { authRoutes } from './routes/auth.js'
|
||||
import { contributionRoutes } from './routes/contributions.js'
|
||||
import { graphRoutes } from './routes/graph.js'
|
||||
import { immichRoutes } from './routes/immich.js'
|
||||
import { mediaRoutes } from './routes/media.js'
|
||||
import { publicRoutes } from './routes/public.js'
|
||||
import { annotationRoutes } from './routes/annotations.js'
|
||||
@@ -147,6 +148,7 @@ export function createApp() {
|
||||
app.register(annotationRoutes)
|
||||
app.register(gedcomRoutes)
|
||||
app.register(visitRoutes)
|
||||
app.register(immichRoutes)
|
||||
|
||||
app.setErrorHandler((error: FastifyError | Error, request, reply) => {
|
||||
if (error instanceof Prisma.PrismaClientInitializationError) {
|
||||
|
||||
@@ -50,6 +50,10 @@ const envSchema = z.object({
|
||||
// Place disque par arbre, et part réservée aux envois de la famille en attente de relecture
|
||||
MEDIA_QUOTA_PER_TREE_MB: z.coerce.number().int().positive().default(5120),
|
||||
MEDIA_PENDING_QUOTA_PER_TREE_MB: z.coerce.number().int().positive().default(500),
|
||||
// Instances Immich autorisées sur ce serveur, séparées par des virgules. Les administrateurs
|
||||
// d'un arbre choisissent leur connexion parmi cette liste : sans elle, la reconnaissance
|
||||
// des visages reste éteinte et le serveur ne peut pas servir de proxy vers un service interne.
|
||||
IMMICH_ALLOWED_API_URLS: z.string().default(''),
|
||||
})
|
||||
|
||||
export const env = envSchema.parse(process.env)
|
||||
|
||||
@@ -32,7 +32,7 @@ export async function softDeletePersonCascade(
|
||||
|
||||
await db.person.updateMany({
|
||||
where: { id: personId, treeId, deletedAt: null },
|
||||
data: { deletedAt: now, updatedBy: actorUserId, avatarPath: null, avatarMimeType: null },
|
||||
data: { deletedAt: now, updatedBy: actorUserId, avatarPath: null, avatarMimeType: null, immichPersonId: null },
|
||||
})
|
||||
|
||||
const unions = await db.union.findMany({
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
// Clé d'API Immich d'un arbre : secrète au repos, jamais renvoyée au front ni écrite dans les
|
||||
// journaux. Même mécanisme que le mot de passe de partage (share-password.ts) : AES-256-GCM,
|
||||
// clé dérivée de JWT_SECRET. Changer ce secret rend les clés illisibles ; chaque arbre
|
||||
// repasse alors en « à configurer », sans rien casser d'autre.
|
||||
const VERSION = 'v1'
|
||||
|
||||
function getKey(): Buffer {
|
||||
return Buffer.from(hkdfSync('sha256', env.JWT_SECRET, 'parenthese', 'immich-api-key-v1', 32))
|
||||
}
|
||||
|
||||
export function encryptImmichApiKey(value: string): string {
|
||||
const iv = randomBytes(12)
|
||||
const cipher = createCipheriv('aes-256-gcm', getKey(), iv)
|
||||
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()])
|
||||
const tag = cipher.getAuthTag()
|
||||
return `${VERSION}:${Buffer.concat([iv, tag, encrypted]).toString('base64')}`
|
||||
}
|
||||
|
||||
// null si la valeur stockée est absente, d'un autre format, ou illisible (JWT_SECRET changé).
|
||||
export function decryptImmichApiKey(stored: string | null | undefined): string | null {
|
||||
if (!stored || !stored.startsWith(`${VERSION}:`)) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = Buffer.from(stored.slice(VERSION.length + 1), 'base64')
|
||||
const decipher = createDecipheriv('aes-256-gcm', getKey(), raw.subarray(0, 12))
|
||||
decipher.setAuthTag(raw.subarray(12, 28))
|
||||
return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
import type { PrismaClient } from '@prisma/client'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
import { decryptImmichApiKey } from './immich-secret.js'
|
||||
|
||||
// Client Immich : la reconnaissance des visages lit les personnes et leurs vignettes.
|
||||
// Contrat vérifié sur la spécification OpenAPI officielle d'Immich v3.1.0 :
|
||||
// GET /api/server/ping -> 200 {"res":"pong"}
|
||||
// GET /api/people?page=N&size=M -> 200 { people: PersonResponseDto[], total, hasNextPage, hidden } (size <= 1000)
|
||||
// GET /api/people/{id} -> 200 PersonResponseDto | 404 (id : UUID v4)
|
||||
// GET /api/people/{id}/thumbnail -> 200 image binaire | 404
|
||||
// Authentification : en-tête x-api-key ; clé refusée -> 401.
|
||||
|
||||
// Instance injoignable : réseau coupé, délai dépassé, réponse illisible.
|
||||
export class ImmichUnavailableError extends Error {
|
||||
constructor(message = 'Immich est injoignable') {
|
||||
super(message)
|
||||
this.name = 'ImmichUnavailableError'
|
||||
}
|
||||
}
|
||||
|
||||
// Clé d'API refusée par Immich (401/403).
|
||||
export class ImmichAuthError extends Error {
|
||||
constructor(message = 'Clé d’API Immich refusée') {
|
||||
super(message)
|
||||
this.name = 'ImmichAuthError'
|
||||
}
|
||||
}
|
||||
|
||||
// Personne ou vignette inexistante côté Immich (404).
|
||||
export class ImmichNotFoundError extends Error {
|
||||
constructor(message = 'Personne Immich introuvable') {
|
||||
super(message)
|
||||
this.name = 'ImmichNotFoundError'
|
||||
}
|
||||
}
|
||||
|
||||
const IMMICH_PEOPLE_PAGE_SIZE = 1000
|
||||
const IMMICH_TIMEOUT_MS = 10_000
|
||||
// Délai global de la liste complète : chaque page a son propre délai, la liste entière aussi.
|
||||
const IMMICH_LIST_DEADLINE_MS = 30_000
|
||||
|
||||
// Identifiants de personnes Immich : UUID v4 (spécification OpenAPI).
|
||||
const IMMICH_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
||||
|
||||
export function isImmichPersonId(value: string): boolean {
|
||||
return IMMICH_ID_RE.test(value)
|
||||
}
|
||||
|
||||
export type ImmichPersonSummary = {
|
||||
id: string
|
||||
name: string
|
||||
hasThumbnail: boolean
|
||||
}
|
||||
|
||||
type ImmichPeoplePage = {
|
||||
people?: unknown
|
||||
hasNextPage?: unknown
|
||||
}
|
||||
|
||||
export class ImmichClient {
|
||||
private readonly apiUrl: string
|
||||
private readonly apiKey: string
|
||||
|
||||
constructor(apiUrl: string, apiKey: string) {
|
||||
this.apiUrl = apiUrl.replace(/\/$/, '')
|
||||
this.apiKey = apiKey
|
||||
}
|
||||
|
||||
// Le chemin de l'instance (ex. /immich) reste devant les chemins de l'API : on concatène,
|
||||
// on ne résout pas une URL relative (qui effacerait ce chemin).
|
||||
// Corps JSON lu hors de toute gestion d'erreur : un corps illisible est une instance
|
||||
// défaillante (503), pas une erreur serveur.
|
||||
private async readJson(response: Response): Promise<unknown> {
|
||||
try {
|
||||
return await response.json()
|
||||
} catch {
|
||||
throw new ImmichUnavailableError('Réponse Immich illisible')
|
||||
}
|
||||
}
|
||||
|
||||
private buildUrl(path: string): string {
|
||||
return `${this.apiUrl}${path}`
|
||||
}
|
||||
|
||||
private async fetch(path: string): Promise<Response> {
|
||||
const url = this.buildUrl(path)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
headers: { 'x-api-key': this.apiKey, Accept: 'application/json' },
|
||||
signal: AbortSignal.timeout(IMMICH_TIMEOUT_MS),
|
||||
// Aucune redirection suivie : la clé ne doit jamais partir vers une autre adresse.
|
||||
redirect: 'error',
|
||||
})
|
||||
} catch (error) {
|
||||
// L'URL ne contient aucun secret ; la clé voyage dans l'en-tête, jamais dans les journaux.
|
||||
console.warn(`Immich injoignable : ${url} (${(error as Error).message})`)
|
||||
throw new ImmichUnavailableError()
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
return response
|
||||
}
|
||||
|
||||
// Journal avec le statut et l'URL (sans secret), puis remontée d'une erreur distincte par cause.
|
||||
console.warn(`Immich a répondu ${response.status} sur ${url}`)
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new ImmichAuthError()
|
||||
}
|
||||
if (response.status === 404) {
|
||||
throw new ImmichNotFoundError()
|
||||
}
|
||||
throw new ImmichUnavailableError(`Immich a répondu ${response.status}`)
|
||||
}
|
||||
|
||||
async ping(): Promise<boolean> {
|
||||
try {
|
||||
const response = await this.fetch('/api/server/ping')
|
||||
const payload = (await response.json()) as { res?: unknown }
|
||||
return payload?.res === 'pong'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Toutes les personnes (sans les masquées), en suivant la pagination d'Immich.
|
||||
async listPeople(): Promise<ImmichPersonSummary[]> {
|
||||
const people: ImmichPersonSummary[] = []
|
||||
let page = 1
|
||||
|
||||
const deadline = Date.now() + IMMICH_LIST_DEADLINE_MS
|
||||
// Garde-fou : une instance qui répondrait toujours hasNextPage ne doit pas nous faire boucler.
|
||||
for (let guard = 0; guard < 1000; guard += 1, page += 1) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new ImmichUnavailableError('Liste des personnes Immich trop longue')
|
||||
}
|
||||
const response = await this.fetch(`/api/people?page=${page}&size=${IMMICH_PEOPLE_PAGE_SIZE}`)
|
||||
const payload = (await this.readJson(response)) as ImmichPeoplePage
|
||||
|
||||
if (!Array.isArray(payload.people)) {
|
||||
throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people')
|
||||
}
|
||||
|
||||
for (const person of payload.people as Array<{ id?: unknown; name?: unknown; thumbnailPath?: unknown }>) {
|
||||
if (typeof person?.id !== 'string' || typeof person?.name !== 'string') {
|
||||
throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people')
|
||||
}
|
||||
people.push({ id: person.id, name: person.name, hasThumbnail: typeof person.thumbnailPath === 'string' && person.thumbnailPath.length > 0 })
|
||||
}
|
||||
|
||||
if (payload.hasNextPage !== true || (payload.people as unknown[]).length === 0) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return people
|
||||
}
|
||||
|
||||
// Une personne précise : 200 avec ses données, 404 si elle n'existe pas. Le 404 de la
|
||||
// vignette ne prouve rien (personne absente ou simple vignette manquante), l'existence
|
||||
// se vérifie donc ici.
|
||||
async getPerson(personId: string): Promise<ImmichPersonSummary> {
|
||||
const response = await this.fetch(`/api/people/${encodeURIComponent(personId)}`)
|
||||
const person = (await this.readJson(response)) as { id?: unknown; name?: unknown; thumbnailPath?: unknown }
|
||||
if (typeof person?.id !== 'string' || typeof person?.name !== 'string') {
|
||||
throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people/{id}')
|
||||
}
|
||||
return {
|
||||
id: person.id,
|
||||
name: person.name,
|
||||
hasThumbnail: typeof person.thumbnailPath === 'string' && person.thumbnailPath.length > 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Vignette d'une personne, en octets bruts (JPEG côté Immich). Absente -> ImmichNotFoundError.
|
||||
// Lue en flux : au-delà de maxBytes, la lecture s'arrête et renvoie null sans charger le reste.
|
||||
async getPersonThumbnail(personId: string, maxBytes: number): Promise<Buffer | null> {
|
||||
const response = await this.fetch(`/api/people/${encodeURIComponent(personId)}/thumbnail`)
|
||||
const declared = Number(response.headers.get('content-length'))
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
await response.body?.cancel().catch(() => {})
|
||||
return null
|
||||
}
|
||||
if (!response.body) {
|
||||
return Buffer.alloc(0)
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const chunks: Buffer[] = []
|
||||
let total = 0
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
total += value.byteLength
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => {})
|
||||
return null
|
||||
}
|
||||
chunks.push(Buffer.from(value))
|
||||
}
|
||||
} catch {
|
||||
throw new ImmichUnavailableError('Lecture de la vignette Immich interrompue')
|
||||
}
|
||||
return Buffer.concat(chunks, total)
|
||||
}
|
||||
}
|
||||
|
||||
// Instance Immich normalisée pour comparaison : origine + chemin, sans slash final. Null si l'URL
|
||||
// est mal formée ou d'un autre protocole que http(s).
|
||||
export function normalizeImmichApiUrl(value: string): string | null {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
return null
|
||||
}
|
||||
// Ni identifiants, ni requête, ni fragment : une adresse d'instance n'en porte pas, et
|
||||
// « https://instance@autre-hote » ne doit jamais passer pour l'instance.
|
||||
if (url.username || url.password || url.search || url.hash) {
|
||||
return null
|
||||
}
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export type ImmichInstance = {
|
||||
// Identifiant opaque, dérivé de l'adresse (stable même si l'opérateur réordonne la liste).
|
||||
id: string
|
||||
label: string
|
||||
apiUrl: string
|
||||
}
|
||||
|
||||
let instancesCache: ImmichInstance[] | undefined
|
||||
|
||||
export function immichInstanceId(apiUrl: string): string {
|
||||
return createHash('sha256').update(apiUrl).digest('hex').slice(0, 16)
|
||||
}
|
||||
|
||||
// Instances Immich autorisées par l'opérateur du serveur (IMMICH_ALLOWED_API_URLS). C'est la seule
|
||||
// liste d'adresses possibles : les administrateurs d'un arbre y choisissent la leur, le serveur
|
||||
// ne devient jamais un proxy vers un service interne choisi librement. Format d'une entrée :
|
||||
// « Libellé=https://adresse » ou « https://adresse ». Sans libellé, le nom d'hôte sert de nom.
|
||||
// Entrées invalides, doublons et libellés en conflit sont ignorés avec un avertissement.
|
||||
export function getImmichInstances(): ImmichInstance[] {
|
||||
if (instancesCache !== undefined) {
|
||||
return instancesCache
|
||||
}
|
||||
|
||||
const instances: ImmichInstance[] = []
|
||||
for (const entry of env.IMMICH_ALLOWED_API_URLS.split(',')) {
|
||||
const trimmed = entry.trim()
|
||||
if (!trimmed) {
|
||||
continue
|
||||
}
|
||||
const named = /^(.*?)\s*=\s*(https?:\/\/.+)$/i.exec(trimmed)
|
||||
const rawUrl = named ? named[2] : trimmed
|
||||
const apiUrl = normalizeImmichApiUrl(rawUrl)
|
||||
if (!apiUrl) {
|
||||
console.warn(`IMMICH_ALLOWED_API_URLS : entrée ignorée (URL http(s) invalide) : ${trimmed}`)
|
||||
continue
|
||||
}
|
||||
if (instances.some((instance) => instance.apiUrl === apiUrl)) {
|
||||
continue
|
||||
}
|
||||
const label = (named?.[1] ?? '').trim() || new URL(apiUrl).hostname
|
||||
if (instances.some((instance) => instance.label.toLowerCase() === label.toLowerCase())) {
|
||||
console.warn(`IMMICH_ALLOWED_API_URLS : entrée ignorée, le nom « ${label} » est déjà pris : donnez-lui un libellé (Libellé=https://…)`)
|
||||
continue
|
||||
}
|
||||
instances.push({ id: immichInstanceId(apiUrl), label, apiUrl })
|
||||
}
|
||||
instancesCache = instances
|
||||
return instances
|
||||
}
|
||||
|
||||
export function getImmichInstanceByApiUrl(value: string): ImmichInstance | undefined {
|
||||
const normalized = normalizeImmichApiUrl(value)
|
||||
return normalized === null ? undefined : getImmichInstances().find((instance) => instance.apiUrl === normalized)
|
||||
}
|
||||
|
||||
export function isImmichApiUrlAllowed(value: string): boolean {
|
||||
return getImmichInstanceByApiUrl(value) !== undefined
|
||||
}
|
||||
|
||||
// Connexion Immich d'un arbre : résolue par arbre, côté serveur, à chaque requête. Pas de client
|
||||
// global qui garderait les identifiants d'un arbre et pourrait servir un autre ; pas d'héritage
|
||||
// de configuration du serveur. Une clé illisible (JWT_SECRET changé) vaut « non configuré », et
|
||||
// une adresse retirée de la liste de l'opérateur aussi : la connexion existante cesse de marcher.
|
||||
export async function getTreeImmichClient(prisma: PrismaClient, treeId: string): Promise<ImmichClient | null> {
|
||||
const config = await prisma.treeImmichConfig.findUnique({
|
||||
where: { treeId },
|
||||
select: { apiUrl: true, apiKeyEnc: true },
|
||||
})
|
||||
if (!config) {
|
||||
return null
|
||||
}
|
||||
|
||||
const apiKey = decryptImmichApiKey(config.apiKeyEnc)
|
||||
if (!apiKey) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!isImmichApiUrlAllowed(config.apiUrl)) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Le client reçoit l'adresse autorisée, normalisée : pas celle, brute, de la base.
|
||||
return new ImmichClient(getImmichInstanceByApiUrl(config.apiUrl)!.apiUrl, apiKey)
|
||||
}
|
||||
@@ -211,6 +211,12 @@ export function applyMediaResponseHeaders(reply: FastifyReply, storedMimeType: s
|
||||
reply.header('Content-Disposition', `attachment; filename="${safeName}"`)
|
||||
}
|
||||
|
||||
// Portrait venu d'une association Immich : son fichier porte le préfixe « immich- ». Le graphe
|
||||
// ne publie jamais l'identifiant Immich, seulement cette origine du portrait.
|
||||
export function isImmichAvatarPath(avatarPath: string | null | undefined): boolean {
|
||||
return avatarPath != null && path.basename(avatarPath).startsWith('immich-')
|
||||
}
|
||||
|
||||
// Efface un fichier du stockage, sans jamais sortir du dossier racine
|
||||
export async function removeStoredFile(storageRoot: string, relativePath: string | null | undefined): Promise<void> {
|
||||
if (!relativePath || /^https?:\/\//.test(relativePath)) return
|
||||
|
||||
@@ -0,0 +1,587 @@
|
||||
import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import path from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import { z } from 'zod'
|
||||
|
||||
import {
|
||||
getImmichInstanceByApiUrl,
|
||||
getImmichInstances,
|
||||
getTreeImmichClient,
|
||||
isImmichPersonId,
|
||||
normalizeImmichApiUrl,
|
||||
ImmichAuthError,
|
||||
ImmichNotFoundError,
|
||||
ImmichUnavailableError,
|
||||
type ImmichPersonSummary,
|
||||
} from '../lib/immich.js'
|
||||
import { decryptImmichApiKey, encryptImmichApiKey } from '../lib/immich-secret.js'
|
||||
import { InvalidMediaError, isImmichAvatarPath, removeStoredFile, sniffMimeType } from '../lib/media-files.js'
|
||||
import { exceedsStorageQuota, getStorageRoot, prepareUploadedFile, requireAdminMembership } from './media.js'
|
||||
|
||||
// Reconnaissance des visages : associer une personne de l'arbre à une personne Immich, dont la
|
||||
// vignette devient son portrait. Chaque arbre porte sa propre connexion Immich : une adresse
|
||||
// choisie parmi celles autorisées par l'opérateur du serveur (IMMICH_ALLOWED_API_URLS), et une
|
||||
// clé chiffrée en base. Toutes les routes sont rattachées à un arbre, réservées à ses
|
||||
// administrateurs, et ne parlent jamais à l'instance d'un autre arbre.
|
||||
|
||||
const treeParamSchema = z.object({ id: z.string().min(1) })
|
||||
const treePersonParamsSchema = z.object({ id: z.string().min(1), personId: z.string().min(1) })
|
||||
|
||||
const assignSchema = z.object({
|
||||
personId: z.string().min(1),
|
||||
immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'),
|
||||
// Remplacer un portrait déjà en place demande un accord explicite, quelle que soit son
|
||||
// origine (posé à la main ou venu d'une association Immich précédente).
|
||||
replaceAvatar: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const unassignSchema = z.object({
|
||||
personId: z.string().min(1),
|
||||
})
|
||||
|
||||
const thumbnailParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'),
|
||||
})
|
||||
|
||||
// Connexion Immich d'un arbre : instance choisie parmi celles autorisées par l'opérateur du
|
||||
// serveur (IMMICH_ALLOWED_API_URLS), désignée par son identifiant opaque. L'adresse ne circule
|
||||
// jamais vers le front. La clé se joint à la mise à jour ou, si le champ reste vide, celle en
|
||||
// place est conservée — jamais relue par le front.
|
||||
const configPayloadSchema = z.object({
|
||||
instanceId: z.string().regex(/^[0-9a-f]{16}$/, 'invalid_instance_id'),
|
||||
apiKey: z.string().min(1).max(512).optional(),
|
||||
})
|
||||
|
||||
const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024
|
||||
|
||||
function replyImmichError(request: FastifyRequest, reply: FastifyReply, error: unknown): FastifyReply {
|
||||
if (error instanceof ImmichNotFoundError) {
|
||||
return reply.code(404).send({ error: 'immich_person_not_found' })
|
||||
}
|
||||
if (error instanceof ImmichAuthError) {
|
||||
return reply.code(502).send({ error: 'immich_auth_failed' })
|
||||
}
|
||||
if (error instanceof ImmichUnavailableError) {
|
||||
return reply.code(503).send({ error: 'immich_unreachable' })
|
||||
}
|
||||
request.log.error({ err: error }, 'Erreur inattendue pendant un appel à Immich')
|
||||
return reply.code(500).send({ error: 'immich_api_error' })
|
||||
}
|
||||
|
||||
// Métadonnées sûres d'une connexion Immich d'arbre : jamais la clé, jamais son chiffré, jamais
|
||||
// l'adresse (l'instance se nomme par son libellé). Une adresse sortie de la liste de l'opérateur
|
||||
// vaut « non configuré » : la connexion est inerte. Une clé qui ne se déchiffre plus (JWT_SECRET
|
||||
// changé) vaut aussi « non configuré », avec keyNeedsReentry : l'administrateur doit la ressaisir.
|
||||
function immichConfigSummary(config: { apiUrl: string; apiKeyEnc: string; updatedAt: Date } | null) {
|
||||
const instance = config ? getImmichInstanceByApiUrl(config.apiUrl) : undefined
|
||||
if (!config || !instance) {
|
||||
return { configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null }
|
||||
}
|
||||
const keyReadable = decryptImmichApiKey(config.apiKeyEnc) !== null
|
||||
return {
|
||||
configured: keyReadable,
|
||||
keyNeedsReentry: !keyReadable,
|
||||
instanceId: instance.id,
|
||||
label: instance.label,
|
||||
updatedAt: config.updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// Portraits venus d'Immich : même nommage que les envois manuels (« avatar-<uuid> »), avec le
|
||||
// préfixe « immich- » qui dit au désassignement que le fichier nous appartient. Un portrait
|
||||
// envoyé à la main n'est jamais touché par le désassignement.
|
||||
function buildAvatarRelativePath(treeId: string, personId: string, extension: string): string {
|
||||
return path.posix.join(treeId, personId, `immich-${randomUUID()}${extension}`)
|
||||
}
|
||||
|
||||
export const immichRoutes: FastifyPluginAsync = async (app) => {
|
||||
// ── Connexion Immich de l'arbre : lecture, écriture, suppression. Réservées aux
|
||||
// administrateurs de l'arbre ; la clé d'API ne quitte jamais le serveur.
|
||||
|
||||
app.get('/trees/:id/immich/config', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const config = await app.prisma.treeImmichConfig.findUnique({
|
||||
where: { treeId: params.data.id },
|
||||
select: { apiUrl: true, apiKeyEnc: true, updatedAt: true },
|
||||
})
|
||||
|
||||
return reply.send({
|
||||
config: immichConfigSummary(config),
|
||||
// Les administrateurs choisissent parmi ces instances : le front en fait un menu, pas un champ libre.
|
||||
instances: getImmichInstances().map(({ id, label }) => ({ id, label })),
|
||||
})
|
||||
})
|
||||
|
||||
app.put('/trees/:id/immich/config', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
const payload = configPayloadSchema.safeParse(request.body)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
if (!payload.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
// L'instance doit faire partie de la liste de l'opérateur : le serveur ne devient jamais
|
||||
// un proxy vers un service interne choisi librement (SSRF). L'adresse vient de la liste,
|
||||
// jamais de la requête.
|
||||
const instance = getImmichInstances().find((candidate) => candidate.id === payload.data.instanceId)
|
||||
if (!instance) {
|
||||
return reply.code(400).send({ error: 'instance_not_allowed' })
|
||||
}
|
||||
|
||||
const treeId = params.data.id
|
||||
const existing = await app.prisma.treeImmichConfig.findUnique({
|
||||
where: { treeId },
|
||||
select: { apiUrl: true, apiKeyEnc: true },
|
||||
})
|
||||
|
||||
// Sans nouvelle clé, la clé en place est conservée — mais il en faut une pour une
|
||||
// première configuration, et quand celle en place ne se déchiffre plus : on ne devine
|
||||
// jamais d'identifiants ailleurs.
|
||||
if (!payload.data.apiKey && (!existing || !decryptImmichApiKey(existing.apiKeyEnc))) {
|
||||
return reply.code(400).send({ error: 'api_key_required' })
|
||||
}
|
||||
|
||||
// Changer d'instance n'emmène jamais la clé de l'ancienne : elle ne vaut rien pour la
|
||||
// nouvelle, et on ne l'envoie pas à un serveur qui n'est pas le sien.
|
||||
if (existing && !payload.data.apiKey
|
||||
&& normalizeImmichApiUrl(existing.apiUrl) !== instance.apiUrl) {
|
||||
return reply.code(400).send({ error: 'api_key_required' })
|
||||
}
|
||||
|
||||
const apiKeyEnc = payload.data.apiKey
|
||||
? encryptImmichApiKey(payload.data.apiKey)
|
||||
: existing!.apiKeyEnc
|
||||
|
||||
const config = await app.prisma.treeImmichConfig.upsert({
|
||||
where: { treeId },
|
||||
create: { treeId, apiUrl: instance.apiUrl, apiKeyEnc },
|
||||
update: { apiUrl: instance.apiUrl, apiKeyEnc },
|
||||
select: { apiUrl: true, apiKeyEnc: true, updatedAt: true },
|
||||
})
|
||||
|
||||
// Journal d'audit : jamais la clé, seulement le fait qu'elle a changé.
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_config_updated',
|
||||
entityType: 'tree_immich_config',
|
||||
entityId: treeId,
|
||||
payloadJson: { instanceId: instance.id, apiKeyChanged: Boolean(payload.data.apiKey) },
|
||||
},
|
||||
})
|
||||
|
||||
return reply.send({ config: immichConfigSummary(config) })
|
||||
})
|
||||
|
||||
app.delete('/trees/:id/immich/config', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const treeId = params.data.id
|
||||
const removed = await app.prisma.treeImmichConfig.deleteMany({ where: { treeId } })
|
||||
|
||||
if (removed.count > 0) {
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_config_removed',
|
||||
entityType: 'tree_immich_config',
|
||||
entityId: treeId,
|
||||
payloadJson: {},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return reply.send({ config: { configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null } })
|
||||
})
|
||||
|
||||
app.get('/trees/:id/immich/status', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.send({ available: false, reason: 'not_configured' })
|
||||
}
|
||||
|
||||
const available = await client.ping()
|
||||
return reply.send({ available, reason: available ? null : 'unreachable' })
|
||||
})
|
||||
|
||||
app.get('/trees/:id/immich/people', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
}
|
||||
|
||||
try {
|
||||
const people = await client.listPeople()
|
||||
return reply.send({ people })
|
||||
} catch (error) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
})
|
||||
|
||||
// Vignette d'une personne Immich, montrée dans le sélecteur. Passée par l'API : l'adresse
|
||||
// d'Immich et sa clé ne quittent jamais le serveur.
|
||||
app.get('/trees/:id/immich/thumbnail/:immichPersonId', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = thumbnailParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_immich_person_id' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
}
|
||||
|
||||
let thumbnail: Buffer | null
|
||||
try {
|
||||
thumbnail = await client.getPersonThumbnail(params.data.immichPersonId, MAX_THUMBNAIL_BYTES)
|
||||
} catch (error) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
|
||||
// Le type se lit dans les octets, pas dans ce qu'Immich déclare : la vignette finit dans une
|
||||
// balise <img>. Vide, trop grande ou pas une image : rien à montrer.
|
||||
const mimeType = thumbnail?.length ? sniffMimeType(thumbnail, 'photo') : null
|
||||
if (!thumbnail || !mimeType?.startsWith('image/')) {
|
||||
request.log.warn('Vignette Immich vide, trop grande ou qui n’est pas une image')
|
||||
return reply.code(404).send({ error: 'thumbnail_not_found' })
|
||||
}
|
||||
|
||||
reply.header('Content-Type', mimeType)
|
||||
reply.header('X-Content-Type-Options', 'nosniff')
|
||||
reply.header('Cache-Control', 'private, max-age=3600')
|
||||
return reply.send(thumbnail)
|
||||
})
|
||||
|
||||
// Personne Immich déjà associée à une fiche, pour la marquer dans le sélecteur. Réservé aux
|
||||
// administrateurs : l'identifiant n'entre jamais dans le graphe public.
|
||||
app.get('/trees/:id/immich/links/:personId', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treePersonParamsSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: params.data.personId, treeId: params.data.id, deletedAt: null },
|
||||
select: { immichPersonId: true },
|
||||
})
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
return reply.send({ immichPersonId: person.immichPersonId })
|
||||
})
|
||||
|
||||
app.post('/trees/:id/immich/assign', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
const payload = assignSchema.safeParse(request.body)
|
||||
if (!params.success || !payload.success) {
|
||||
return reply.code(400).send({ error: payload.success ? 'invalid_params' : 'invalid_immich_person_id' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
}
|
||||
|
||||
const { personId, immichPersonId } = payload.data
|
||||
const treeId = params.data.id
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: personId, treeId, deletedAt: null },
|
||||
select: { id: true, avatarPath: true },
|
||||
})
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
// La personne Immich doit exister : le 404 de la vignette ne le prouve pas (personne
|
||||
// absente ou simple vignette manquante), on la vérifie donc explicitement. Un refus
|
||||
// d'authentification ou une erreur serveur ne sont jamais pris pour une absence.
|
||||
let immichPerson: ImmichPersonSummary
|
||||
try {
|
||||
immichPerson = await client.getPerson(immichPersonId)
|
||||
} catch (error) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
|
||||
// Vignette de la personne Immich : absente -> on associe sans toucher au portrait existant.
|
||||
// Demandée seulement si Immich en annonce une : sans vignette, l'appel est inutile.
|
||||
let thumbnail: Buffer | null = null
|
||||
if (immichPerson.hasThumbnail) {
|
||||
try {
|
||||
thumbnail = await client.getPersonThumbnail(immichPersonId, MAX_THUMBNAIL_BYTES)
|
||||
} catch (error) {
|
||||
if (!(error instanceof ImmichNotFoundError)) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
// Vignette absente : l'association se fait sans portrait.
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbnail) {
|
||||
await app.prisma.$transaction([
|
||||
app.prisma.person.update({
|
||||
where: { id: personId },
|
||||
data: { immichPersonId, updatedBy: request.actor.userId },
|
||||
}),
|
||||
app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_assign',
|
||||
entityType: 'person',
|
||||
entityId: personId,
|
||||
payloadJson: { immichPersonId, avatarUpdated: false },
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
return reply.send({ ok: true, avatarUpdated: false, immichPersonId })
|
||||
}
|
||||
|
||||
// Un portrait déjà en place ne se remplace jamais en silence : sans accord explicite,
|
||||
// l'association s'arrête avant d'écrire quoi que ce soit. Le front transforme ce refus
|
||||
// en demande de confirmation puis rejoue la requête avec replaceAvatar.
|
||||
if (person.avatarPath && !payload.data.replaceAvatar) {
|
||||
return reply.code(409).send({ error: 'avatar_exists' })
|
||||
}
|
||||
|
||||
// La vignette passe par le même traitement qu'un portrait envoyé : type lu dans les octets,
|
||||
// métadonnées retirées, quota de l'arbre respecté.
|
||||
let prepared: Awaited<ReturnType<typeof prepareUploadedFile>>
|
||||
try {
|
||||
prepared = await prepareUploadedFile(thumbnail, 'photo', `immich-${immichPersonId}.jpg`)
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidMediaError) {
|
||||
return reply.code(400).send({ error: 'invalid_avatar_image' })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
if (await exceedsStorageQuota(app, treeId, prepared.buffer.length, false)) {
|
||||
return reply.code(413).send({ error: 'storage_quota_exceeded' })
|
||||
}
|
||||
|
||||
const relativePath = buildAvatarRelativePath(treeId, personId, prepared.extension)
|
||||
const storageRoot = getStorageRoot()
|
||||
const absolutePath = path.resolve(storageRoot, relativePath)
|
||||
|
||||
// Chemin hors du stockage : refusé, jamais écrit.
|
||||
if (!absolutePath.startsWith(storageRoot + path.sep)) {
|
||||
return reply.code(400).send({ error: 'invalid_media_path' })
|
||||
}
|
||||
|
||||
// Fichier écrit avant la base : si la transaction échoue, on l'efface et rien n'a changé.
|
||||
await mkdir(path.dirname(absolutePath), { recursive: true })
|
||||
await writeFile(absolutePath, prepared.buffer)
|
||||
|
||||
try {
|
||||
await app.prisma.$transaction([
|
||||
app.prisma.person.update({
|
||||
where: { id: personId },
|
||||
data: {
|
||||
avatarPath: relativePath,
|
||||
avatarMimeType: prepared.mimeType,
|
||||
immichPersonId,
|
||||
updatedBy: request.actor.userId,
|
||||
},
|
||||
}),
|
||||
app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_assign',
|
||||
entityType: 'person',
|
||||
entityId: personId,
|
||||
payloadJson: { immichPersonId, avatarUpdated: true, avatarPath: relativePath },
|
||||
},
|
||||
}),
|
||||
])
|
||||
} catch (error) {
|
||||
await removeStoredFile(storageRoot, relativePath).catch(() => {})
|
||||
request.log.error({ err: error }, 'Échec de l’association Immich : fichier de portrait retiré, base inchangée')
|
||||
throw error
|
||||
}
|
||||
|
||||
// L'ancien portrait ne reste pas sur le disque. Un échec du nettoyage n'invalide pas
|
||||
// l'association, qui a déjà réussi : il est journalisé, rien de plus.
|
||||
if (person.avatarPath && person.avatarPath !== relativePath) {
|
||||
await removeStoredFile(storageRoot, person.avatarPath).catch((cleanupError) => {
|
||||
request.log.error(
|
||||
{ err: cleanupError, oldAvatar: person.avatarPath },
|
||||
'Ancien portrait non supprimé après une association Immich',
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
return reply.send({ ok: true, avatarUpdated: true, immichPersonId })
|
||||
})
|
||||
|
||||
app.post('/trees/:id/immich/unassign', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
const payload = unassignSchema.safeParse(request.body)
|
||||
if (!params.success || !payload.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
// Pas de garde « non configuré » ici : le retrait d'association ne parle jamais à Immich,
|
||||
// et c'est le seul moyen de nettoyer des associations passées après une déconnexion.
|
||||
const { personId } = payload.data
|
||||
const treeId = params.data.id
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: personId, treeId, deletedAt: null },
|
||||
select: { id: true, avatarPath: true, immichPersonId: true },
|
||||
})
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
// Le graphe ne dit plus qui est associé : le retrait se propose toujours côté front. Sans
|
||||
// association en place, il ne fait rien — pas d'écriture, pas d'entrée d'audit.
|
||||
if (!person.immichPersonId) {
|
||||
return reply.send({ ok: true, avatarRemoved: false })
|
||||
}
|
||||
|
||||
// Le portrait vient d'Immich uniquement si son fichier porte notre préfixe. Un portrait
|
||||
// envoyé à la main reste en place : seule l'association est retirée.
|
||||
const avatarFromImmich = isImmichAvatarPath(person.avatarPath)
|
||||
|
||||
const updateData: {
|
||||
immichPersonId: null
|
||||
updatedBy: string
|
||||
avatarPath?: null
|
||||
avatarMimeType?: null
|
||||
} = { immichPersonId: null, updatedBy: request.actor.userId }
|
||||
if (avatarFromImmich) {
|
||||
updateData.avatarPath = null
|
||||
updateData.avatarMimeType = null
|
||||
}
|
||||
|
||||
// Base d'abord, fichier ensuite : le portrait disparaît seulement une fois la base à jour.
|
||||
await app.prisma.$transaction([
|
||||
app.prisma.person.update({ where: { id: personId }, data: updateData }),
|
||||
app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_unassign',
|
||||
entityType: 'person',
|
||||
entityId: personId,
|
||||
payloadJson: { previousImmichPersonId: person.immichPersonId, avatarRemoved: avatarFromImmich },
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
if (avatarFromImmich) {
|
||||
await removeStoredFile(getStorageRoot(), person.avatarPath).catch((cleanupError) => {
|
||||
request.log.error(
|
||||
{ err: cleanupError, avatarPath: person.avatarPath },
|
||||
'Portrait Immich non supprimé après un désassignement (base à jour)',
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
return reply.send({ ok: true, avatarRemoved: avatarFromImmich })
|
||||
})
|
||||
}
|
||||
@@ -92,7 +92,8 @@ function hasAdminRight(role: MembershipRole): boolean {
|
||||
return role === 'owner' || role === 'admin'
|
||||
}
|
||||
|
||||
function getStorageRoot(): string {
|
||||
// Racine du stockage des médias : partagée avec les portraits venus d'Immich (routes/immich.ts).
|
||||
export function getStorageRoot(): string {
|
||||
return path.resolve(env.MEDIA_STORAGE_PATH)
|
||||
}
|
||||
|
||||
@@ -116,7 +117,7 @@ function normalizeOptionalText(value: string | null | undefined): string | null
|
||||
|
||||
// Fichier décodé, reconnu à ses octets et nettoyé (photos sans métadonnées, vidéos sans position).
|
||||
// Le type déclaré par le navigateur n'est plus qu'un indice pour les conteneurs ambigus.
|
||||
async function prepareUploadedFile(
|
||||
export async function prepareUploadedFile(
|
||||
buffer: Buffer,
|
||||
type: BinaryMediaType,
|
||||
fileName: string,
|
||||
@@ -167,7 +168,7 @@ async function treeDiskUsage(treeId: string): Promise<number> {
|
||||
}
|
||||
|
||||
// Place disque d'un arbre : total, et part des envois en attente de relecture (limite l'envoi en boucle)
|
||||
async function exceedsStorageQuota(app: FastifyRequest['server'], treeId: string, incomingBytes: number, isPending: boolean): Promise<boolean> {
|
||||
export async function exceedsStorageQuota(app: FastifyRequest['server'], treeId: string, incomingBytes: number, isPending: boolean): Promise<boolean> {
|
||||
const MB = 1024 * 1024
|
||||
if ((await treeDiskUsage(treeId)) + incomingBytes > env.MEDIA_QUOTA_PER_TREE_MB * MB) {
|
||||
return true
|
||||
@@ -190,7 +191,7 @@ const UPLOAD_RATE_LIMIT = { bodyLimit: UPLOAD_BODY_LIMIT, config: { rateLimit: {
|
||||
// retrouvées après un import GEDCOM), envoyées une par une. Le quota de stockage de l'arbre s'applique.
|
||||
const AVATAR_RATE_LIMIT = { bodyLimit: UPLOAD_BODY_LIMIT, config: { rateLimit: { max: 120, timeWindow: '1 minute' } } }
|
||||
|
||||
async function requireAdminMembership(app: FastifyRequest['server'], userId: string, treeId: string) {
|
||||
export async function requireAdminMembership(app: FastifyRequest['server'], userId: string, treeId: string) {
|
||||
const membership = await app.prisma.treeMembership.findUnique({
|
||||
where: {
|
||||
treeId_userId: {
|
||||
@@ -493,6 +494,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
select: {
|
||||
id: true,
|
||||
avatarPath: true,
|
||||
immichPersonId: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -553,6 +555,10 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
avatarPath: relativePath,
|
||||
avatarMimeType: prepared.mimeType,
|
||||
updatedBy: request.actor.userId,
|
||||
// Un portrait déposé à la main remplace aussi le lien Immich : sans cela, l'association
|
||||
// survivrait invisible en base (le graphe ne publie que l'origine du portrait) et ne
|
||||
// pourrait plus être retirée depuis l'interface.
|
||||
...(person.immichPersonId ? { immichPersonId: null } : {}),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -567,6 +573,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
action: 'person_avatar_updated',
|
||||
entityType: 'person',
|
||||
entityId: params.data.personId,
|
||||
...(person.immichPersonId ? { payloadJson: { immichLinkRemoved: true } } : {}),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -602,6 +609,8 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
data: {
|
||||
avatarPath: null,
|
||||
avatarMimeType: null,
|
||||
// Retirer le portrait retire aussi le lien Immich : l'association ne survit pas au portrait.
|
||||
immichPersonId: null,
|
||||
updatedBy: request.actor.userId,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Annotation, MediaItem, ParentChildLink, Person, Union } from '@prisma/client'
|
||||
|
||||
import { sanitizeAnnotationContentForRead } from '../lib/annotation-content.js'
|
||||
import { isImmichAvatarPath } from '../lib/media-files.js'
|
||||
|
||||
export type GraphPayload = {
|
||||
persons: Array<{
|
||||
@@ -17,6 +18,7 @@ export type GraphPayload = {
|
||||
avatarUrlPath: string | null
|
||||
sex: string | null
|
||||
notes: string | null
|
||||
avatarFromImmich: boolean
|
||||
}>
|
||||
unions: Array<{
|
||||
id: string
|
||||
@@ -90,6 +92,7 @@ export function buildGraphPayload(
|
||||
avatarUrlPath: person.avatarPath ? `/trees/${treeId}/persons/${person.id}/avatar` : null,
|
||||
sex: person.sex,
|
||||
notes: person.notes,
|
||||
avatarFromImmich: isImmichAvatarPath(person.avatarPath),
|
||||
})),
|
||||
unions: unions.map((union) => ({
|
||||
id: union.id,
|
||||
|
||||
@@ -18,6 +18,7 @@ describe('buildGraphPayload', () => {
|
||||
sex: null,
|
||||
notes: null,
|
||||
avatarPath: 't-1/p-2/avatar.jpg',
|
||||
immichPersonId: '123e4567-e89b-42d3-a456-426614174000',
|
||||
createdBy: null,
|
||||
updatedBy: null,
|
||||
createdAt: new Date(),
|
||||
@@ -41,6 +42,24 @@ describe('buildGraphPayload', () => {
|
||||
updatedAt: new Date(),
|
||||
deletedAt: null,
|
||||
},
|
||||
{
|
||||
id: 'p-3',
|
||||
treeId: 't-1',
|
||||
firstName: 'Paul',
|
||||
lastName: 'Durand',
|
||||
birthName: null,
|
||||
birthDate: null,
|
||||
deathDate: null,
|
||||
sex: 'male',
|
||||
notes: null,
|
||||
avatarPath: 't-1/p-3/immich-abc.jpg',
|
||||
immichPersonId: '123e4567-e89b-42d3-a456-426614174999',
|
||||
createdBy: null,
|
||||
updatedBy: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
deletedAt: null,
|
||||
},
|
||||
] as any,
|
||||
[
|
||||
{
|
||||
@@ -97,6 +116,14 @@ describe('buildGraphPayload', () => {
|
||||
expect(graph.persons[0].birthDate).toBe('1994-06-02')
|
||||
expect(graph.persons[0].birthName).toBe('Durand')
|
||||
expect(graph.persons[0].avatarUrlPath).toBe('/trees/t-1/persons/p-2/avatar')
|
||||
// L'identifiant Immich ne part jamais dans le graphe : il ne sert qu'aux administrateurs.
|
||||
// Seule l'origine du portrait (fichier préfixé « immich- ») est publiée.
|
||||
expect(graph.persons[0]).not.toHaveProperty('immichPersonId')
|
||||
expect(graph.persons[1]).not.toHaveProperty('immichPersonId')
|
||||
expect(graph.persons[2]).not.toHaveProperty('immichPersonId')
|
||||
expect(graph.persons[0].avatarFromImmich).toBe(false)
|
||||
expect(graph.persons[1].avatarFromImmich).toBe(false)
|
||||
expect(graph.persons[2].avatarFromImmich).toBe(true)
|
||||
expect(graph.persons[1].avatarUrlPath).toBeNull()
|
||||
expect(graph.unions[0].id).toBe('u-1')
|
||||
expect(graph.filiations[0].viaUnionId).toBe('u-1')
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Connexion Immich par arbre : chaque arbre porte ses identifiants en base, seuls ses
|
||||
// administrateurs les configurent, et la clé d'API ne ressort jamais du serveur.
|
||||
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
user: {
|
||||
count: vi.fn(),
|
||||
},
|
||||
person: {
|
||||
findFirst: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
treeMembership: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
treeImmichConfig: {
|
||||
findUnique: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
mediaItem: {
|
||||
aggregate: vi.fn(),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
$disconnect: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../src/lib/prisma.js', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
let createApp: () => FastifyInstance
|
||||
let encryptImmichApiKey: (value: string) => string
|
||||
let TREE_1_ENC = ''
|
||||
let TREE_2_ENC = ''
|
||||
const fetchMock = vi.fn()
|
||||
|
||||
async function createUserToken(app: FastifyInstance, userId = 'user-1'): Promise<string> {
|
||||
await app.ready()
|
||||
return (app as any).jwt.sign(
|
||||
{ kind: 'user', sub: userId, jti: randomUUID(), userId, email: 'user@example.com' },
|
||||
{ expiresIn: '1h' },
|
||||
)
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.PORT = '4000'
|
||||
process.env.DATABASE_URL = 'postgresql://postgres:postgres@localhost:5432/genealogy'
|
||||
process.env.JWT_SECRET = 'test-secret-with-sufficient-length'
|
||||
process.env.JWT_EXPIRES_IN = '7d'
|
||||
process.env.JWT_TREE_ACCESS_EXPIRES_IN = '24h'
|
||||
process.env.CORS_ORIGIN = 'http://localhost:5173'
|
||||
// Instances autorisées par l'opérateur du serveur : les administrateurs d'un arbre
|
||||
// choisissent parmi elles, jamais en champ libre.
|
||||
process.env.IMMICH_ALLOWED_API_URLS = 'http://immich-tree-1.test,http://immich-tree-2.test,Maison=http://immich.example.org:2283,http://immich.example.org,http://immich-moved.example.org'
|
||||
|
||||
// Les clés chiffrées se calculent après la mise en place de JWT_SECRET, comme en production.
|
||||
const secret = await import('../src/lib/immich-secret.js')
|
||||
encryptImmichApiKey = secret.encryptImmichApiKey
|
||||
TREE_1_ENC = encryptImmichApiKey('secret-key-tree-1')
|
||||
TREE_2_ENC = encryptImmichApiKey('secret-key-tree-2')
|
||||
|
||||
const module = await import('../src/app.js')
|
||||
createApp = module.createApp
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
prismaMock.user.count.mockResolvedValue(1)
|
||||
|
||||
// user-1 administre tree-1 ; user-2 administre tree-2. Jamais l'arbre de l'autre.
|
||||
prismaMock.treeMembership.findUnique.mockImplementation(async ({ where }: { where: { treeId_userId?: { treeId: string; userId: string } } }) => {
|
||||
const { treeId, userId } = where.treeId_userId ?? ({} as { treeId: string; userId: string })
|
||||
if (treeId === 'tree-1' && userId === 'user-1') {
|
||||
return { treeId, userId, role: 'owner', tree: { deletedAt: null } }
|
||||
}
|
||||
if (treeId === 'tree-2' && userId === 'user-2') {
|
||||
return { treeId, userId, role: 'owner', tree: { deletedAt: null } }
|
||||
}
|
||||
if (treeId === 'tree-1' && userId === 'user-member') {
|
||||
return { treeId, userId, role: 'member', tree: { deletedAt: null } }
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
prismaMock.treeImmichConfig.findUnique.mockImplementation(async ({ where }: { where: { treeId: string } }) => {
|
||||
if (where.treeId === 'tree-1') {
|
||||
return { apiUrl: 'http://immich-tree-1.test', apiKeyEnc: TREE_1_ENC, updatedAt: new Date('2026-10-01T00:00:00Z') }
|
||||
}
|
||||
if (where.treeId === 'tree-2') {
|
||||
return { apiUrl: 'http://immich-tree-2.test', apiKeyEnc: TREE_2_ENC, updatedAt: new Date('2026-10-02T00:00:00Z') }
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
prismaMock.treeImmichConfig.upsert.mockImplementation(async (args: {
|
||||
create?: { apiUrl: string }
|
||||
update?: { apiUrl: string }
|
||||
}) => ({
|
||||
apiUrl: args.create?.apiUrl ?? args.update?.apiUrl,
|
||||
apiKeyEnc: args.create?.apiKeyEnc ?? args.update?.apiKeyEnc,
|
||||
updatedAt: new Date(),
|
||||
}))
|
||||
prismaMock.treeImmichConfig.deleteMany.mockResolvedValue({ count: 1 })
|
||||
prismaMock.auditLog.create.mockResolvedValue({ id: 'audit-1' })
|
||||
|
||||
fetchMock.mockReset()
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({ res: 'pong' }), { status: 200, headers: { 'content-type': 'application/json' } }))
|
||||
})
|
||||
|
||||
describe('Immich configuration: read', () => {
|
||||
it('exposes only safe metadata, never the API key', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
const body = response.json()
|
||||
expect(body.config).toMatchObject({ configured: true, instanceId: 'c2ec51abd0edebf3', label: 'immich-tree-1.test' })
|
||||
const serialized = JSON.stringify(body)
|
||||
// Aucune adresse brute : ni l'instance, ni la liste ne laissent voir une URL.
|
||||
expect(serialized).not.toContain('http://')
|
||||
expect(serialized).not.toContain('secret-key-tree-1')
|
||||
expect(serialized).not.toContain('apiKey')
|
||||
expect(serialized).not.toContain(TREE_1_ENC)
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('asks for the key again when it no longer decrypts, instead of reporting it configured', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
// Clé chiffrée avec un autre secret (JWT_SECRET changé) : illisible.
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue({
|
||||
apiUrl: 'http://immich-tree-1.test',
|
||||
// Octets aléatoires au bon format : le déchiffrement échoue (authentification GCM).
|
||||
apiKeyEnc: `v1:${Buffer.alloc(64, 7).toString('base64')}`,
|
||||
updatedAt: new Date('2026-10-01T00:00:00Z'),
|
||||
})
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
|
||||
expect(response.json().config).toEqual({
|
||||
configured: false,
|
||||
keyNeedsReentry: true,
|
||||
instanceId: 'c2ec51abd0edebf3',
|
||||
label: 'immich-tree-1.test',
|
||||
updatedAt: '2026-10-01T00:00:00.000Z',
|
||||
})
|
||||
|
||||
// La connexion ne sert à rien tant que la clé n'est pas ressaisie.
|
||||
const status = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/status',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(status.json()).toEqual({ available: false, reason: 'not_configured' })
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses to keep an unreadable key when the address is saved again', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValueOnce({
|
||||
apiUrl: 'http://immich-tree-1.test',
|
||||
apiKeyEnc: 'v1:ce-texte-ne-se-dechiffre-pas',
|
||||
updatedAt: new Date('2026-10-01T00:00:00Z'),
|
||||
})
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: 'c2ec51abd0edebf3' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json()).toEqual({ error: 'api_key_required' })
|
||||
expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('reports a tree without a configuration row as not configured', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
|
||||
// Un arbre fraîchement créé n'a pas de ligne : rien de configuré, rien d'hérité.
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null })
|
||||
expect(response.json().instances).toEqual([
|
||||
{ id: 'c2ec51abd0edebf3', label: 'immich-tree-1.test' },
|
||||
{ id: '0715d0c35f2b0405', label: 'immich-tree-2.test' },
|
||||
{ id: '6fc8e421ad9b5371', label: 'Maison' },
|
||||
{ id: '2c47e4ca85342f88', label: 'immich.example.org' },
|
||||
{ id: '2d46a51941003fcd', label: 'immich-moved.example.org' },
|
||||
])
|
||||
expect(JSON.stringify(response.json())).not.toContain('http://')
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Immich configuration: write', () => {
|
||||
it('lets a tree administrator configure their tree, key encrypted and audited without secret', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: '6fc8e421ad9b5371', apiKey: 'my-new-key' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json().config).toMatchObject({ configured: true, instanceId: '6fc8e421ad9b5371', label: 'Maison' })
|
||||
// L'adresse stockée est celle de la liste de l'opérateur, jamais une valeur envoyée par le client.
|
||||
expect(prismaMock.treeImmichConfig.upsert.mock.calls[0][0].create.apiUrl).toBe('http://immich.example.org:2283')
|
||||
|
||||
const upsertArgs = prismaMock.treeImmichConfig.upsert.mock.calls[0][0]
|
||||
expect(upsertArgs.where).toEqual({ treeId: 'tree-1' })
|
||||
expect(upsertArgs.create.apiKeyEnc).not.toContain('my-new-key')
|
||||
expect(upsertArgs.create.apiKeyEnc).toMatch(/^v1:/)
|
||||
expect(upsertArgs.update.apiKeyEnc).toBe(upsertArgs.create.apiKeyEnc)
|
||||
|
||||
expect(prismaMock.auditLog.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
treeId: 'tree-1',
|
||||
actorType: 'user',
|
||||
actorId: 'user-1',
|
||||
action: 'immich_config_updated',
|
||||
entityType: 'tree_immich_config',
|
||||
entityId: 'tree-1',
|
||||
payloadJson: { instanceId: '6fc8e421ad9b5371', apiKeyChanged: true },
|
||||
},
|
||||
})
|
||||
|
||||
expect(JSON.stringify(response.json())).not.toContain('my-new-key')
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('keeps the existing key when the same address is saved again', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: 'c2ec51abd0edebf3' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json().config.instanceId).toBe('c2ec51abd0edebf3')
|
||||
|
||||
const upsertArgs = prismaMock.treeImmichConfig.upsert.mock.calls[0][0]
|
||||
// La clé en place est conservée telle quelle : pas de nouvelle clé, pas de déchiffrage.
|
||||
expect(upsertArgs.create.apiKeyEnc).toBe(TREE_1_ENC)
|
||||
expect(upsertArgs.update.apiKeyEnc).toBe(TREE_1_ENC)
|
||||
expect(prismaMock.auditLog.create.mock.calls[0][0].data.payloadJson).toEqual({
|
||||
instanceId: 'c2ec51abd0edebf3',
|
||||
apiKeyChanged: false,
|
||||
})
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('requires a new key when the address changes: the old key never travels', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: '2d46a51941003fcd' },
|
||||
})
|
||||
|
||||
// La clé de l'ancienne instance ne vaut rien pour la nouvelle, et ne lui est jamais
|
||||
// envoyée : il faut une nouvelle clé, rien n'est écrit sans elle.
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json()).toEqual({ error: 'api_key_required' })
|
||||
expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('requires a key for a first configuration', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: '2c47e4ca85342f88' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json()).toEqual({ error: 'api_key_required' })
|
||||
expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('rejects an identifier that is not an instance id', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: 'ftp://immich.example.org', apiKey: 'my-new-key' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json().error).toBe('invalid_payload')
|
||||
expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses non-administrators and other trees', async () => {
|
||||
const app = createApp()
|
||||
const ownerToken = await createUserToken(app)
|
||||
const memberToken = await createUserToken(app, 'user-member')
|
||||
|
||||
const member = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${memberToken}` },
|
||||
payload: { instanceId: '2c47e4ca85342f88', apiKey: 'stolen-key' },
|
||||
})
|
||||
expect(member.statusCode).toBe(403)
|
||||
|
||||
// L'administrateur de tree-1 ne touche pas la configuration de tree-2.
|
||||
const otherTree = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-2/immich/config',
|
||||
headers: { authorization: `Bearer ${ownerToken}` },
|
||||
payload: { instanceId: '2c47e4ca85342f88', apiKey: 'evil-key' },
|
||||
})
|
||||
expect(otherTree.statusCode).toBe(403)
|
||||
|
||||
const anonymous = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
payload: { instanceId: '2c47e4ca85342f88', apiKey: 'key' },
|
||||
})
|
||||
expect(anonymous.statusCode).toBe(401)
|
||||
|
||||
expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled()
|
||||
expect(prismaMock.auditLog.create).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Immich configuration: removal', () => {
|
||||
it('revokes the tree access and audits the removal', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null })
|
||||
expect(prismaMock.treeImmichConfig.deleteMany).toHaveBeenCalledWith({ where: { treeId: 'tree-1' } })
|
||||
expect(prismaMock.auditLog.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
treeId: 'tree-1',
|
||||
actorType: 'user',
|
||||
actorId: 'user-1',
|
||||
action: 'immich_config_removed',
|
||||
entityType: 'tree_immich_config',
|
||||
entityId: 'tree-1',
|
||||
payloadJson: {},
|
||||
},
|
||||
})
|
||||
|
||||
// Une fois la configuration retirée, plus aucun appel vers l'instance ne part.
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null)
|
||||
fetchMock.mockClear()
|
||||
const people = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/people',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(people.statusCode).toBe(503)
|
||||
expect(people.json()).toEqual({ error: 'immich_not_configured' })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses removal by a non-administrator or on another tree', async () => {
|
||||
const app = createApp()
|
||||
const ownerToken = await createUserToken(app)
|
||||
const memberToken = await createUserToken(app, 'user-member')
|
||||
|
||||
const member = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${memberToken}` },
|
||||
})
|
||||
expect(member.statusCode).toBe(403)
|
||||
|
||||
const otherTree = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/trees/tree-2/immich/config',
|
||||
headers: { authorization: `Bearer ${ownerToken}` },
|
||||
})
|
||||
expect(otherTree.statusCode).toBe(403)
|
||||
|
||||
expect(prismaMock.treeImmichConfig.deleteMany).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Immich credentials: tree isolation', () => {
|
||||
it('uses tree 2 credentials for tree 2 requests, never tree 1 credentials', async () => {
|
||||
const app = createApp()
|
||||
const token2 = await createUserToken(app, 'user-2')
|
||||
|
||||
fetchMock.mockImplementation(async () => new Response(JSON.stringify({ people: [], total: 0, hasNextPage: false }), { status: 200, headers: { 'content-type': 'application/json' } }))
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-2/immich/people',
|
||||
headers: { authorization: `Bearer ${token2}` },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(String(fetchMock.mock.calls[0][0])).toBe('http://immich-tree-2.test/api/people?page=1&size=1000')
|
||||
expect((fetchMock.mock.calls[0][1] as RequestInit).headers).toMatchObject({ 'x-api-key': 'secret-key-tree-2' })
|
||||
expect(prismaMock.treeImmichConfig.findUnique).toHaveBeenCalledWith({
|
||||
where: { treeId: 'tree-2' },
|
||||
select: { apiUrl: true, apiKeyEnc: true },
|
||||
})
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses tree 1 credentials to serve tree 2 requests', async () => {
|
||||
const app = createApp()
|
||||
const token1 = await createUserToken(app, 'user-1')
|
||||
|
||||
// user-1 administre tree-1 mais pas tree-2 : refus avant toute résolution de configuration.
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-2/immich/people',
|
||||
headers: { authorization: `Bearer ${token1}` },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(response.json()).toEqual({ error: 'forbidden' })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Immich configuration: operator allowlist', () => {
|
||||
it('rejects an instance outside the list and changes nothing', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: '1234567890abcdef', apiKey: 'stolen-key' },
|
||||
})
|
||||
|
||||
// Le serveur ne devient jamais un proxy vers un service interne choisi librement.
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json()).toEqual({ error: 'instance_not_allowed' })
|
||||
expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled()
|
||||
expect(prismaMock.auditLog.create).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('stores the canonical address of the instance chosen by its identifier', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: 'c2ec51abd0edebf3', apiKey: 'my-new-key' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json().config).toMatchObject({ configured: true, instanceId: 'c2ec51abd0edebf3', label: 'immich-tree-1.test' })
|
||||
expect(prismaMock.treeImmichConfig.upsert.mock.calls[0][0].create.apiUrl).toBe('http://immich-tree-1.test')
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('stops using a stored connection whose address left the list', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue({
|
||||
apiUrl: 'http://removed.example.org',
|
||||
apiKeyEnc: TREE_1_ENC,
|
||||
updatedAt: new Date('2026-10-01T00:00:00Z'),
|
||||
})
|
||||
|
||||
// La connexion stockée devient « non configurée » : l'adresse n'est plus autorisée.
|
||||
const config = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(config.statusCode).toBe(200)
|
||||
expect(config.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null })
|
||||
|
||||
const status = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/status',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(status.json()).toEqual({ available: false, reason: 'not_configured' })
|
||||
|
||||
const people = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/people',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(people.statusCode).toBe(503)
|
||||
expect(people.json()).toEqual({ error: 'immich_not_configured' })
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,174 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Arbre sans connexion Immich : aucune requête vers une instance ne doit partir, chaque route
|
||||
// qui parle à l'instance répond « non configuré » — sauf le retrait d'association, purement
|
||||
// local. Les variables d'environnement du serveur, même renseignées, ne servent plus à rien :
|
||||
// la configuration vit par arbre, en base. Fichier à part : on appelle l'application dans une
|
||||
// session de test sans configuration Immich pour tree-1.
|
||||
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
user: {
|
||||
count: vi.fn().mockResolvedValue(1),
|
||||
},
|
||||
person: {
|
||||
findFirst: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
treeMembership: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
treeImmichConfig: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
$disconnect: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../src/lib/prisma.js', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
let createApp: () => FastifyInstance
|
||||
|
||||
beforeAll(async () => {
|
||||
// Même renseignées, ces variables ne donnent accès à rien : elles ne sont plus lues.
|
||||
process.env.IMMICH_ENABLED = 'true'
|
||||
process.env.IMMICH_API_URL = 'http://immich.example.org'
|
||||
process.env.IMMICH_API_KEY = 'global-key'
|
||||
// Aucune instance autorisée : explicite, pour ne pas hériter de la liste d'un .env local.
|
||||
process.env.IMMICH_ALLOWED_API_URLS = ''
|
||||
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.PORT = '4000'
|
||||
process.env.DATABASE_URL = 'postgresql://postgres:postgres@localhost:5432/genealogy'
|
||||
process.env.JWT_SECRET = 'test-secret-with-sufficient-length'
|
||||
process.env.JWT_EXPIRES_IN = '7d'
|
||||
process.env.JWT_TREE_ACCESS_EXPIRES_IN = '24h'
|
||||
process.env.CORS_ORIGIN = 'http://localhost:5173'
|
||||
|
||||
const module = await import('../src/app.js')
|
||||
createApp = module.createApp
|
||||
})
|
||||
|
||||
describe('Immich integration: tree without configuration', () => {
|
||||
it('reports not configured, never calls Immich, and never falls back to server credentials', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
const token = (app as any).jwt.sign(
|
||||
{ kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'user@example.com' },
|
||||
{ expiresIn: '1h' },
|
||||
)
|
||||
|
||||
prismaMock.treeMembership.findUnique.mockResolvedValue({
|
||||
treeId: 'tree-1',
|
||||
userId: 'user-1',
|
||||
role: 'owner',
|
||||
tree: { deletedAt: null },
|
||||
})
|
||||
// Aucune ligne de configuration pour cet arbre : il vient d'être créé.
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null)
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const status = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/status',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(status.statusCode).toBe(200)
|
||||
expect(status.json()).toEqual({ available: false, reason: 'not_configured' })
|
||||
|
||||
const config = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(config.statusCode).toBe(200)
|
||||
expect(config.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null })
|
||||
// Aucune instance autorisée par l'opérateur : le menu des adresses est vide.
|
||||
expect(config.json().instances).toEqual([])
|
||||
|
||||
const people = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/people',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(people.statusCode).toBe(503)
|
||||
expect(people.json()).toEqual({ error: 'immich_not_configured' })
|
||||
|
||||
const thumbnail = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/trees/tree-1/immich/thumbnail/123e4567-e89b-42d3-a456-426614174000',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(thumbnail.statusCode).toBe(503)
|
||||
expect(thumbnail.json()).toEqual({ error: 'immich_not_configured' })
|
||||
|
||||
const assign = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/trees/tree-1/immich/assign',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { personId: 'person-1', immichPersonId: '123e4567-e89b-42d3-a456-426614174000' },
|
||||
})
|
||||
expect(assign.statusCode).toBe(503)
|
||||
expect(assign.json()).toEqual({ error: 'immich_not_configured' })
|
||||
|
||||
// Le retrait d'association reste possible sans connexion : il nettoie des associations
|
||||
// passées sans jamais parler à Immich.
|
||||
prismaMock.person.findFirst.mockResolvedValue({
|
||||
id: 'person-1',
|
||||
avatarPath: null,
|
||||
immichPersonId: '123e4567-e89b-42d3-a456-426614174000',
|
||||
})
|
||||
const unassign = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/trees/tree-1/immich/unassign',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { personId: 'person-1' },
|
||||
})
|
||||
expect(unassign.statusCode).toBe(200)
|
||||
expect(unassign.json()).toEqual({ ok: true, avatarRemoved: false })
|
||||
|
||||
// Un arbre sans configuration ne parle jamais à Immich, ni à celle du serveur.
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
vi.unstubAllGlobals()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses any address when the operator has authorized no instance', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
const token = (app as any).jwt.sign(
|
||||
{ kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'user@example.com' },
|
||||
{ expiresIn: '1h' },
|
||||
)
|
||||
|
||||
prismaMock.treeMembership.findUnique.mockResolvedValue({
|
||||
treeId: 'tree-1',
|
||||
userId: 'user-1',
|
||||
role: 'owner',
|
||||
tree: { deletedAt: null },
|
||||
})
|
||||
prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null)
|
||||
|
||||
// Liste vide côté opérateur : aucune adresse ne peut être configurée, la fonction reste éteinte.
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/immich/config',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { instanceId: '2c47e4ca85342f88', apiKey: 'some-key' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json()).toEqual({ error: 'instance_not_allowed' })
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
+24
-4
@@ -45,6 +45,7 @@ import {
|
||||
updatePerson,
|
||||
uploadAnnotationPhoto,
|
||||
} from './api/treeApi'
|
||||
import { getImmichErrorMessage, unassignImmichPerson } from './api/immichApi.js'
|
||||
import { useAuth } from './hooks/useAuth'
|
||||
import { useTreeAccess, getTreeTokenStorageKey, getSlugFromPathname, readTreeAccessRole, TREE_ID_FROM_ENV } from './hooks/useTreeAccess'
|
||||
import { useMediaManager } from './hooks/useMediaManager'
|
||||
@@ -1535,18 +1536,33 @@ function App() {
|
||||
}
|
||||
}, [auth.userAuth.token, tree.treeContext.accessToken, tree.treeContext.treeId, refreshTreeAndKeepSelection])
|
||||
|
||||
const handlePersonAvatarDelete = useCallback(async (personId) => {
|
||||
// Visage venu d'Immich : recharger l'arbre pour montrer le nouveau portrait (ou le portrait restant)
|
||||
const handleImmichChange = useCallback(async (personId) => {
|
||||
await refreshTreeAndKeepSelection(personId, { relayout: false, avatarCacheBust: Date.now() })
|
||||
}, [refreshTreeAndKeepSelection])
|
||||
|
||||
const handlePersonAvatarDelete = useCallback(async (personId, avatarFromImmich = false) => {
|
||||
const accessToken = tree.treeContext.accessToken || auth.userAuth.token
|
||||
if (!accessToken || !tree.treeContext.treeId) return
|
||||
|
||||
setAvatarActionState({ loading: true, error: '' })
|
||||
|
||||
try {
|
||||
await deletePersonAvatar(tree.treeContext.treeId, personId, accessToken)
|
||||
await refreshTreeAndKeepSelection(personId, { relayout: true })
|
||||
// Portrait venu d'Immich : le désassignement retire le portrait et l'association d'un
|
||||
// coup ; la suppression seule laisserait une association pendante en base.
|
||||
if (avatarFromImmich) {
|
||||
await unassignImmichPerson(tree.treeContext.treeId, personId, accessToken)
|
||||
await refreshTreeAndKeepSelection(personId, { relayout: false, avatarCacheBust: Date.now() })
|
||||
} else {
|
||||
await deletePersonAvatar(tree.treeContext.treeId, personId, accessToken)
|
||||
await refreshTreeAndKeepSelection(personId, { relayout: true })
|
||||
}
|
||||
setAvatarActionState({ loading: false, error: '' })
|
||||
} catch (error) {
|
||||
setAvatarActionState({ loading: false, error: getAccountErrorMessage(error) })
|
||||
setAvatarActionState({
|
||||
loading: false,
|
||||
error: avatarFromImmich ? getImmichErrorMessage(error, t) : getAccountErrorMessage(error),
|
||||
})
|
||||
}
|
||||
}, [auth.userAuth.token, tree.treeContext.accessToken, tree.treeContext.treeId, refreshTreeAndKeepSelection])
|
||||
|
||||
@@ -2847,6 +2863,9 @@ function App() {
|
||||
onManageMedia={media.handleOpenMediaManager}
|
||||
onAvatarUpload={tree.canEditCurrentTree ? handlePersonAvatarUpload : undefined}
|
||||
onAvatarDelete={tree.canEditCurrentTree ? handlePersonAvatarDelete : undefined}
|
||||
treeId={tree.treeContext.treeId || null}
|
||||
immichToken={tree.treeContext.accessToken || auth.userAuth.token}
|
||||
onImmichChange={tree.canEditCurrentTree ? handleImmichChange : undefined}
|
||||
avatarActionLoading={avatarActionState.loading}
|
||||
avatarActionError={avatarActionState.error}
|
||||
isAdmin={userRole.isAdmin}
|
||||
@@ -2913,6 +2932,7 @@ function App() {
|
||||
visible={adminPanelVisible}
|
||||
treeId={tree.treeContext.treeId}
|
||||
authToken={tree.treeContext.accessToken}
|
||||
isAdmin={userRole.isAdmin}
|
||||
onTreeDeleted={handleTreeDeleted}
|
||||
onGedcomImported={handleGedcomImported}
|
||||
onOpenPhotoStart={() => { setAdminPanelVisible(false); openPhotoStart() }}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { API_BASE_URL, apiRequest } from './client.js'
|
||||
|
||||
// Reconnaissance des visages : la connexion Immich est propre à chaque arbre, configurée par
|
||||
// ses administrateurs. L'adresse est choisie parmi celles autorisées par l'opérateur du
|
||||
// serveur ; la clé d'API ne quitte jamais le backend. Les erreurs distinguent non configuré /
|
||||
// injoignable / clé refusée.
|
||||
|
||||
function withAuth(options = {}, token) {
|
||||
if (!token) return options
|
||||
return { ...options, headers: { ...(options.headers || {}), Authorization: `Bearer ${token}` } }
|
||||
}
|
||||
|
||||
export function getImmichErrorMessage(error, t) {
|
||||
const code = error?.payload?.error || ''
|
||||
if (code === 'immich_not_configured') return t('Immich n’est pas configuré pour cet arbre.')
|
||||
if (code === 'immich_unreachable') return t('Immich est injoignable.')
|
||||
if (code === 'immich_auth_failed') return t('La clé d’accès à Immich a été refusée.')
|
||||
if (code === 'immich_person_not_found') return t('Personne introuvable dans Immich.')
|
||||
if (code === 'invalid_immich_person_id') return t('Identifiant Immich invalide.')
|
||||
if (code === 'invalid_avatar_image') return t('La vignette Immich n’est pas une image valide.')
|
||||
if (code === 'storage_quota_exceeded') return t('Espace disque de l’arbre dépassé.')
|
||||
if (code === 'api_key_required') return t('Indiquez la clé d’accès à Immich pour la première configuration.')
|
||||
if (code === 'instance_not_allowed') return t('Cette instance Immich n’est pas autorisée par l’opérateur du serveur.')
|
||||
if (code === 'forbidden') return t('Seuls les administrateurs de l’arbre peuvent associer un visage Immich.')
|
||||
if (error?.status === 0 || error?.message === 'Failed to fetch') return t('Immich est injoignable.')
|
||||
return error?.message || t('Erreur inattendue.')
|
||||
}
|
||||
|
||||
// Connexion Immich de l'arbre : métadonnées sûres (jamais la clé, jamais l'adresse) et instances
|
||||
// autorisées par l'opérateur, nommées par leur libellé, dont le panneau d'administration fait un menu.
|
||||
export async function fetchImmichConfig(treeId, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({}, token))
|
||||
return {
|
||||
config: data?.config || { configured: false, instanceId: null, label: null, updatedAt: null },
|
||||
instances: Array.isArray(data?.instances) ? data.instances : [],
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveImmichConfig(treeId, { instanceId, apiKey }, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ instanceId, ...(apiKey ? { apiKey } : {}) }),
|
||||
}, token))
|
||||
return data?.config || null
|
||||
}
|
||||
|
||||
export async function removeImmichConfig(treeId, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({
|
||||
method: 'DELETE',
|
||||
}, token))
|
||||
}
|
||||
|
||||
export async function checkImmichStatus(treeId, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/status`, withAuth({}, token))
|
||||
}
|
||||
|
||||
export async function listImmichPeople(treeId, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/people`, withAuth({}, token))
|
||||
return Array.isArray(data?.people) ? data.people : []
|
||||
}
|
||||
|
||||
// Personne Immich déjà associée à cette fiche (administrateurs seulement), ou null.
|
||||
export async function fetchImmichLink(treeId, personId, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/links/${encodeURIComponent(personId)}`, withAuth({}, token))
|
||||
return data?.immichPersonId || null
|
||||
}
|
||||
|
||||
export async function fetchImmichThumbnail(treeId, immichPersonId, token) {
|
||||
const path = `/trees/${encodeURIComponent(treeId)}/immich/thumbnail/${encodeURIComponent(immichPersonId)}`
|
||||
const response = await fetch(`${API_BASE_URL}${path}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`immich_thumbnail_failed_${response.status}`)
|
||||
}
|
||||
return URL.createObjectURL(await response.blob())
|
||||
}
|
||||
|
||||
export async function assignImmichPerson(treeId, personId, immichPersonId, token, { replaceAvatar = false } = {}) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/assign`, withAuth({
|
||||
method: 'POST',
|
||||
// replaceAvatar : accord explicite pour remplacer un portrait déjà en place — le serveur
|
||||
// refuse sinon (409 avatar_exists), quelle que soit l'origine du portrait actuel.
|
||||
body: JSON.stringify({ personId, immichPersonId, ...(replaceAvatar ? { replaceAvatar: true } : {}) }),
|
||||
}, token))
|
||||
}
|
||||
|
||||
export async function unassignImmichPerson(treeId, personId, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/unassign`, withAuth({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ personId }),
|
||||
}, token))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Download, ImagePlus, Trash2, X } from 'lucide-react'
|
||||
import { Download, ImagePlus, Trash2, Unplug, X } from 'lucide-react'
|
||||
import './SettingsPanels.css'
|
||||
import {
|
||||
deleteTree,
|
||||
@@ -10,6 +10,13 @@ import {
|
||||
updateTree,
|
||||
updateTreeSettings,
|
||||
} from '../api/treeApi'
|
||||
import {
|
||||
checkImmichStatus,
|
||||
fetchImmichConfig,
|
||||
getImmichErrorMessage,
|
||||
removeImmichConfig,
|
||||
saveImmichConfig,
|
||||
} from '../api/immichApi.js'
|
||||
import PzBusy from './PzBusy.jsx'
|
||||
import TreeVisitsSection from './TreeVisitsSection.jsx'
|
||||
import { t } from '../i18n/index.js'
|
||||
@@ -27,6 +34,7 @@ const AdminPanel = ({
|
||||
visible,
|
||||
treeId,
|
||||
authToken,
|
||||
isAdmin = false,
|
||||
onClose,
|
||||
onTreeDeleted,
|
||||
onGedcomImported,
|
||||
@@ -51,6 +59,15 @@ const AdminPanel = ({
|
||||
const [importingGedcom, setImportingGedcom] = useState(false)
|
||||
const gedcomInputRef = useRef(null)
|
||||
|
||||
// Connexion Immich propre à cet arbre : l'adresse se choisit parmi celles autorisées par
|
||||
// l'opérateur du serveur, la clé n'est jamais relue et le champ vide la conserve.
|
||||
const [immichConfig, setImmichConfig] = useState(null)
|
||||
const [immichInstances, setImmichInstances] = useState([])
|
||||
const [immichInstanceId, setImmichInstanceId] = useState('')
|
||||
const [immichApiKey, setImmichApiKey] = useState('')
|
||||
const [immichStatus, setImmichStatus] = useState(null) // null : inconnu, 'ok', sinon le motif
|
||||
const [immichBusy, setImmichBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible || !treeId || !authToken) {
|
||||
return
|
||||
@@ -66,6 +83,26 @@ const AdminPanel = ({
|
||||
setGedcomFile(null)
|
||||
setImportingGedcom(false)
|
||||
|
||||
setImmichConfig(null)
|
||||
setImmichInstances([])
|
||||
setImmichInstanceId('')
|
||||
setImmichApiKey('')
|
||||
setImmichStatus(null)
|
||||
// Réservé aux administrateurs de l'arbre. Le panneau attend cette réponse avant de s'afficher :
|
||||
// la section Immich n'apparaît pas après coup et la zone de suppression ne bouge pas.
|
||||
const immichLoad = isAdmin
|
||||
? fetchImmichConfig(treeId, authToken)
|
||||
.then(({ config, instances }) => {
|
||||
if (!active) return
|
||||
setImmichConfig(config)
|
||||
setImmichInstances(instances)
|
||||
setImmichInstanceId(instances.some((instance) => instance.id === config?.instanceId) ? config.instanceId : '')
|
||||
})
|
||||
.catch(() => {
|
||||
// Configuration non chargée : la section Immich reste masquée
|
||||
})
|
||||
: Promise.resolve()
|
||||
|
||||
fetchTreeSettings(treeId, authToken)
|
||||
.then((settings) => {
|
||||
if (!active || !settings) return
|
||||
@@ -75,7 +112,7 @@ const AdminPanel = ({
|
||||
// Réglage non chargé : on laisse la valeur par défaut affichée
|
||||
})
|
||||
|
||||
getTree(treeId, authToken)
|
||||
const treeLoad = getTree(treeId, authToken)
|
||||
.then((result) => {
|
||||
if (!active) return
|
||||
const loadedTree = result?.tree || null
|
||||
@@ -87,14 +124,15 @@ const AdminPanel = ({
|
||||
if (!active) return
|
||||
setErrorMessage(t('Impossible de charger les paramètres de cet arbre.'))
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false)
|
||||
})
|
||||
|
||||
Promise.all([treeLoad, immichLoad]).finally(() => {
|
||||
if (active) setLoading(false)
|
||||
})
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [visible, treeId, authToken])
|
||||
}, [visible, treeId, authToken, isAdmin])
|
||||
|
||||
const handlePolicyChange = async (nextPolicy) => {
|
||||
if (!treeId || !authToken || savingPolicy || nextPolicy === contributionPolicy) return
|
||||
@@ -253,6 +291,81 @@ const AdminPanel = ({
|
||||
}
|
||||
}
|
||||
|
||||
// ── Connexion Immich de l'arbre ──────────────────────────────────────────────
|
||||
|
||||
const testImmichConnection = async () => {
|
||||
if (!treeId || !authToken) return
|
||||
setImmichStatus('testing')
|
||||
try {
|
||||
const status = await checkImmichStatus(treeId, authToken)
|
||||
setImmichStatus(status?.available ? 'ok' : (status?.reason || 'unreachable'))
|
||||
} catch (err) {
|
||||
setImmichStatus('error')
|
||||
setErrorMessage(getImmichErrorMessage(err, t))
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveImmichConfig = async (event) => {
|
||||
event.preventDefault()
|
||||
if (!treeId || !authToken || immichBusy) return
|
||||
|
||||
const instanceId = immichInstanceId
|
||||
if (!instanceId) {
|
||||
setErrorMessage(t('Choisissez l’instance Immich.'))
|
||||
return
|
||||
}
|
||||
const apiKey = immichApiKey.trim()
|
||||
// Changer d'instance réclame une nouvelle clé : l'ancienne n'est ni conservée ni envoyée
|
||||
// au nouveau serveur.
|
||||
const changingInstance = Boolean(immichConfig?.configured && immichConfig.instanceId && immichConfig.instanceId !== instanceId)
|
||||
if (changingInstance && !apiKey) {
|
||||
setErrorMessage(t('L’instance Immich change : indiquez la clé d’accès de la nouvelle instance, l’ancienne n’est pas conservée.'))
|
||||
return
|
||||
}
|
||||
if (!immichConfig?.configured && !apiKey) {
|
||||
setErrorMessage(t('Indiquez la clé d’accès à Immich pour la première configuration.'))
|
||||
return
|
||||
}
|
||||
|
||||
setImmichBusy(true)
|
||||
setErrorMessage('')
|
||||
setSuccessMessage('')
|
||||
try {
|
||||
const config = await saveImmichConfig(treeId, { instanceId, apiKey }, authToken)
|
||||
setImmichConfig(config || { configured: true, instanceId, label: null, updatedAt: null })
|
||||
setImmichApiKey('')
|
||||
setSuccessMessage(t('Connexion Immich enregistrée.'))
|
||||
await testImmichConnection()
|
||||
} catch (err) {
|
||||
setErrorMessage(getImmichErrorMessage(err, t))
|
||||
} finally {
|
||||
setImmichBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveImmichConfig = async () => {
|
||||
if (!treeId || !authToken || immichBusy || !(immichConfig?.configured || immichConfig?.keyNeedsReentry)) return
|
||||
if (!window.confirm(t('Supprimer la connexion Immich de cet arbre ? La reconnaissance des visages sera désactivée.'))) {
|
||||
return
|
||||
}
|
||||
|
||||
setImmichBusy(true)
|
||||
setErrorMessage('')
|
||||
setSuccessMessage('')
|
||||
try {
|
||||
await removeImmichConfig(treeId, authToken)
|
||||
setImmichConfig({ configured: false, instanceId: null, label: null, updatedAt: null })
|
||||
setImmichInstanceId('')
|
||||
setImmichApiKey('')
|
||||
setImmichStatus(null)
|
||||
setSuccessMessage(t('Connexion Immich supprimée.'))
|
||||
} catch (err) {
|
||||
setErrorMessage(getImmichErrorMessage(err, t))
|
||||
} finally {
|
||||
setImmichBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!visible) return null
|
||||
|
||||
return (
|
||||
@@ -426,6 +539,92 @@ const AdminPanel = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{section === 'danger' && immichInstances.length > 0 && (
|
||||
<div className="ts-panel">
|
||||
<div className="ts-row">
|
||||
<div className="ts-row-text">
|
||||
<strong>{t('Reconnaissance des visages')}</strong>
|
||||
<p className="pz-small">{t('La connexion Immich est propre à cet arbre : ses administrateurs choisissent une instance autorisée par l’opérateur du serveur et fournissent leur propre clé d’accès.')}</p>
|
||||
<span className={`pz-tag ${immichConfig?.configured ? 'pz-tag--accent' : ''}`}>
|
||||
{immichConfig.configured
|
||||
? t('Configurée')
|
||||
: immichConfig.keyNeedsReentry
|
||||
? t('Clé à ressaisir')
|
||||
: t('Non configurée')}
|
||||
</span>
|
||||
{immichConfig?.keyNeedsReentry && (
|
||||
<span className="pz-small">
|
||||
{t('La clé enregistrée ne peut plus être lue (le secret du serveur a changé). Ressaisissez-la pour réactiver la connexion.')}
|
||||
</span>
|
||||
)}
|
||||
{immichConfig?.configured && (
|
||||
<span className="pz-small">
|
||||
{immichStatus === 'ok' && t('Instance joignable.')}
|
||||
{immichStatus === 'testing' && t('Test en cours…')}
|
||||
{immichStatus === 'not_configured' && t('Immich n’est pas configuré pour cet arbre.')}
|
||||
{immichStatus === 'unreachable' && t('Immich est injoignable.')}
|
||||
{immichStatus === 'error' && t('Test impossible.')}
|
||||
{(immichStatus === null || immichStatus === undefined) && t('Connexion non testée depuis l’ouverture.')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{immichConfig?.configured && (
|
||||
<div className="ts-row-actions">
|
||||
<button type="button" className="pz-btn pz-btn--secondary pz-btn--sm" onClick={testImmichConnection} disabled={immichBusy}>
|
||||
{t('Tester la connexion')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form className="ts-panel" onSubmit={handleSaveImmichConfig}>
|
||||
<div className="pz-field">
|
||||
<label htmlFor="immichInstance">{t('Instance Immich')}</label>
|
||||
<select
|
||||
id="immichInstance"
|
||||
value={immichInstanceId}
|
||||
onChange={(event) => setImmichInstanceId(event.target.value)}
|
||||
required
|
||||
>
|
||||
<option value="">{t('Choisir une instance…')}</option>
|
||||
{immichInstances.map((instance) => (
|
||||
<option key={instance.id} value={instance.id}>{instance.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="pz-field">
|
||||
<label htmlFor="immichApiKey">{t('Clé d’accès Immich')}</label>
|
||||
<input
|
||||
id="immichApiKey"
|
||||
type="password"
|
||||
value={immichApiKey}
|
||||
maxLength={512}
|
||||
autoComplete="new-password"
|
||||
onChange={(event) => setImmichApiKey(event.target.value)}
|
||||
placeholder={immichConfig?.configured
|
||||
? (immichConfig.instanceId && immichInstanceId !== immichConfig.instanceId
|
||||
? t('Clé d’accès de la nouvelle instance requise')
|
||||
: t('Laisser vide pour conserver la clé actuelle'))
|
||||
: t('Clé créée dans Immich (Paramètres > Clés d’API)')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="ts-actions ts-row-actions">
|
||||
<button type="submit" className="pz-btn pz-btn--primary pz-btn--sm" disabled={immichBusy}>
|
||||
<PzBusy busy={immichBusy} busyLabel={t('Enregistrement en cours')}>{t('Enregistrer')}</PzBusy>
|
||||
</button>
|
||||
{(immichConfig?.configured || immichConfig?.keyNeedsReentry) && (
|
||||
<button type="button" className="pz-btn pz-btn--danger-ghost pz-btn--sm" onClick={handleRemoveImmichConfig} disabled={immichBusy}>
|
||||
<Unplug size={15} aria-hidden="true" />
|
||||
{t('Supprimer la connexion')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{section === 'danger' && (
|
||||
<div className="ts-panel">
|
||||
<div className="ts-danger">
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/* Association d'un visage Immich : sélecteur de personne avec aperçu du portrait. La fenêtre vient de pz.css */
|
||||
.immich-modal-overlay { z-index: 2200; }
|
||||
.immich-modal-card { max-width: 520px; }
|
||||
|
||||
.immich-body { display: grid; gap: 16px; }
|
||||
|
||||
.immich-current {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--pz-a300);
|
||||
border-radius: var(--pz-r-m);
|
||||
background: var(--pz-a50);
|
||||
font: 500 13px var(--pz-sans);
|
||||
color: var(--pz-ink-2);
|
||||
}
|
||||
|
||||
.immich-search {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--pz-line);
|
||||
border-radius: var(--pz-r-m);
|
||||
background: var(--pz-surface);
|
||||
color: var(--pz-faint);
|
||||
}
|
||||
.immich-search input {
|
||||
flex: 1;
|
||||
border: none;
|
||||
background: transparent;
|
||||
font: 500 13.5px var(--pz-sans);
|
||||
color: var(--pz-ink);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.immich-list {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--pz-line);
|
||||
border-radius: var(--pz-r-m);
|
||||
padding: 6px;
|
||||
}
|
||||
.immich-person {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: calc(var(--pz-r-m) - 3px);
|
||||
background: var(--pz-surface);
|
||||
color: var(--pz-ink-2);
|
||||
font: 500 13px var(--pz-sans);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background-color 140ms ease, color 140ms ease;
|
||||
}
|
||||
.immich-person.is-active { border-color: var(--pz-a500); background: var(--pz-a50); color: var(--pz-a700); }
|
||||
.immich-person.is-linked:not(.is-active) { border-color: var(--pz-a300); }
|
||||
.immich-person-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.immich-person-tag { margin-left: auto; flex: none; }
|
||||
@media (hover: hover) and (pointer: fine) { .immich-person:hover:not(.is-active) { background: var(--pz-a50); } }
|
||||
|
||||
/* Miniature ronde d'un visage ; en attente ou sans vignette, un rond neutre avec l'icône. */
|
||||
.immich-face {
|
||||
width: 34px; height: 34px; flex: none; display: grid; place-items: center; overflow: hidden;
|
||||
border-radius: 50%; border: 1px solid var(--pz-line); background: var(--pz-bg); color: var(--pz-faint);
|
||||
}
|
||||
.immich-face img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
|
||||
/* Aperçu du visage choisi : même photo que les fiches (carré arrondi), n'apparaît qu'après un choix. */
|
||||
.immich-preview {
|
||||
display: flex; align-items: center; gap: 14px; padding: 12px 14px;
|
||||
border-radius: var(--pz-r-m); background: var(--pz-a50);
|
||||
}
|
||||
.immich-face--preview {
|
||||
width: 64px; height: 64px; border-radius: 24%; border: 0;
|
||||
background: var(--pz-a100); color: var(--pz-a700);
|
||||
box-shadow: 0 0 0 1px rgba(42, 38, 34, .06), var(--pz-shadow);
|
||||
}
|
||||
.immich-preview-name { font: 500 14px var(--pz-sans); color: var(--pz-ink-2); }
|
||||
|
||||
.immich-empty { font: 500 13px var(--pz-sans); color: var(--pz-faint); text-align: center; padding: 12px 0; }
|
||||
.immich-error { margin: 0; }
|
||||
|
||||
/* Demande de confirmation avant de remplacer un portrait déjà en place. */
|
||||
.immich-confirm {
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--pz-danger);
|
||||
border-radius: var(--pz-r-m);
|
||||
background: var(--pz-danger-bg);
|
||||
color: var(--pz-danger);
|
||||
font: 500 13px/1.5 var(--pz-sans);
|
||||
}
|
||||
.immich-spin { animation: immich-rotate 900ms linear infinite; }
|
||||
@keyframes immich-rotate { to { transform: rotate(360deg); } }
|
||||
@@ -0,0 +1,364 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Loader2, Search, Unlink, UserRound, X } from 'lucide-react'
|
||||
import { createPortal } from 'react-dom'
|
||||
|
||||
import {
|
||||
assignImmichPerson,
|
||||
checkImmichStatus,
|
||||
fetchImmichLink,
|
||||
fetchImmichThumbnail,
|
||||
getImmichErrorMessage,
|
||||
listImmichPeople,
|
||||
unassignImmichPerson,
|
||||
} from '../api/immichApi.js'
|
||||
import { t } from '../i18n/index.js'
|
||||
import PzBusy from './PzBusy.jsx'
|
||||
import './ImmichFacePanel.css'
|
||||
|
||||
// Nombre de miniatures chargées en même temps : une liste peut compter beaucoup de visages.
|
||||
const MAX_PARALLEL_THUMBNAILS = 3
|
||||
|
||||
// Miniatures du panneau : une requête par visage, mise en cache le temps du panneau. Les URL
|
||||
// blob sont révoquées au démontage. Renvoie request(immichPersonId) -> URL blob, ou null.
|
||||
function useFaceThumbnails(treeId, token) {
|
||||
const cacheRef = useRef(new Map()) // immichPersonId -> URL blob, ou null (pas de vignette)
|
||||
const inflightRef = useRef(new Map()) // immichPersonId -> promesse en attente
|
||||
const queueRef = useRef([])
|
||||
const runningRef = useRef(0)
|
||||
const mountedRef = useRef(true)
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (runningRef.current < MAX_PARALLEL_THUMBNAILS && queueRef.current.length > 0) {
|
||||
const job = queueRef.current.shift()
|
||||
runningRef.current += 1
|
||||
job().finally(() => {
|
||||
runningRef.current -= 1
|
||||
pump()
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
|
||||
const request = useCallback((immichPersonId) => {
|
||||
if (cacheRef.current.has(immichPersonId)) return Promise.resolve(cacheRef.current.get(immichPersonId))
|
||||
if (inflightRef.current.has(immichPersonId)) return inflightRef.current.get(immichPersonId)
|
||||
|
||||
const promise = new Promise((resolve) => {
|
||||
queueRef.current.push(async () => {
|
||||
let url = null
|
||||
if (mountedRef.current) {
|
||||
try {
|
||||
url = await fetchImmichThumbnail(treeId, immichPersonId, token)
|
||||
} catch {
|
||||
url = null
|
||||
}
|
||||
}
|
||||
inflightRef.current.delete(immichPersonId)
|
||||
if (!mountedRef.current) {
|
||||
if (url) URL.revokeObjectURL(url)
|
||||
resolve(null)
|
||||
return
|
||||
}
|
||||
cacheRef.current.set(immichPersonId, url)
|
||||
resolve(url)
|
||||
})
|
||||
})
|
||||
inflightRef.current.set(immichPersonId, promise)
|
||||
pump()
|
||||
return promise
|
||||
}, [treeId, token, pump])
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
const cache = cacheRef.current
|
||||
// La file et les promesses en attente ne sont pas vidées : elles se résolvent à vide dès
|
||||
// qu'elles trouvent le panneau démonté, et restent valables si le montage reprend (StrictMode).
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
cache.forEach((url) => { if (url) URL.revokeObjectURL(url) })
|
||||
cache.clear()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
// Vrai une fois l'élément affiché (ou tout de suite si eager). Sans IntersectionObserver, vrai.
|
||||
function useInView(ref, eager) {
|
||||
const [inView, setInView] = useState(eager)
|
||||
|
||||
useEffect(() => {
|
||||
if (inView) return undefined
|
||||
const element = ref.current
|
||||
if (!element) return undefined
|
||||
if (typeof IntersectionObserver === 'undefined') {
|
||||
setInView(true)
|
||||
return undefined
|
||||
}
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
setInView(true)
|
||||
observer.disconnect()
|
||||
}
|
||||
}, { rootMargin: '120px' })
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [inView, ref])
|
||||
|
||||
return inView
|
||||
}
|
||||
|
||||
// Visage d'une personne Immich : sa miniature ronde, chargée à l'affichage. En attente, ou sans
|
||||
// vignette, un rond neutre avec l'icône.
|
||||
const FaceThumb = ({ immichPersonId, hasThumbnail, request, eager = false, className = '' }) => {
|
||||
const ref = useRef(null)
|
||||
const inView = useInView(ref, eager)
|
||||
const [url, setUrl] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!inView || !hasThumbnail || !immichPersonId) return undefined
|
||||
let cancelled = false
|
||||
request(immichPersonId).then((loaded) => { if (!cancelled) setUrl(loaded) })
|
||||
return () => { cancelled = true }
|
||||
}, [inView, hasThumbnail, immichPersonId, request])
|
||||
|
||||
return (
|
||||
<span ref={ref} className={`immich-face ${className}`} aria-hidden="true">
|
||||
{url ? <img src={url} alt="" /> : <UserRound size={16} aria-hidden="true" />}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Associer une personne de l'arbre à une personne Immich : sa vignette devient le portrait.
|
||||
// Réservé aux administrateurs de l'arbre (l'API vérifie le rôle côté serveur).
|
||||
const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => {
|
||||
const [available, setAvailable] = useState(null) // null : vérification en cours
|
||||
const [unavailableReason, setUnavailableReason] = useState('')
|
||||
const [people, setPeople] = useState([])
|
||||
const [loadingPeople, setLoadingPeople] = useState(false)
|
||||
const [linkedId, setLinkedId] = useState(null) // personne Immich déjà associée à cette fiche
|
||||
const [search, setSearch] = useState('')
|
||||
const [selected, setSelected] = useState(null)
|
||||
const [actionLoading, setActionLoading] = useState(false)
|
||||
const [confirmReplace, setConfirmReplace] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const requestThumbnail = useFaceThumbnails(treeId, token)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
const status = await checkImmichStatus(treeId, token)
|
||||
if (cancelled) return
|
||||
setAvailable(Boolean(status?.available))
|
||||
setUnavailableReason(status?.available ? '' : (status?.reason || 'unreachable'))
|
||||
if (!status?.available) return
|
||||
|
||||
setLoadingPeople(true)
|
||||
const [immichPeople, link] = await Promise.all([
|
||||
listImmichPeople(treeId, token),
|
||||
fetchImmichLink(treeId, person.id, token).catch(() => null),
|
||||
])
|
||||
if (cancelled) return
|
||||
setPeople(immichPeople)
|
||||
setLinkedId(link)
|
||||
} catch (err) {
|
||||
if (cancelled) return
|
||||
setAvailable(false)
|
||||
setUnavailableReason('')
|
||||
setError(getImmichErrorMessage(err, t))
|
||||
} finally {
|
||||
if (!cancelled) setLoadingPeople(false)
|
||||
}
|
||||
}
|
||||
|
||||
load()
|
||||
return () => { cancelled = true }
|
||||
}, [treeId, token, person.id])
|
||||
|
||||
const handleSelect = useCallback((immichPerson) => {
|
||||
setSelected(immichPerson)
|
||||
setError('')
|
||||
setConfirmReplace(false)
|
||||
}, [])
|
||||
|
||||
const handleAssign = useCallback(async (replaceAvatar = false) => {
|
||||
if (!selected || actionLoading) return
|
||||
setActionLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
await assignImmichPerson(treeId, person.id, selected.id, token, { replaceAvatar })
|
||||
onImmichChange?.(person.id)
|
||||
onClose?.()
|
||||
} catch (err) {
|
||||
// Un portrait est déjà en place : le serveur refuse le remplacement en silence
|
||||
// (409 avatar_exists) ; il revient à l'administrateur de le confirmer.
|
||||
if (!replaceAvatar && err?.payload?.error === 'avatar_exists') {
|
||||
setConfirmReplace(true)
|
||||
} else {
|
||||
setError(getImmichErrorMessage(err, t))
|
||||
}
|
||||
} finally {
|
||||
setActionLoading(false)
|
||||
}
|
||||
}, [selected, actionLoading, treeId, person, token, onImmichChange, onClose])
|
||||
|
||||
const handleUnassign = useCallback(async () => {
|
||||
if (!person.avatarFromImmich || actionLoading) return
|
||||
setActionLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
await unassignImmichPerson(treeId, person.id, token)
|
||||
onImmichChange?.(person.id)
|
||||
onClose?.()
|
||||
} catch (err) {
|
||||
setError(getImmichErrorMessage(err, t))
|
||||
} finally {
|
||||
setActionLoading(false)
|
||||
}
|
||||
}, [person, actionLoading, treeId, token, onImmichChange, onClose])
|
||||
|
||||
const filteredPeople = search.trim()
|
||||
? people.filter((immichPerson) => immichPerson.name?.toLowerCase().includes(search.trim().toLowerCase()))
|
||||
: people
|
||||
|
||||
const handleOverlayClick = (event) => {
|
||||
if (event.target === event.currentTarget) {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
// L'association en place se retire aussi bien sans connexion : changer ou retirer le serveur
|
||||
// Immich ne laisse jamais une ancienne image impossible à nettoyer manuellement. Le graphe
|
||||
// ne dit que l'origine du portrait (avatarFromImmich), jamais l'identifiant Immich.
|
||||
const unassignBlock = person.avatarFromImmich && (
|
||||
<div className="immich-current">
|
||||
<p>{t('{name} est déjà associée à une personne Immich.', { name: person.firstName || person.lastName })}</p>
|
||||
<button type="button" className="pz-btn pz-btn--danger-ghost" onClick={handleUnassign} disabled={actionLoading}>
|
||||
<Unlink size={16} aria-hidden="true" /> {t('Retirer l’association')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
|
||||
return createPortal(
|
||||
<div className="pz-overlay immich-modal-overlay" onClick={handleOverlayClick}>
|
||||
<div className="pz-modal immich-modal-card" role="dialog" aria-modal="true" aria-labelledby="immichFaceTitle">
|
||||
<div className="pz-modal-head">
|
||||
<p className="pz-eyebrow">{t('Reconnaissance des visages')}</p>
|
||||
<h1 id="immichFaceTitle" className="pz-title">{person.firstName} <em>{person.lastName}</em></h1>
|
||||
</div>
|
||||
<button type="button" className="pz-btn pz-btn--ghost pz-btn--icon pz-modal-close" onClick={onClose} aria-label={t('Fermer')}>
|
||||
<X size={18} aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
{available === null || loadingPeople ? (
|
||||
<div className="immich-body"><PzBusy /></div>
|
||||
) : available === false ? (
|
||||
<div className="immich-body">
|
||||
{unassignBlock}
|
||||
<p className="immich-empty">
|
||||
{unavailableReason === 'not_configured'
|
||||
? t('Immich n’est pas configuré pour cet arbre. Ses administrateurs le règlent dans Paramètres de l’arbre.')
|
||||
: t('Immich est injoignable.')}
|
||||
</p>
|
||||
{error && <div className="pz-error immich-error">{error}</div>}
|
||||
</div>
|
||||
) : (
|
||||
<div className="immich-body">
|
||||
{unassignBlock}
|
||||
|
||||
<div className="pz-field">
|
||||
<span className="pz-label" id="immichSearchLabel">{t('Personne à associer dans Immich')}</span>
|
||||
<div className="immich-search">
|
||||
<Search size={16} aria-hidden="true" />
|
||||
<input
|
||||
type="search"
|
||||
aria-labelledby="immichSearchLabel"
|
||||
placeholder={t('Rechercher par nom')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{filteredPeople.length === 0 ? (
|
||||
<p className="immich-empty">{people.length === 0 ? t('Aucune personne dans Immich.') : t('Aucune personne trouvée.')}</p>
|
||||
) : (
|
||||
<div className="immich-list" role="listbox" aria-label={t('Personnes Immich')}>
|
||||
{filteredPeople.map((immichPerson) => {
|
||||
const isSelected = selected?.id === immichPerson.id
|
||||
const isLinked = linkedId === immichPerson.id
|
||||
return (
|
||||
<button
|
||||
key={immichPerson.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
className={`immich-person ${isSelected ? 'is-active' : ''} ${isLinked ? 'is-linked' : ''}`}
|
||||
onClick={() => handleSelect(immichPerson)}
|
||||
>
|
||||
<FaceThumb
|
||||
immichPersonId={immichPerson.id}
|
||||
hasThumbnail={immichPerson.hasThumbnail}
|
||||
request={requestThumbnail}
|
||||
/>
|
||||
<span className="immich-person-name">{immichPerson.name || t('Sans nom')}</span>
|
||||
{isLinked && <span className="pz-tag pz-tag--accent immich-person-tag">{t('Associée')}</span>}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selected && (
|
||||
<div className="immich-preview">
|
||||
<FaceThumb
|
||||
key={selected.id}
|
||||
className="immich-face--preview"
|
||||
immichPersonId={selected.id}
|
||||
hasThumbnail={selected.hasThumbnail}
|
||||
request={requestThumbnail}
|
||||
eager
|
||||
/>
|
||||
<div className="immich-preview-name">{selected.name || t('Sans nom')}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <div className="pz-error immich-error">{error}</div>}
|
||||
|
||||
{confirmReplace && (
|
||||
<p className="immich-confirm">
|
||||
{t('Un portrait est déjà en place. Associer cette personne Immich remplacera le portrait actuel et supprimera son fichier.')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="pz-modal-actions">
|
||||
{confirmReplace ? (
|
||||
<>
|
||||
<button type="button" className="pz-btn pz-btn--ghost" onClick={() => setConfirmReplace(false)}>
|
||||
{t('Garder le portrait actuel')}
|
||||
</button>
|
||||
<button type="button" className="pz-btn pz-btn--danger" onClick={() => handleAssign(true)} disabled={actionLoading}>
|
||||
{actionLoading ? <Loader2 size={16} className="immich-spin" aria-hidden="true" /> : null}
|
||||
{t('Remplacer le portrait et associer')}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button type="button" className="pz-btn pz-btn--ghost" onClick={onClose}>{t('Annuler')}</button>
|
||||
<button type="button" className="pz-btn pz-btn--primary" onClick={() => handleAssign()} disabled={!selected || actionLoading}>
|
||||
{actionLoading ? <Loader2 size={16} className="immich-spin" aria-hidden="true" /> : null}
|
||||
{t('Associer et prendre le portrait')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)
|
||||
}
|
||||
|
||||
export default ImmichFacePanel
|
||||
@@ -55,6 +55,9 @@
|
||||
.pc-photo--add:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 3px; }
|
||||
.pc-photo--add:disabled { opacity: .6; cursor: default; }
|
||||
.pc-photo-actions { display: grid; gap: 4px; justify-items: center; }
|
||||
/* Menu du choix de source du portrait : au-dessus de la fiche (z-index 1000), sous la modale Immich (2200) */
|
||||
.pc-source-backdrop { position: fixed; inset: 0; z-index: 1100; }
|
||||
.pc-source-menu { position: fixed; z-index: 1150; min-width: 220px; }
|
||||
.pc-photo-btn {
|
||||
border: 0; background: none; padding: 2px 4px; cursor: pointer;
|
||||
font: 500 12px var(--pz-sans); color: var(--pz-a700); text-decoration: underline; text-underline-offset: 2px;
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useState, useEffect, useRef, forwardRef } from 'react'
|
||||
import { Save, Trash2, Plus, X, Search, Check, Play, ImagePlus } from 'lucide-react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Save, Trash2, Plus, X, Search, Check, Play, ImagePlus, Sparkles } from 'lucide-react'
|
||||
import { getParents, getChildren, getPersonUnions, getPersonMedias, filiations, persons, unions } from '../data/mockData'
|
||||
import { fetchImmichConfig } from '../api/immichApi.js'
|
||||
import GeoMediaThumbnail from './GeoMediaThumbnail'
|
||||
import ImmichFacePanel from './ImmichFacePanel.jsx'
|
||||
import './PersonCard.css'
|
||||
import PzBusy from './PzBusy.jsx'
|
||||
import { t, dateLocale } from '../i18n/index.js'
|
||||
@@ -35,6 +38,9 @@ const PersonCard = ({
|
||||
onManageMedia,
|
||||
onAvatarUpload,
|
||||
onAvatarDelete,
|
||||
treeId = null,
|
||||
immichToken = null,
|
||||
onImmichChange,
|
||||
avatarActionLoading = false,
|
||||
avatarActionError = '',
|
||||
isAdmin = false,
|
||||
@@ -55,6 +61,14 @@ const PersonCard = ({
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saveSuccess, setSaveSuccess] = useState(false)
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||
const [showImmichPanel, setShowImmichPanel] = useState(false)
|
||||
// null : connexion Immich de l'arbre inconnue, puis booléen. Le menu de source ne se propose
|
||||
// qu'à qui peut agir (owner/admin de l'arbre, comme pour toute action Immich) et seulement
|
||||
// si l'arbre est connecté ou qu'une association passée demande un nettoyage.
|
||||
const [immichConfigured, setImmichConfigured] = useState(null)
|
||||
const [showSourceMenu, setShowSourceMenu] = useState(false)
|
||||
const [sourceMenuPos, setSourceMenuPos] = useState({ top: 0, left: 0 })
|
||||
const sourceBtnRef = useRef(null)
|
||||
|
||||
// Inline relation search state
|
||||
const [activeRelationSearch, setActiveRelationSearch] = useState(null) // 'parent' | 'spouse' | 'child' | null
|
||||
@@ -70,8 +84,49 @@ const PersonCard = ({
|
||||
setActiveRelationSearch(null)
|
||||
setRelationSearchQuery('')
|
||||
setSaveSuccess(false)
|
||||
setShowSourceMenu(false)
|
||||
}, [person.id])
|
||||
|
||||
// Connexion Immich de l'arbre : métadonnées sans clé. Une erreur (rôle périmé, réseau) se
|
||||
// traduit par « non configuré » : la fiche reste utilisable, simplement sans choix de source.
|
||||
// Seul un administrateur de l'arbre voit l'option Immich, comme côté serveur.
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setImmichConfigured(null)
|
||||
setShowSourceMenu(false)
|
||||
if (!editMode || !isAdmin || !treeId || !onImmichChange || !immichToken) return undefined
|
||||
fetchImmichConfig(treeId, immichToken)
|
||||
.then(({ config }) => { if (!cancelled) setImmichConfigured(Boolean(config?.configured)) })
|
||||
.catch(() => { if (!cancelled) setImmichConfigured(false) })
|
||||
return () => { cancelled = true }
|
||||
}, [editMode, isAdmin, treeId, immichToken, onImmichChange])
|
||||
|
||||
useEffect(() => {
|
||||
if (!showSourceMenu) return undefined
|
||||
const onKeyDown = (event) => { if (event.key === 'Escape') setShowSourceMenu(false) }
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
return () => window.removeEventListener('keydown', onKeyDown)
|
||||
}, [showSourceMenu])
|
||||
|
||||
const immichUsable = isAdmin && Boolean(immichConfigured || person.avatarFromImmich)
|
||||
const openAvatarPicker = () => {
|
||||
if (avatarActionLoading) return
|
||||
if (immichUsable) {
|
||||
const rect = sourceBtnRef.current?.getBoundingClientRect()
|
||||
if (rect) {
|
||||
setSourceMenuPos({
|
||||
top: Math.round(rect.bottom) + 6,
|
||||
left: Math.round(Math.min(rect.left, window.innerWidth - 252)),
|
||||
})
|
||||
}
|
||||
setShowSourceMenu(true)
|
||||
} else {
|
||||
avatarInputRef.current?.click()
|
||||
}
|
||||
}
|
||||
const chooseFileSource = () => { setShowSourceMenu(false); avatarInputRef.current?.click() }
|
||||
const chooseImmichSource = () => { setShowSourceMenu(false); setShowImmichPanel(true) }
|
||||
|
||||
// Focus search input when relation search opens
|
||||
useEffect(() => {
|
||||
if (activeRelationSearch) {
|
||||
@@ -363,11 +418,24 @@ const PersonCard = ({
|
||||
)}
|
||||
{editMode && onAvatarUpload && (
|
||||
<div className="pc-photo-actions">
|
||||
<button type="button" className="pc-photo-btn" onClick={() => avatarInputRef.current?.click()} disabled={avatarActionLoading}>
|
||||
<button
|
||||
ref={sourceBtnRef}
|
||||
type="button"
|
||||
className="pc-photo-btn"
|
||||
onClick={openAvatarPicker}
|
||||
disabled={avatarActionLoading}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={showSourceMenu}
|
||||
>
|
||||
{person.photo ? t('Changer') : t('Ajouter une photo')}
|
||||
</button>
|
||||
{person.photo && (
|
||||
<button type="button" className="pc-photo-btn pc-photo-btn--danger" onClick={() => onAvatarDelete?.(person.id)} disabled={avatarActionLoading}>
|
||||
<button
|
||||
type="button"
|
||||
className="pc-photo-btn pc-photo-btn--danger"
|
||||
onClick={() => onAvatarDelete?.(person.id, person.avatarFromImmich)}
|
||||
disabled={avatarActionLoading}
|
||||
>
|
||||
{t('Retirer')}
|
||||
</button>
|
||||
)}
|
||||
@@ -690,6 +758,35 @@ const PersonCard = ({
|
||||
)}
|
||||
</footer>
|
||||
)}
|
||||
|
||||
{/* ── Choix de la source du portrait (menu contextuel) ── */}
|
||||
{showSourceMenu && (
|
||||
createPortal(
|
||||
<>
|
||||
<div className="pc-source-backdrop" onClick={() => setShowSourceMenu(false)} />
|
||||
<div className="pc-source-menu pz-menu" role="menu" aria-label={t('Source du portrait')} style={{ top: `${sourceMenuPos.top}px`, left: `${sourceMenuPos.left}px` }}>
|
||||
<button type="button" role="menuitem" className="pz-menu-item" onClick={chooseFileSource}>
|
||||
<ImagePlus size={16} aria-hidden="true" /> {t('Depuis un fichier')}
|
||||
</button>
|
||||
<button type="button" role="menuitem" className="pz-menu-item" onClick={chooseImmichSource}>
|
||||
<Sparkles size={16} aria-hidden="true" /> {t('Depuis Immich')}
|
||||
</button>
|
||||
</div>
|
||||
</>,
|
||||
document.body,
|
||||
)
|
||||
)}
|
||||
|
||||
{/* ── Association d'un visage Immich (modale) ── */}
|
||||
{showImmichPanel && treeId && (
|
||||
<ImmichFacePanel
|
||||
person={person}
|
||||
treeId={treeId}
|
||||
token={immichToken}
|
||||
onClose={() => setShowImmichPanel(false)}
|
||||
onImmichChange={onImmichChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -44,6 +44,8 @@
|
||||
.ts-row--muted { opacity: .6; }
|
||||
.ts-row-text { display: grid; gap: 4px; min-width: 0; }
|
||||
.ts-row-text strong { font: 500 14.5px var(--pz-sans); color: var(--pz-ink); }
|
||||
/* La grille étire ses enfants : une pastille garde la largeur de son texte. */
|
||||
.ts-row-text > .pz-tag { justify-self: start; }
|
||||
.ts-row-actions { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; flex: none; }
|
||||
.ts-file { justify-self: start; margin-top: 4px; }
|
||||
.ts-file-input { display: none; }
|
||||
|
||||
@@ -115,6 +115,7 @@ function mapRemotePersonToLocal(person, current = null) {
|
||||
profession: person?.profession || null,
|
||||
nationality: person?.nationality || null,
|
||||
photo: current?.photo || null,
|
||||
avatarFromImmich: person?.avatarFromImmich ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ describe('loadGraphData avatar mapping', () => {
|
||||
deathDate: null,
|
||||
notes: null,
|
||||
avatarUrlPath: '/trees/t-1/persons/p-1/avatar',
|
||||
avatarFromImmich: true,
|
||||
},
|
||||
{
|
||||
id: 'p-2',
|
||||
@@ -24,6 +25,7 @@ describe('loadGraphData avatar mapping', () => {
|
||||
deathDate: null,
|
||||
notes: null,
|
||||
avatarUrlPath: null,
|
||||
avatarFromImmich: false,
|
||||
},
|
||||
],
|
||||
unions: [],
|
||||
@@ -48,6 +50,9 @@ describe('loadGraphData avatar mapping', () => {
|
||||
expect(getPersonById('p-1')?.photo).toBe('/api/trees/t-1/persons/p-1/avatar?token=abc')
|
||||
expect(getPersonById('p-2')?.photo).toBeNull()
|
||||
expect(getPersonMedias('p-2')[0]?.source).toBe('Album familial')
|
||||
// Origine du portrait portée par la personne (faux quand il ne vient pas d'Immich)
|
||||
expect(getPersonById('p-1')?.avatarFromImmich).toBe(true)
|
||||
expect(getPersonById('p-2')?.avatarFromImmich).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -123,6 +123,29 @@ export default {
|
||||
"Dernière vérification": "Final check",
|
||||
"Supprimer « {name} »": "Delete “{name}”",
|
||||
"Tapez le nom exact de l'arbre pour confirmer.": "Type the exact name of the tree to confirm.",
|
||||
// Section Immich dans l'onglet Avancé (AdminPanel)
|
||||
'La connexion Immich est propre à cet arbre : ses administrateurs choisissent une instance autorisée par l’opérateur du serveur et fournissent leur propre clé d’accès.': 'The Immich connection belongs to this tree: its administrators pick an instance authorized by the server operator and provide their own access key.',
|
||||
'Configurée': 'Configured',
|
||||
'Non configurée': 'Not configured',
|
||||
'Clé à ressaisir': 'Key to re-enter',
|
||||
'La clé enregistrée ne peut plus être lue (le secret du serveur a changé). Ressaisissez-la pour réactiver la connexion.': 'The saved key can no longer be read (the server secret changed). Enter it again to reactivate the connection.',
|
||||
'Instance joignable.': 'Instance reachable.',
|
||||
'Test en cours…': 'Testing…',
|
||||
'Test impossible.': 'Test failed.',
|
||||
'Connexion non testée depuis l’ouverture.': 'Connection not tested since the panel opened.',
|
||||
'Tester la connexion': 'Test the connection',
|
||||
'Instance Immich': 'Immich instance',
|
||||
'Choisir une instance…': 'Choose an instance…',
|
||||
'Choisissez l’instance Immich.': 'Choose the Immich instance.',
|
||||
'Clé d’accès Immich': 'Immich access key',
|
||||
'Laisser vide pour conserver la clé actuelle': 'Leave empty to keep the current key',
|
||||
'Clé d’accès de la nouvelle instance requise': 'New instance access key required',
|
||||
'L’instance Immich change : indiquez la clé d’accès de la nouvelle instance, l’ancienne n’est pas conservée.': 'The Immich instance is changing: enter the new instance’s access key — the old one is not kept.',
|
||||
'Clé créée dans Immich (Paramètres > Clés d’API)': 'Key created in Immich (Settings > API Keys)',
|
||||
'Supprimer la connexion': 'Remove the connection',
|
||||
'Connexion Immich enregistrée.': 'Immich connection saved.',
|
||||
'Supprimer la connexion Immich de cet arbre ? La reconnaissance des visages sera désactivée.': 'Remove this tree\'s Immich connection? Face recognition will be disabled.',
|
||||
'Connexion Immich supprimée.': 'Immich connection removed.',
|
||||
// Onglet Visites (TreeVisitsSection)
|
||||
"téléphone": "phone",
|
||||
"tablette": "tablet",
|
||||
|
||||
@@ -259,4 +259,36 @@ export default {
|
||||
'En rédaction': 'In the newsroom',
|
||||
'Interview archive radio': 'Archived radio interview',
|
||||
'Inconnu': 'Unknown',
|
||||
// Visages venus d'Immich (PersonCard, ImmichFacePanel, immichApi)
|
||||
'Depuis Immich': 'From Immich',
|
||||
'Depuis un fichier': 'From a file',
|
||||
'Source du portrait': 'Portrait source',
|
||||
'Visage Immich': 'Immich face',
|
||||
'Reconnaissance des visages': 'Face recognition',
|
||||
'Immich n’est pas configuré pour cet arbre.': 'Immich is not configured for this tree.',
|
||||
'Immich n’est pas configuré pour cet arbre. Ses administrateurs le règlent dans Paramètres de l’arbre.': 'Immich is not configured for this tree. Its administrators set it up in Tree settings.',
|
||||
'Immich est injoignable.': 'Immich cannot be reached.',
|
||||
'La clé d’accès à Immich a été refusée.': 'The Immich access key was rejected.',
|
||||
'Personne introuvable dans Immich.': 'Person not found in Immich.',
|
||||
'Identifiant Immich invalide.': 'Invalid Immich identifier.',
|
||||
'La vignette Immich n’est pas une image valide.': 'The Immich thumbnail is not a valid image.',
|
||||
'Espace disque de l’arbre dépassé.': 'Tree storage quota exceeded.',
|
||||
'Indiquez la clé d’accès à Immich pour la première configuration.': 'Enter the Immich access key for the first setup.',
|
||||
'Cette instance Immich n’est pas autorisée par l’opérateur du serveur.': 'This Immich instance is not authorized by the server operator.',
|
||||
'Seuls les administrateurs de l’arbre peuvent associer un visage Immich.': 'Only tree administrators can link an Immich face.',
|
||||
'Erreur inattendue.': 'Unexpected error.',
|
||||
'{name} est déjà associée à une personne Immich.': '{name} is already linked to an Immich person.',
|
||||
'Retirer l’association': 'Remove the link',
|
||||
'Personne à associer dans Immich': 'Immich person to link',
|
||||
'Rechercher par nom': 'Search by name',
|
||||
'Aucune personne dans Immich.': 'No people in Immich.',
|
||||
'Aucune personne trouvée.': 'No people found.',
|
||||
'Personnes Immich': 'Immich people',
|
||||
'Sans nom': 'Unnamed',
|
||||
'Associée': 'Linked',
|
||||
'Associer et prendre le portrait': 'Link and use as portrait',
|
||||
'Un portrait est déjà en place. Associer cette personne Immich remplacera le portrait actuel et supprimera son fichier.':
|
||||
'A portrait is already in place. Linking this Immich person will replace the current portrait and delete its file.',
|
||||
'Garder le portrait actuel': 'Keep the current portrait',
|
||||
'Remplacer le portrait et associer': 'Replace the portrait and link',
|
||||
}
|
||||
@@ -57,6 +57,7 @@ export function adaptGraphForGalaxy(apiGraph, _treeId) {
|
||||
birthDate: p.birthDate,
|
||||
deathDate: p.deathDate,
|
||||
photo: p.avatarUrlPath ? `/api${p.avatarUrlPath}` : null,
|
||||
avatarFromImmich: Boolean(p.avatarFromImmich),
|
||||
frameType: 'round', // Default
|
||||
}))
|
||||
|
||||
|
||||
Reference in new issue
Block a user