1 Commits

Author SHA1 Message Date
Jules Neny
7e7ddfbfbf feat(api): ajoute endpoint /api/aep-perso (desinscription/reabonnement) 2026-07-04 11:55:15 +02:00
6 changed files with 234 additions and 389 deletions

View File

@@ -1,24 +1,17 @@
# Kit (ex-ConvertKit) - newsletter infolettre # Kit (ex-ConvertKit) - newsletter infolettre
KIT_API_SECRET_V4=kit_xxx KIT_API_SECRET_V4=kit_xxx
# Behold.so : DEPRECATED V1.5-E — remplace par RSSHub self-host (rss.trans-former.fr). # Behold.so feed IDs (voir docs/BEHOLD-SETUP.md)
# InstaFeed.vue consomme desormais PUBLIC_JOURNAL_URL (filtre platform=instagram). # 1) Inscris-toi sur https://behold.so/dashboard
# Les 2 vars ci-dessous ne sont plus lues ; conservees pour compat.env.local existant. # 2) Connecte les 2 comptes Insta (@aep.politique + @julesneny)
# 3) Recupere les feed IDs et copie ce fichier vers .env.local puis remplis ci-dessous
PUBLIC_BEHOLD_AEP= PUBLIC_BEHOLD_AEP=
PUBLIC_BEHOLD_JULESNENY= PUBLIC_BEHOLD_JULESNENY=
# Journal unifie (V1.6) - URL JSON agrege par n8n cron 4h UTC # Journal unifie (PC6) - URL JSON agrege par n8n cron nocturne
# Sources : RSSHub self-host (Insta @aep.politique + @julesneny) + Substack natif
# + Atom Gitea natif (git.trans-former.fr/jules.atom) + LinkedIn API V2
# Override en local : pointer vers un mock /public/data/journal.json par exemple # Override en local : pointer vers un mock /public/data/journal.json par exemple
PUBLIC_JOURNAL_URL=https://data.trans-former.fr/journal.json PUBLIC_JOURNAL_URL=https://data.trans-former.fr/journal.json
# LinkedIn (V1.6) - Member ID du profil Jules (format numerique, sans urn: prefix)
# Recuperer via curl -H "Authorization: Bearer TOKEN" https://api.linkedin.com/v2/me | jq .id
# Stocke comme variable d'env n8n (Settings -> Variables) sous le nom LINKEDIN_MEMBER_ID
# Le workflow l'utilise comme : urn:li:person:${LINKEDIN_MEMBER_ID}
LINKEDIN_MEMBER_ID=
# Chatbot upstream (PC7) - URL backend chatbot AEP # Chatbot upstream (PC7) - URL backend chatbot AEP
# V1 : chatbot AEP classique (Mistral Small + 120 fiches) # V1 : chatbot AEP classique (Mistral Small + 120 fiches)
# V1.5 : switch vers LightRAG-PE (1 ligne) # V1.5 : switch vers LightRAG-PE (1 ligne)

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,6 @@
{ {
"version": "1.1", "version": "1.1",
"generatedAt": "2026-05-12T22:53:33.094Z", "generatedAt": "2026-05-12T09:28:20.972Z",
"nodes": [ "nodes": [
{ {
"id": "contrat-social-medecine-corps-social", "id": "contrat-social-medecine-corps-social",

View File

@@ -1,21 +1,23 @@
--- ---
import InstaFeed from '../vue/InstaFeed.vue'; import InstaFeed from '../vue/InstaFeed.vue';
// V1.5-E : Behold remplacé par RSSHub self-host. InstaFeed lit désormais // Feed IDs Behold a remplir apres inscription Behold (voir docs/BEHOLD-SETUP.md)
// le journal unifié (PUBLIC_JOURNAL_URL → data.trans-former.fr/journal.json) const FEED_AEP = import.meta.env.PUBLIC_BEHOLD_AEP || 'PLACEHOLDER_AEP';
// agrégé par n8n depuis rss.trans-former.fr. Plus de feedId Behold à passer. const FEED_JULESNENY = import.meta.env.PUBLIC_BEHOLD_JULESNENY || 'PLACEHOLDER_JULESNENY';
--- ---
<div class="h-full overflow-y-auto"> <div class="h-full overflow-y-auto">
<InstaFeed <InstaFeed
client:visible client:visible
account="aep.politique" feedId={FEED_AEP}
account="@aep.politique"
accountUrl="https://www.instagram.com/aep.politique/" accountUrl="https://www.instagram.com/aep.politique/"
fallbackBio="Carrousels manifeste AEP ; pensee politique eco-architecture" fallbackBio="Carrousels manifeste AEP ; pensee politique eco-architecture"
/> />
<InstaFeed <InstaFeed
client:visible client:visible
account="julesneny" feedId={FEED_JULESNENY}
account="@julesneny"
accountUrl="https://www.instagram.com/julesneny/" accountUrl="https://www.instagram.com/julesneny/"
fallbackBio="Peinture, poesie, Corse ; archives visuelles personnelles" fallbackBio="Peinture, poesie, Corse ; archives visuelles personnelles"
/> />

View File

@@ -1,80 +1,46 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
// V1.5-E : on consomme désormais le journal unifié agrégé par n8n interface BeholdPost {
// (sources RSSHub self-host → data.trans-former.fr/journal.json),
// au lieu de l'API Behold directe (rate-limit, plafond 6 posts gratuit).
interface JournalItem {
id: string;
platform: string;
date: string;
titre: string;
extrait?: string;
url: string;
thumbnail: string | null;
}
interface JournalPayload {
generatedAt: string;
items: JournalItem[];
}
interface InstaPost {
id: string; id: string;
permalink: string; permalink: string;
thumbnailUrl: string | null; mediaUrl: string;
caption: string; thumbnailUrl?: string;
caption?: string;
mediaType: 'IMAGE' | 'VIDEO' | 'CAROUSEL_ALBUM';
timestamp: string; timestamp: string;
} }
const props = defineProps<{ const props = defineProps<{
/** handle Instagram sans @ (ex: 'aep.politique', 'julesneny') — sert à filtrer le journal */ feedId: string;
account: string; account: string;
accountUrl: string; accountUrl: string;
fallbackBio?: string; fallbackBio?: string;
/** nombre max de posts affichés (défaut 6, parité avec ancien Behold) */
max?: number;
}>(); }>();
const posts = ref<InstaPost[]>([]); const posts = ref<BeholdPost[]>([]);
const loading = ref(true); const loading = ref(true);
const error = ref<string | null>(null); const error = ref<string | null>(null);
const JOURNAL_URL = const isPlaceholder = (id: string) => !id || id.startsWith('PLACEHOLDER_');
(import.meta as unknown as { env: Record<string, string | undefined> }).env
.PUBLIC_JOURNAL_URL || 'https://data.trans-former.fr/journal.json';
const accountHandle = (props.account || '').replace(/^@/, '').toLowerCase();
const limit = props.max ?? 6;
onMounted(async () => { onMounted(async () => {
if (isPlaceholder(props.feedId)) {
loading.value = false;
error.value = 'no-feed-id';
return;
}
try { try {
const controller = new AbortController(); const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 8000); const timeoutId = setTimeout(() => controller.abort(), 5000);
const res = await fetch(JOURNAL_URL, { const res = await fetch(`https://feeds.behold.so/${props.feedId}`, {
signal: controller.signal, signal: controller.signal,
cache: 'no-store',
}); });
clearTimeout(timeoutId); clearTimeout(timeoutId);
if (!res.ok) throw new Error(`Journal returned ${res.status}`); if (!res.ok) throw new Error(`Behold returned ${res.status}`);
const data = (await res.json()) as JournalPayload; const data = await res.json();
const all = Array.isArray(data?.items) ? data.items : []; const items: BeholdPost[] = Array.isArray(data) ? data : (data.posts ?? []);
posts.value = all posts.value = items.slice(0, 6);
.filter(
(it) =>
it.platform === 'instagram' &&
typeof it.url === 'string' &&
it.url.toLowerCase().includes(`/${accountHandle}`),
)
.slice(0, limit)
.map((it) => ({
id: it.id,
permalink: it.url,
thumbnailUrl: it.thumbnail ?? null,
caption: it.titre || it.extrait || '',
timestamp: it.date,
}));
if (!posts.value.length) error.value = 'no-posts';
} catch (e) { } catch (e) {
error.value = (e as Error).message || 'fetch-error'; error.value = (e as Error).message || 'fetch-error';
} finally { } finally {
@@ -105,28 +71,24 @@ onMounted(async () => {
/> />
</div> </div>
<div v-else-if="posts.length" class="grid grid-cols-2 gap-1 p-1"> <div
v-else-if="posts.length"
class="grid grid-cols-2 gap-1 p-1"
>
<a <a
v-for="post in posts" v-for="post in posts"
:key="post.id" :key="post.id"
:href="post.permalink" :href="post.permalink"
target="_blank" target="_blank"
rel="noopener" rel="noopener"
class="block aspect-square overflow-hidden group bg-neutral-100" class="block aspect-square overflow-hidden group"
> >
<img <img
v-if="post.thumbnailUrl" :src="post.thumbnailUrl || post.mediaUrl"
:src="post.thumbnailUrl"
:alt="post.caption?.slice(0, 80) || account" :alt="post.caption?.slice(0, 80) || account"
loading="lazy" loading="lazy"
class="w-full h-full object-cover group-hover:scale-105 transition-transform" class="w-full h-full object-cover group-hover:scale-105 transition-transform"
/> />
<span
v-else
class="w-full h-full flex items-center justify-center text-[10px] text-neutral-400 p-2 text-center"
>
{{ post.caption?.slice(0, 60) || account }}
</span>
</a> </a>
</div> </div>

196
src/pages/api/aep-perso.ts Normal file
View File

@@ -0,0 +1,196 @@
import type { APIRoute } from 'astro'
export const prerender = false
const KIT_API_BASE = 'https://api.kit.com/v4'
const TAG_NAME = 'AEP - sans perso'
function htmlPage(title: string, heading: string, message: string): string {
return `<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${title} — trans-former.fr</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-neutral-50 text-neutral-900 min-h-screen flex items-center justify-center p-6">
<main class="max-w-md w-full bg-white rounded-xl shadow-sm border border-neutral-200 p-8 text-center">
<h1 class="text-2xl font-semibold mb-4">${heading}</h1>
<p class="text-neutral-600 leading-relaxed">${message}</p>
<a href="https://www.trans-former.fr"
class="mt-6 inline-block text-sm text-neutral-500 underline underline-offset-2 hover:text-neutral-900">
&larr; Retour sur trans-former.fr
</a>
</main>
</body>
</html>`
}
async function getSubscriberByEmail(email: string, apiKey: string): Promise<string | null> {
const url = `${KIT_API_BASE}/subscribers?email_address=${encodeURIComponent(email)}`
const res = await fetch(url, {
headers: { 'X-Kit-Api-Key': apiKey },
signal: AbortSignal.timeout(10000),
})
if (!res.ok) return null
const data = await res.json()
if (!data?.subscribers?.length) return null
return String(data.subscribers[0].id)
}
async function getTagId(apiKey: string): Promise<number | null> {
const url = `${KIT_API_BASE}/tags`
const res = await fetch(url, {
headers: { 'X-Kit-Api-Key': apiKey },
signal: AbortSignal.timeout(10000),
})
if (!res.ok) return null
const data = await res.json()
const tag = data?.tags?.find((t: any) => t.name === TAG_NAME)
return tag?.id ?? null
}
async function tagSubscriber(subscriberId: string, tagId: number, apiKey: string): Promise<boolean> {
const url = `${KIT_API_BASE}/tags/${tagId}/subscribers`
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Kit-Api-Key': apiKey,
},
body: JSON.stringify({ id: subscriberId }),
signal: AbortSignal.timeout(10000),
})
return res.ok || res.status === 409
}
async function untagSubscriber(subscriberId: string, tagId: number, apiKey: string): Promise<boolean> {
const url = `${KIT_API_BASE}/tags/${tagId}/subscribers/${subscriberId}`
const res = await fetch(url, {
method: 'DELETE',
headers: { 'X-Kit-Api-Key': apiKey },
signal: AbortSignal.timeout(10000),
})
return res.ok || res.status === 404
}
export const GET: APIRoute = async ({ url }) => {
const KIT_API_KEY = import.meta.env.KIT_API_SECRET_V4
if (!KIT_API_KEY) {
return new Response(htmlPage(
'Erreur',
'Configuration manquante',
'Le service de désinscription n\'est pas configuré. Contacte-moi à <a href="mailto:julesneny8@gmail.com" class="underline">julesneny8@gmail.com</a>.'
), {
status: 500,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
const email = (url.searchParams.get('email') || '').trim().toLowerCase()
const action = url.searchParams.get('action')
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return new Response(htmlPage(
'Lien invalide',
'Lien invalide',
'Le lien que tu as suivi est incomplet ou mal formé. Essaye de copier-coller l\'URL complète depuis l\'email.'
), {
status: 400,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
if (action !== 'unsubscribe' && action !== 'resubscribe') {
return new Response(htmlPage(
'Action inconnue',
'Action inconnue',
'Le lien que tu as suivi ne correspond à aucune action connue.'
), {
status: 400,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
try {
const subscriberId = await getSubscriberByEmail(email, KIT_API_KEY)
if (!subscriberId) {
return new Response(htmlPage(
'Email inconnu',
'Email inconnu',
'Cet email n\'est pas abonné à la newsletter. Si tu penses qu\'il s\'agit d\'une erreur, écris-moi à <a href="mailto:julesneny8@gmail.com" class="underline">julesneny8@gmail.com</a>.'
), {
status: 404,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
const tagId = await getTagId(KIT_API_KEY)
if (!tagId) {
return new Response(htmlPage(
'Erreur',
'Configuration manquante',
'Le tag de désinscription est introuvable. Contacte-moi à <a href="mailto:julesneny8@gmail.com" class="underline">julesneny8@gmail.com</a>.'
), {
status: 500,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
if (action === 'unsubscribe') {
const result = await tagSubscriber(subscriberId, tagId, KIT_API_KEY)
if (!result) {
return new Response(htmlPage(
'Erreur',
'Erreur technique',
'Une erreur est survenue lors de la désinscription. Réessaie ou écris-moi à <a href="mailto:julesneny8@gmail.com" class="underline">julesneny8@gmail.com</a>.'
), {
status: 500,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
return new Response(htmlPage(
'Désinscription réussie',
'Tu es désinscrit·e',
'Tu ne recevras plus les lettres «&nbsp;perso&nbsp;» de l\'infolettre <em>Architecture d\'Écologie Politique</em>. Tu continues à recevoir les textes de fond.<br><br>Si tu changes d\'avis, un lien de réabonnement est disponible dans chaque email de fond.'
), {
status: 200,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
if (action === 'resubscribe') {
const result = await untagSubscriber(subscriberId, tagId, KIT_API_KEY)
if (!result) {
return new Response(htmlPage(
'Erreur',
'Erreur technique',
'Une erreur est survenue lors du réabonnement. Réessaie ou écris-moi à <a href="mailto:julesneny8@gmail.com" class="underline">julesneny8@gmail.com</a>.'
), {
status: 500,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
return new Response(htmlPage(
'Réabonnement réussi',
'Tu es de nouveau abonné·e',
'Tu recevras à nouveau les lettres «&nbsp;perso&nbsp;» de l\'infolettre <em>Architecture d\'Écologie Politique</em>. Merci de ton intérêt !'
), {
status: 200,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
return new Response(null, { status: 400 })
} catch (e) {
return new Response(htmlPage(
'Erreur',
'Erreur technique',
'Une erreur inattendue est survenue. Réessaie ou écris-moi à <a href="mailto:julesneny8@gmail.com" class="underline">julesneny8@gmail.com</a>.'
), {
status: 500,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
}