Images de l'arbre : jeton médias à la place de la session du compte

Portraits, souvenirs, photos posées sur l'arbre et aperçus de relecture chargeaient leur image avec la session complète dans l'adresse. Ils utilisent maintenant le jeton de lecture des médias fourni avec le graphe (utils/mediaToken.js), jamais ajouté à une adresse externe. L'aperçu d'une photo posée par la famille n'accepte qu'une photo de cet arbre, reconstruite depuis son chemin. Message pour un arbre plein (storage_quota_exceeded).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
IliesAllaliandClaude Opus 5.5 committed 2026-09-30 18:03:04 +02:00
1 parent 91c93ddfa1
commit 468204c9d3
10 files changed
+78 -26

No files matched your search

+3 -5
View File
@@ -1,4 +1,5 @@
import { useEffect, useState, useCallback, useRef, useMemo } from 'react'
import { buildMediaUrl } from './utils/mediaToken.js'
import Galaxy from './components/Galaxy'
import PersonCard from './components/PersonCard.jsx'
import { FamilyWelcome, SouvenirPicker } from './components/FamilyOnboarding.jsx'
@@ -783,10 +784,8 @@ function App() {
// Get natural dimensions from the file
const img = new Image()
img.onload = () => {
const apiBase = import.meta.env.VITE_API_BASE_URL || '/api'
const fullUrl = token
? `${apiBase}${result.photoPath}?token=${encodeURIComponent(token)}`
: `${apiBase}${result.photoPath}`
// Adresse d'affichage avec le jeton médias ; le serveur n'enregistre que photoPath
const fullUrl = buildMediaUrl(result.photoPath, import.meta.env.VITE_API_BASE_URL || '/api')
annot.placePhoto(worldX, worldY, result.photoPath, fullUrl, img.naturalWidth, img.naturalHeight)
URL.revokeObjectURL(img.src)
}
@@ -2695,7 +2694,6 @@ function App() {
/>
<ContributionPanel
visible={contrib.contribState.visible}
mediaToken={tree.treeContext.accessToken || auth.userAuth.token || ''}
treeId={tree.treeContext.treeId}
canModerate={tree.canEditCurrentTree}
loading={contrib.contribState.loading}
+1
View File
@@ -57,6 +57,7 @@ export async function fetchTreeGraph(treeId, token) {
treeId: data?.treeId || treeId,
rootPersonId: data?.rootPersonId || null,
graph: data?.graph || { persons: [], unions: [], filiations: [], medias: [] },
mediaToken: data?.mediaToken || '',
}
}
+12 -7
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from 'react'
import { buildMediaUrl } from '../utils/mediaToken.js'
import { API_BASE_URL } from '../api/client'
import { persons as treePersons } from '../data/mockData'
import { Check, ChevronDown, Copy, RefreshCw, X } from 'lucide-react'
@@ -37,13 +38,13 @@ const MEDIA_TYPE_LABELS = {
}
// Souvenir envoyé par la famille : de quoi juger avant d'accepter
function getMediaPreview(change, treeId, token) {
function getMediaPreview(change, treeId) {
const data = (change.afterJson && typeof change.afterJson === 'object') ? change.afterJson : {}
const label = MEDIA_TYPE_LABELS[data.type] || t('Souvenir')
const caption = typeof data.caption === 'string' ? data.caption : ''
const isYoutube = data.mimeType === 'video/youtube'
const url = change.entityId && treeId && !isYoutube
? `${API_BASE_URL}/trees/${encodeURIComponent(treeId)}/media/${encodeURIComponent(change.entityId)}${token ? `?token=${encodeURIComponent(token)}` : ''}`
? buildMediaUrl(`/trees/${encodeURIComponent(treeId)}/media/${encodeURIComponent(change.entityId)}`, API_BASE_URL)
: null
return { type: data.type, label, caption, url, isYoutube }
}
@@ -143,7 +144,7 @@ function getFieldRows(change) {
})
}
function getAnnotationPreview(change) {
function getAnnotationPreview(change, treeId) {
const data = change.afterJson || change.after || {}
const type = data.type
if (!type) return null
@@ -152,8 +153,13 @@ function getAnnotationPreview(change) {
if (type === 'drawing') return { type, color: data.style?.color || '#2A2622' }
if (type === 'photo') {
try {
// Seulement une photo de cet arbre, reconstruite depuis son chemin : une adresse fournie par
// l'auteur de la contribution pourrait pister celui qui relit
const parsed = typeof data.content === 'string' ? JSON.parse(data.content) : data.content
return { type, url: parsed?.url || null }
const prefix = `/trees/${treeId}/annotation-photos/`
const photoPath = typeof parsed?.photoPath === 'string' ? parsed.photoPath : ''
const isOwnPhoto = photoPath.startsWith(prefix) && /^[A-Za-z0-9-]+$/.test(photoPath.slice(prefix.length))
return { type, url: isOwnPhoto ? buildMediaUrl(photoPath, API_BASE_URL) : null }
} catch { return { type } }
}
return { type }
@@ -188,7 +194,6 @@ function buildInviteText(url, password) {
const ContributionPanel = ({
visible,
mediaToken = '',
treeId,
canModerate,
loading,
@@ -494,8 +499,8 @@ const ContributionPanel = ({
const isRejected = decision === 'rejected'
const personName = getPersonDisplayName(change, session.changes || [])
const fields = getFieldRows(change)
const annPreview = change.entityType === 'annotation' ? getAnnotationPreview(change) : null
const mediaPreview = change.entityType === 'media' ? getMediaPreview(change, treeId, mediaToken) : null
const annPreview = change.entityType === 'annotation' ? getAnnotationPreview(change, treeId) : null
const mediaPreview = change.entityType === 'media' ? getMediaPreview(change, treeId) : null
return (
<div
+10 -12
View File
@@ -4,6 +4,7 @@
// ============================================================
import { t } from '../i18n/index.js'
import { buildMediaUrl } from '../utils/mediaToken.js'
// Démo : noms et lieux restent français, les textes descriptifs sont traduits.
export let persons = [
@@ -80,16 +81,13 @@ function pickFrameType(id) {
return frameTypes[hash % frameTypes.length]
}
function buildProtectedAssetUrl(pathOrUrl, apiBaseUrl, authToken, cacheBust = null) {
if (!pathOrUrl) {
// Adresse d'un fichier de l'arbre avec le jeton médias (voir utils/mediaToken.js)
function buildProtectedAssetUrl(pathOrUrl, apiBaseUrl, mediaToken, cacheBust = null) {
let protectedUrl = buildMediaUrl(pathOrUrl, apiBaseUrl, mediaToken)
if (!protectedUrl) {
return null
}
const absolutePath = pathOrUrl.startsWith('http://') || pathOrUrl.startsWith('https://')
? pathOrUrl
: `${apiBaseUrl}${pathOrUrl}`
let protectedUrl = authToken ? `${absolutePath}?token=${encodeURIComponent(authToken)}` : absolutePath
if (cacheBust !== null && cacheBust !== undefined) {
const separator = protectedUrl.includes('?') ? '&' : '?'
protectedUrl = `${protectedUrl}${separator}v=${encodeURIComponent(String(cacheBust))}`
@@ -130,7 +128,7 @@ export function resetToDemoData() {
}
export function loadGraphData(graph, options = {}) {
const authToken = options.authToken || ''
const mediaToken = options.mediaToken || ''
const apiBaseUrl = (options.apiBaseUrl || '').replace(/\/$/, '')
const avatarCacheBust = options.avatarCacheBust ?? null
@@ -142,7 +140,7 @@ export function loadGraphData(graph, options = {}) {
persons = remotePersons.map((person) => {
const localPerson = mapRemotePersonToLocal(person)
localPerson.photo = buildProtectedAssetUrl(person.avatarUrlPath || null, apiBaseUrl, authToken, avatarCacheBust)
localPerson.photo = buildProtectedAssetUrl(person.avatarUrlPath || null, apiBaseUrl, mediaToken, avatarCacheBust)
return localPerson
})
@@ -200,7 +198,7 @@ export function loadGraphData(graph, options = {}) {
medias = remoteMedias
.filter((media) => personIdSet.has(media.personId))
.map((media, index) => {
const mediaUrl = buildProtectedAssetUrl(media.urlPath || '', apiBaseUrl, authToken)
const mediaUrl = buildProtectedAssetUrl(media.urlPath || '', apiBaseUrl, mediaToken)
return {
id: media.id,
@@ -218,12 +216,12 @@ export function loadGraphData(graph, options = {}) {
annotations = remoteAnnotations.map((ann) => {
let content = ann.content || ''
// For photo annotations: rebuild URL with current auth token from stored photoPath
// Annotation photo : l'adresse est reconstruite ici depuis photoPath, le serveur n'en garde aucune
if (ann.type === 'photo' && content) {
try {
const parsed = typeof content === 'string' ? JSON.parse(content) : content
if (parsed.photoPath) {
parsed.url = buildProtectedAssetUrl(parsed.photoPath, apiBaseUrl, authToken)
parsed.url = buildProtectedAssetUrl(parsed.photoPath, apiBaseUrl, mediaToken)
content = JSON.stringify(parsed)
}
} catch { /* ignore */ }
+1 -1
View File
@@ -42,7 +42,7 @@ describe('loadGraphData avatar mapping', () => {
],
annotations: [],
},
{ apiBaseUrl: '/api', authToken: 'abc' },
{ apiBaseUrl: '/api', mediaToken: 'abc' },
)
expect(getPersonById('p-1')?.photo).toBe('/api/trees/t-1/persons/p-1/avatar?token=abc')
+3 -1
View File
@@ -1,4 +1,5 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { setMediaToken } from '../utils/mediaToken.js'
import { API_BASE_URL } from '../api/client'
import { fetchTreeGraph, unlockTreeAccess } from '../api/treeApi'
import { loadGraphData, persons as graphPersons, resetToDemoData } from '../data/mockData'
@@ -65,8 +66,9 @@ export function useTreeAccess() {
const openTreeGraph = async (treeId, token, options = {}) => {
const graphPayload = await fetchTreeGraph(treeId, token)
setMediaToken(graphPayload.mediaToken)
loadGraphData(graphPayload.graph, {
authToken: token,
mediaToken: graphPayload.mediaToken,
apiBaseUrl: API_BASE_URL,
avatarCacheBust: options.avatarCacheBust ?? avatarCacheBustRef.current,
})
+1
View File
@@ -84,6 +84,7 @@ export default {
'Le fichier média envoyé est invalide.': 'The media file you sent is invalid.',
'Le format de fichier ne correspond pas au type de média choisi.': 'The file format does not match the media type you chose.',
'Ajoutez le texte de la citation.': 'Add the text of the quote.',
"L'arbre n'a plus de place pour de nouveaux souvenirs. Son propriétaire peut en supprimer.": 'This tree has no room left for new memories. Its owner can delete some.',
"Erreur base de données. Lancez `npm run prisma:deploy` puis redémarrez l'API.": 'Database error. Run `npm run prisma:deploy`, then restart the API.',
'Base de données indisponible. Lancez `npm run db:bootstrap` dans le backend.': 'Database unavailable. Run `npm run db:bootstrap` in the backend.',
'Slug invalide : 3-64 caractères, uniquement lettres minuscules, chiffres et tirets.': 'Invalid slug: 3 to 64 characters, lowercase letters, numbers and hyphens only.',
+4
View File
@@ -55,6 +55,10 @@ export function getAccountErrorMessage(error) {
return t('Le format de fichier ne correspond pas au type de média choisi.')
}
if (errorCode === 'storage_quota_exceeded') {
return t("L'arbre n'a plus de place pour de nouveaux souvenirs. Son propriétaire peut en supprimer.")
}
if (errorCode === 'citation_text_required') {
return t('Ajoutez le texte de la citation.')
}
+26
View File
@@ -0,0 +1,26 @@
// Jeton de lecture des médias de l'arbre ouvert, fourni par le serveur avec le graphe.
// Les images sont chargées par <img src>, sans en-tête : leur adresse porte ce jeton, jamais la
// session du compte (qui finissait dans l'historique, les journaux et les liens copiés).
let currentMediaToken = ''
export function setMediaToken(token) {
currentMediaToken = typeof token === 'string' ? token : ''
}
export function getMediaToken() {
return currentMediaToken
}
// Adresse d'un fichier servi par l'API. Une adresse externe (YouTube) ne reçoit jamais de jeton.
export function buildMediaUrl(pathOrUrl, apiBaseUrl = '', token = currentMediaToken) {
if (!pathOrUrl) {
return null
}
if (/^https?:\/\//.test(pathOrUrl)) {
return pathOrUrl
}
const url = `${apiBaseUrl}${pathOrUrl}`
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}` : url
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest'
import { buildMediaUrl } from './mediaToken.js'
describe('adresse des médias', () => {
it('ajoute le jeton médias aux fichiers servis par l API', () => {
expect(buildMediaUrl('/trees/t/media/m', '/api', 'jeton')).toBe('/api/trees/t/media/m?token=jeton')
})
it('ne met jamais de jeton sur une adresse externe', () => {
expect(buildMediaUrl('https://www.youtube.com/watch?v=abc', '/api', 'jeton')).toBe('https://www.youtube.com/watch?v=abc')
})
it('renvoie null sans chemin', () => {
expect(buildMediaUrl('', '/api', 'jeton')).toBeNull()
})
})