FB API linked

This commit is contained in:
2026-03-23 00:36:51 +01:00
parent 7d50f0c939
commit 8a932470ea
5 changed files with 341 additions and 123 deletions
+4 -1
View File
@@ -26,4 +26,7 @@ dist-ssr
# Media files # Media files
*.webp *.webp
*.mp4 *.mp4
*.jpg *.jpg
.env
+4
View File
@@ -9,6 +9,10 @@
href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap"
rel="stylesheet" rel="stylesheet"
/> />
<meta
name="facebook-domain-verification"
content="3jesovm4ls6vp30v1j47dxzxdc9kvi"
/>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+270 -116
View File
@@ -1,76 +1,218 @@
import { useState } from "react"; import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion"; import { motion, AnimatePresence } from "framer-motion";
// Modèle de données pour un post Facebook // Modèle de données pour un post Facebook
interface FacebookPost { interface FacebookPost {
id: number; id: number | string;
date: string; date: string;
content: string; content: string;
imageSrc: string; imageSrc: string;
link: string; link: string;
} }
// Fausses données (en attendant la connexion API ou le widget) // Interface pour la réponse de l'API Facebook
const mockPosts: FacebookPost[] = [ interface FacebookApiPost {
{ id: string;
id: 1, created_time: string;
date: "Il y a 2 jours", message?: string;
content: full_picture?: string;
"Un immense merci aux bénévoles présents ce matin pour la préparation des 50 nouveaux colis à destination de l'Ukraine ! 🌻📦", permalink_url: string;
imageSrc: "/historique/pam-aerien.webp", // Mets une vraie image de test attachments?: {
link: "https://www.facebook.com", data: Array<{
}, title?: string;
{ media?: {
id: 2, image?: { src: string };
date: "La semaine dernière", };
content: }>;
"Retour en images sur notre superbe atelier de peinture traditionnelle de Pâques (Pysanka). Merci aux enfants pour leur créativité ! 🎨", };
imageSrc: "/historique/premier-evenement.webp", }
link: "https://www.facebook.com",
}, // Interface pour la récupération des comptes (pages)
{ interface FacebookAccountResponse {
id: 3, data: Array<{
date: "Il y a 2 semaines", id: string;
content: access_token: string;
"Le camion est bien arrivé ! La génératrice a pu être livrée à l'hôpital de Kharkiv. Merci à tous nos donateurs. 💙💛", }>;
imageSrc: "/historique/dernier-evenement.webp", }
link: "https://www.facebook.com",
}, // Composant Spinner
{ const LoadingSpinner = () => (
id: 4, <div className="flex items-center justify-center h-full w-full">
date: "Il y a 3 semaines", <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
content: </div>
"Réunion très productive avec la mairie pour préparer l'année à venir. De beaux projets en perspective ! 🏛️🤝", );
imageSrc: "/historique/signature-statuts.webp",
link: "https://www.facebook.com", const ErrorMessage = () => (
}, <div className="flex flex-col items-center justify-center h-full w-full text-primary font-medium p-6 text-center">
{ <p className="mb-6 italic text-lg text-site-text/70">
id: 5, Suivez nos dernières actions directement sur Facebook.
date: "Il y a 1 mois", </p>
content: <a
"Collecte de vêtements chauds terminée. Merci à tous les donateurs, le camion part demain ! 🚛❄️", href="https://www.facebook.com/profile.php?id=819434444588954"
imageSrc: "/historique/arrivee.webp", target="_blank"
link: "https://www.facebook.com", rel="noopener noreferrer"
}, className="px-8 py-3 rounded-full bg-primary text-white font-bold uppercase tracking-wider hover:bg-heading-accent transition-all shadow-lg text-sm"
{ >
id: 6, Voir la page Facebook
date: "Il y a 1 mois", </a>
content: </div>
"Petit souvenir de notre stand au forum des associations. On a hâte de vous retrouver ! 👋", );
imageSrc: "/hero-section/a-propos.webp",
link: "https://www.facebook.com", // Utilitaire pour formater la date (ex: "Il y a 2 jours")
}, const timeAgo = (dateString: string) => {
]; const date = new Date(dateString);
const now = new Date();
const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (seconds < 60) return "À l'instant";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `Il y a ${minutes} minute${minutes > 1 ? "s" : ""}`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `Il y a ${hours} heure${hours > 1 ? "s" : ""}`;
const days = Math.floor(hours / 24);
if (days < 30) return `Il y a ${days} jour${days > 1 ? "s" : ""}`;
const months = Math.floor(days / 30);
if (months < 12) return `Il y a ${months} mois`;
return `Il y a ${Math.floor(days / 365)} an(s)`;
};
export default function FacebookCarousel() { export default function FacebookCarousel() {
const [posts, setPosts] = useState<FacebookPost[]>([]);
const [currentIndex, setCurrentIndex] = useState(0); const [currentIndex, setCurrentIndex] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [isPaused, setIsPaused] = useState(false);
// Gestion du défilement automatique
useEffect(() => {
// On n'active pas l'autoplay si : chargement, erreur, pas assez de posts, ou pause (souris dessus)
if (loading || error || posts.length < 2 || isPaused) return;
const interval = setInterval(() => {
setCurrentIndex((prev) => (prev === posts.length - 1 ? 0 : prev + 1));
}, 5000); // Change toutes les 5 secondes
return () => clearInterval(interval);
}, [loading, error, posts.length, isPaused]);
useEffect(() => {
const fetchFacebookPosts = async () => {
const pageId = import.meta.env.VITE_FACEBOOK_PAGE_ID;
const accessToken = import.meta.env.VITE_FACEBOOK_ACCESS_TOKEN;
if (!accessToken || accessToken.includes("ton_token")) {
setLoading(false);
setError(true);
return;
}
const baseUrl = import.meta.env.DEV
? "/api/facebook"
: "https://graph.facebook.com/v19.0";
const fields =
"id,created_time,message,full_picture,permalink_url,attachments";
try {
let url = `${baseUrl}/${pageId}/posts?fields=${fields}&limit=6&access_token=${accessToken}`;
// 'credentials: omit' évite d'envoyer des cookies tiers, ce qui réduit les blocages CORS/Pistage
let response = await fetch(url, {
mode: "cors",
credentials: "omit",
});
let data = await response.json();
// --- MODE DEV UNIQUEMENT : Récupération automatique du Page Token ---
// Si l'API rejette le token (Code 190 = Invalid OAuth, souvent car c'est un User Token au lieu d'un Page Token)
if (
import.meta.env.DEV &&
data.error &&
(data.error.code === 190 || data.error.code === 100)
) {
console.log(
"🔄 Token rejeté. Tentative de récupération du Page Token via l'API...",
);
try {
const accountsRes = await fetch(
`${baseUrl}/me/accounts?access_token=${accessToken}`,
);
const accountsData =
(await accountsRes.json()) as FacebookAccountResponse;
const pageData = accountsData.data?.find((p) => p.id === pageId);
if (pageData?.access_token) {
console.log(
"%c✅ SUCCÈS ! Voici le TOKEN DE PAGE à mettre dans votre .env :",
"color: green; font-weight: bold; font-size: 12px;",
);
console.log(pageData.access_token);
// On réessaie la requête avec le bon token
url = `${baseUrl}/${pageId}/posts?fields=${fields}&limit=6&access_token=${pageData.access_token}`;
response = await fetch(url);
data = await response.json();
}
} catch {
console.warn(
"Impossible de récupérer le Page Token automatiquement.",
);
}
}
if (!response.ok || data.error) {
console.error(
"Erreur API Facebook:",
data.error || response.statusText,
);
throw new Error("API Error");
}
if (data.data && data.data.length > 0) {
const formattedPosts = (data.data as FacebookApiPost[]).map(
(post) => {
let imageSrc =
post.full_picture ||
post.attachments?.data[0]?.media?.image?.src ||
"/logo.png";
// En DEV : On passe par le proxy pour éviter le blocage "Tracking Protection" du navigateur
if (import.meta.env.DEV && imageSrc.startsWith("http")) {
imageSrc = `/api/proxy-image?url=${encodeURIComponent(imageSrc)}`;
}
return {
id: post.id,
date: timeAgo(post.created_time),
content:
post.message ||
post.attachments?.data[0]?.title ||
"Découvrez ce contenu directement sur notre page Facebook.",
imageSrc,
link: post.permalink_url,
};
},
);
if (formattedPosts.length > 0) {
setPosts(formattedPosts);
}
}
} catch {
setError(true);
} finally {
setLoading(false);
}
};
fetchFacebookPosts();
}, []);
const nextPost = () => { const nextPost = () => {
setCurrentIndex((prev) => (prev === mockPosts.length - 1 ? 0 : prev + 1)); setCurrentIndex((prev) => (prev === posts.length - 1 ? 0 : prev + 1));
}; };
const prevPost = () => { const prevPost = () => {
setCurrentIndex((prev) => (prev === 0 ? mockPosts.length - 1 : prev - 1)); setCurrentIndex((prev) => (prev === 0 ? posts.length - 1 : prev - 1));
}; };
return ( return (
@@ -87,73 +229,85 @@ export default function FacebookCarousel() {
</div> </div>
{/* Flèches de navigation */} {/* Flèches de navigation */}
<div className="flex gap-4"> {posts.length > 0 && !loading && !error && (
<button <div className="flex gap-4">
onClick={prevPost} <button
className="w-12 h-12 rounded-full border-2 border-primary text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors" onClick={prevPost}
aria-label="Précédent" className="w-12 h-12 rounded-full border-2 border-primary text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors"
> aria-label="Précédent"
← >
</button> ←
<button </button>
onClick={nextPost} <button
className="w-12 h-12 rounded-full bg-primary text-white flex items-center justify-center hover:bg-hover-nav hover:text-primary transition-colors shadow-md" onClick={nextPost}
aria-label="Suivant" className="w-12 h-12 rounded-full bg-primary text-white flex items-center justify-center hover:bg-hover-nav hover:text-primary transition-colors shadow-md"
> aria-label="Suivant"
→ >
</button> →
</div> </button>
</div>
)}
</div> </div>
{/* Zone du Carrousel */} {/* Zone du Carrousel */}
<div className="relative h-112.5 w-full overflow-hidden rounded-[30px] bg-bg-2 shadow-inner border border-primary/10"> <div
<AnimatePresence mode="wait"> className="relative h-112.5 w-full overflow-hidden rounded-[30px] bg-bg-2 shadow-inner border border-primary/10"
<motion.div onMouseEnter={() => setIsPaused(true)}
key={currentIndex} onMouseLeave={() => setIsPaused(false)}
initial={{ opacity: 0, x: 50 }} >
animate={{ opacity: 1, x: 0 }} {loading ? (
exit={{ opacity: 0, x: -50 }} <LoadingSpinner />
transition={{ duration: 0.3, ease: "easeInOut" }} ) : error || posts.length === 0 ? (
className="absolute inset-0 flex flex-col md:flex-row h-full" <ErrorMessage />
> ) : (
{/* Image du Post */} <AnimatePresence mode="wait">
<div className="w-full md:w-1/2 h-48 md:h-full overflow-hidden"> <motion.div
<img key={currentIndex}
src={mockPosts[currentIndex].imageSrc} initial={{ opacity: 0, x: 50 }}
alt="Illustration du post" animate={{ opacity: 1, x: 0 }}
className="w-full h-full object-cover" exit={{ opacity: 0, x: -50 }}
/> transition={{ duration: 0.3, ease: "easeInOut" }}
</div> className="absolute inset-0 flex flex-col md:flex-row h-full"
>
{/* Contenu du Post */} {/* Image du Post */}
<div className="w-full md:w-1/2 h-full flex flex-col justify-center p-8 md:p-12 bg-white"> <div className="w-full md:w-1/2 h-48 md:h-full overflow-hidden">
<div className="flex items-center gap-3 mb-6"> <img
<div className="w-10 h-10 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold"> src={posts[currentIndex].imageSrc}
f alt="Illustration du post"
</div> className="w-full h-full object-cover"
<div> />
<h3 className="font-bold text-primary">Cœur UA PAM</h3>
<span className="text-sm text-site-text/70">
{mockPosts[currentIndex].date}
</span>
</div>
</div> </div>
<p className="text-lg text-site-text leading-relaxed mb-8 italic"> {/* Contenu du Post */}
"{mockPosts[currentIndex].content}" <div className="w-full md:w-1/2 h-full flex flex-col justify-center p-8 md:p-12 bg-white">
</p> <div className="flex items-center gap-3 mb-6">
<div className="w-10 h-10 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold">
f
</div>
<div>
<h3 className="font-bold text-primary">Cœur UA PAM</h3>
<span className="text-sm text-site-text/70">
{posts[currentIndex].date}
</span>
</div>
</div>
<a <p className="text-lg text-site-text leading-relaxed mb-8 italic line-clamp-6">
href={mockPosts[currentIndex].link} "{posts[currentIndex].content}"
target="_blank" </p>
rel="noopener noreferrer"
className="inline-block self-start px-6 py-3 rounded-full bg-bg-2 text-primary font-bold hover:bg-primary hover:text-white transition-colors border border-primary/10" <a
> href={posts[currentIndex].link}
Voir sur Facebook target="_blank"
</a> rel="noopener noreferrer"
</div> className="inline-block self-start px-6 py-3 rounded-full bg-bg-2 text-primary font-bold hover:bg-primary hover:text-white transition-colors border border-primary/10"
</motion.div> >
</AnimatePresence> Voir sur Facebook
</a>
</div>
</motion.div>
</AnimatePresence>
)}
</div> </div>
</div> </div>
); );
+2 -2
View File
@@ -167,11 +167,11 @@ const Historic = () => {
)} )}
</AnimatedContent> </AnimatedContent>
{/* <AnimatedContent distance={40} direction="vertical" threshold={0.2}> <AnimatedContent distance={40} direction="vertical" threshold={0.2}>
<div className="w-full"> <div className="w-full">
<FacebookCarousel /> <FacebookCarousel />
</div> </div>
</AnimatedContent> */} </AnimatedContent>
</div> </div>
); );
}; };
+61 -4
View File
@@ -1,7 +1,64 @@
import { defineConfig } from 'vite' import { defineConfig } from "vite";
import react from '@vitejs/plugin-react' import react from "@vitejs/plugin-react";
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [
}) react(),
// Middleware personnalisé pour le proxy d'images (plus robuste que server.proxy)
{
name: "image-proxy",
configureServer(server) {
server.middlewares.use("/api/proxy-image", async (req, res) => {
try {
// req.url contient uniquement la partie après /api/proxy-image (ex: /?url=...)
const urlObj = new URL(req.url || "", `http://${req.headers.host}`);
const targetUrl = urlObj.searchParams.get("url");
if (!targetUrl) {
res.statusCode = 400;
res.end("URL missing");
return;
}
// On récupère l'image avec un User-Agent "normal" pour éviter les blocages 403/404
const response = await fetch(targetUrl, {
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
},
});
if (!response.ok) {
res.statusCode = response.status;
res.end(response.statusText);
return;
}
// On transmet le type de contenu (ex: image/jpeg)
const contentType = response.headers.get("content-type");
if (contentType) res.setHeader("Content-Type", contentType);
// On renvoie les données binaires
const arrayBuffer = await response.arrayBuffer();
res.write(Buffer.from(arrayBuffer));
res.end();
} catch (e) {
console.error("Proxy error:", e);
res.statusCode = 500;
res.end("Internal Server Error");
}
});
},
},
],
server: {
proxy: {
"/api/facebook": {
target: "https://graph.facebook.com/v19.0",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api\/facebook/, ""),
},
},
},
});