Compare commits
14 Commits
v1.8.3
...
7615ec670e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7615ec670e
|
||
|
|
40cfff683d
|
||
|
|
bb52782226
|
||
|
|
6a70274623
|
||
|
|
aabc615b89
|
||
|
|
f9b202375f
|
||
|
|
6398965f16
|
||
|
|
9e9b1db012
|
||
|
|
62bf03d07a
|
||
|
|
c83ba6eb7d
|
||
|
|
05a05a1940
|
||
|
|
7c065a2fb9
|
||
|
|
001cdaff8f
|
||
|
|
0eb940c5ce
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@memegoat/backend",
|
||||
"version": "1.8.3",
|
||||
"version": "1.9.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { forwardRef, Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { ContentsModule } from "../contents/contents.module";
|
||||
import { RealtimeModule } from "../realtime/realtime.module";
|
||||
import { S3Module } from "../s3/s3.module";
|
||||
import { CommentsController } from "./comments.controller";
|
||||
@@ -8,7 +9,12 @@ import { CommentLikesRepository } from "./repositories/comment-likes.repository"
|
||||
import { CommentsRepository } from "./repositories/comments.repository";
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, S3Module, RealtimeModule],
|
||||
imports: [
|
||||
AuthModule,
|
||||
S3Module,
|
||||
RealtimeModule,
|
||||
forwardRef(() => ContentsModule),
|
||||
],
|
||||
controllers: [CommentsController],
|
||||
providers: [CommentsService, CommentsRepository, CommentLikesRepository],
|
||||
exports: [CommentsService],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ForbiddenException, NotFoundException } from "@nestjs/common";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { ContentsRepository } from "../contents/repositories/contents.repository";
|
||||
import { EventsGateway } from "../realtime/events.gateway";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
import { CommentsService } from "./comments.service";
|
||||
@@ -25,12 +26,17 @@ describe("CommentsService", () => {
|
||||
isLikedByUser: jest.fn(),
|
||||
};
|
||||
|
||||
const mockContentsRepository = {
|
||||
findOne: jest.fn(),
|
||||
};
|
||||
|
||||
const mockS3Service = {
|
||||
getPublicUrl: jest.fn(),
|
||||
};
|
||||
|
||||
const mockEventsGateway = {
|
||||
sendToContent: jest.fn(),
|
||||
sendToUser: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -40,6 +46,7 @@ describe("CommentsService", () => {
|
||||
CommentsService,
|
||||
{ provide: CommentsRepository, useValue: mockCommentsRepository },
|
||||
{ provide: CommentLikesRepository, useValue: mockCommentLikesRepository },
|
||||
{ provide: ContentsRepository, useValue: mockContentsRepository },
|
||||
{ provide: S3Service, useValue: mockS3Service },
|
||||
{ provide: EventsGateway, useValue: mockEventsGateway },
|
||||
],
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import {
|
||||
ForbiddenException,
|
||||
forwardRef,
|
||||
Inject,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { ContentsRepository } from "../contents/repositories/contents.repository";
|
||||
import { EventsGateway } from "../realtime/events.gateway";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
import type { CreateCommentDto } from "./dto/create-comment.dto";
|
||||
@@ -14,6 +17,8 @@ export class CommentsService {
|
||||
constructor(
|
||||
private readonly commentsRepository: CommentsRepository,
|
||||
private readonly commentLikesRepository: CommentLikesRepository,
|
||||
@Inject(forwardRef(() => ContentsRepository))
|
||||
private readonly contentsRepository: ContentsRepository,
|
||||
private readonly s3Service: S3Service,
|
||||
private readonly eventsGateway: EventsGateway,
|
||||
) {}
|
||||
@@ -28,10 +33,48 @@ export class CommentsService {
|
||||
|
||||
// Récupérer le commentaire avec les infos utilisateur pour le WebSocket
|
||||
const enrichedComment = await this.findOneEnriched(comment.id, userId);
|
||||
if (!enrichedComment) return null;
|
||||
|
||||
// Notifier les autres utilisateurs sur ce contenu
|
||||
// Notifier les autres utilisateurs sur ce contenu (room de contenu)
|
||||
this.eventsGateway.sendToContent(contentId, "new_comment", enrichedComment);
|
||||
|
||||
// Notifications ciblées
|
||||
try {
|
||||
// 1. Notifier l'auteur du post
|
||||
const content = await this.contentsRepository.findOne(contentId);
|
||||
if (content && content.userId !== userId) {
|
||||
this.eventsGateway.sendToUser(content.userId, "notification", {
|
||||
type: "comment",
|
||||
userId: userId,
|
||||
username: enrichedComment.user.username,
|
||||
contentId: contentId,
|
||||
commentId: comment.id,
|
||||
text: `a commenté votre post : "${dto.text.substring(0, 30)}${dto.text.length > 30 ? "..." : ""}"`,
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Si c'est une réponse, notifier l'auteur du commentaire parent
|
||||
if (dto.parentId) {
|
||||
const parentComment = await this.commentsRepository.findOne(dto.parentId);
|
||||
if (
|
||||
parentComment &&
|
||||
parentComment.userId !== userId &&
|
||||
(!content || parentComment.userId !== content.userId)
|
||||
) {
|
||||
this.eventsGateway.sendToUser(parentComment.userId, "notification", {
|
||||
type: "reply",
|
||||
userId: userId,
|
||||
username: enrichedComment.user.username,
|
||||
contentId: contentId,
|
||||
commentId: comment.id,
|
||||
text: `a répondu à votre commentaire : "${dto.text.substring(0, 30)}${dto.text.length > 30 ? "..." : ""}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to send notification:", error);
|
||||
}
|
||||
|
||||
return enrichedComment;
|
||||
}
|
||||
|
||||
@@ -105,6 +148,23 @@ export class CommentsService {
|
||||
throw new NotFoundException("Comment not found");
|
||||
}
|
||||
await this.commentLikesRepository.addLike(commentId, userId);
|
||||
|
||||
// Notifier l'auteur du commentaire
|
||||
if (comment.userId !== userId) {
|
||||
try {
|
||||
const liker = await this.findOneEnriched(commentId, userId);
|
||||
this.eventsGateway.sendToUser(comment.userId, "notification", {
|
||||
type: "like_comment",
|
||||
userId: userId,
|
||||
username: liker?.user.username,
|
||||
contentId: comment.contentId,
|
||||
commentId: commentId,
|
||||
text: "a aimé votre commentaire",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to send like notification:", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async unlike(userId: string, commentId: string) {
|
||||
|
||||
@@ -41,7 +41,9 @@ export const pgpEncrypted = customType<{ data: string; driverData: Buffer }>({
|
||||
export function withAutomaticPgpDecrypt<T extends AnyPgColumn>(column: T): T {
|
||||
const originalGetSQL = column.getSQL.bind(column);
|
||||
column.getSQL = () =>
|
||||
sql`pgp_sym_decrypt(${originalGetSQL()}, ${getPgpKey()})`.mapWith(column);
|
||||
sql`pgp_sym_decrypt(${originalGetSQL()}, ${getPgpKey()})::text`.mapWith(
|
||||
column,
|
||||
);
|
||||
return column;
|
||||
}
|
||||
|
||||
@@ -59,5 +61,7 @@ export function pgpSymDecrypt(
|
||||
column: AnyPgColumn,
|
||||
key: string | SQL,
|
||||
): SQL<string> {
|
||||
return sql`pgp_sym_decrypt(${column}, ${key})`.mapWith(column) as SQL<string>;
|
||||
return sql`pgp_sym_decrypt(${column}, ${key})::text`.mapWith(
|
||||
column,
|
||||
) as SQL<string>;
|
||||
}
|
||||
|
||||
@@ -16,9 +16,39 @@ import { getSessionOptions, SessionData } from "../auth/session.config";
|
||||
import { JwtService } from "../crypto/services/jwt.service";
|
||||
|
||||
@WebSocketGateway({
|
||||
transports: ["websocket"],
|
||||
cors: {
|
||||
origin: "*",
|
||||
origin: (
|
||||
origin: string,
|
||||
callback: (err: Error | null, allow?: boolean) => void,
|
||||
) => {
|
||||
// Autoriser si pas d'origine (ex: app mobile ou serveur à serveur)
|
||||
// ou si on est en développement local
|
||||
if (
|
||||
!origin ||
|
||||
origin.includes("localhost") ||
|
||||
origin.includes("127.0.0.1")
|
||||
) {
|
||||
callback(null, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// En production, on peut restreindre via une variable d'environnement
|
||||
const domainName = process.env.CORS_DOMAIN_NAME;
|
||||
if (!domainName || domainName === "*") {
|
||||
callback(null, true);
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedOrigins = domainName.split(",").map((o) => o.trim());
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
callback(new Error("Not allowed by CORS"));
|
||||
}
|
||||
},
|
||||
credentials: true,
|
||||
methods: ["GET", "POST"],
|
||||
},
|
||||
})
|
||||
export class EventsGateway
|
||||
@@ -28,6 +58,7 @@ export class EventsGateway
|
||||
server!: Server;
|
||||
|
||||
private readonly logger = new Logger(EventsGateway.name);
|
||||
private readonly onlineUsers = new Map<string, Set<string>>(); // userId -> Set of socketIds
|
||||
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
@@ -64,11 +95,23 @@ export class EventsGateway
|
||||
}
|
||||
|
||||
const payload = await this.jwtService.verifyJwt(session.accessToken);
|
||||
if (!payload.sub) {
|
||||
throw new Error("Invalid token payload: missing sub");
|
||||
}
|
||||
|
||||
client.data.user = payload;
|
||||
|
||||
// Rejoindre une room personnelle pour les notifications
|
||||
client.join(`user:${payload.sub}`);
|
||||
|
||||
// Gérer le statut en ligne
|
||||
const userId = payload.sub as string;
|
||||
if (!this.onlineUsers.has(userId)) {
|
||||
this.onlineUsers.set(userId, new Set());
|
||||
this.server.emit("user_status", { userId, status: "online" });
|
||||
}
|
||||
this.onlineUsers.get(userId)?.add(client.id);
|
||||
|
||||
this.logger.log(`Client connected: ${client.id} (User: ${payload.sub})`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Connection error for client ${client.id}: ${error}`);
|
||||
@@ -77,6 +120,15 @@ export class EventsGateway
|
||||
}
|
||||
|
||||
handleDisconnect(client: Socket) {
|
||||
const userId = client.data.user?.sub;
|
||||
if (userId && this.onlineUsers.has(userId)) {
|
||||
const sockets = this.onlineUsers.get(userId);
|
||||
sockets?.delete(client.id);
|
||||
if (sockets?.size === 0) {
|
||||
this.onlineUsers.delete(userId);
|
||||
this.server.emit("user_status", { userId, status: "offline" });
|
||||
}
|
||||
}
|
||||
this.logger.log(`Client disconnected: ${client.id}`);
|
||||
}
|
||||
|
||||
@@ -98,6 +150,31 @@ export class EventsGateway
|
||||
this.logger.log(`Client ${client.id} left content room: ${contentId}`);
|
||||
}
|
||||
|
||||
@SubscribeMessage("typing")
|
||||
handleTyping(
|
||||
@ConnectedSocket() client: Socket,
|
||||
@MessageBody() data: { recipientId: string; isTyping: boolean },
|
||||
) {
|
||||
const userId = client.data.user?.sub;
|
||||
if (!userId) return;
|
||||
|
||||
this.server.to(`user:${data.recipientId}`).emit("user_typing", {
|
||||
userId,
|
||||
isTyping: data.isTyping,
|
||||
});
|
||||
}
|
||||
|
||||
@SubscribeMessage("check_status")
|
||||
handleCheckStatus(
|
||||
@ConnectedSocket() _client: Socket,
|
||||
@MessageBody() userId: string,
|
||||
) {
|
||||
return {
|
||||
userId,
|
||||
status: this.onlineUsers.has(userId) ? "online" : "offline",
|
||||
};
|
||||
}
|
||||
|
||||
// Méthode utilitaire pour envoyer des messages à un utilisateur spécifique
|
||||
sendToUser(userId: string, event: string, data: any) {
|
||||
this.server.to(`user:${userId}`).emit(event, data);
|
||||
|
||||
@@ -131,6 +131,8 @@ services:
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-https://api.memegoat.fr}
|
||||
NEXT_PUBLIC_APP_URL: ${NEXT_PUBLIC_APP_URL:-https://memegoat.fr}
|
||||
NEXT_PUBLIC_CONTACT_EMAIL: ${MAIL_FROM:-noreply@memegoat.fr}
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || "https://memegoat.fr";
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "https://api.memegoat.fr";
|
||||
|
||||
const getHostname = (url: string) => {
|
||||
try {
|
||||
return new URL(url).hostname;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
};
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
reactCompiler: true,
|
||||
@@ -7,11 +18,11 @@ const nextConfig: NextConfig = {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "memegoat.fr",
|
||||
hostname: getHostname(appUrl),
|
||||
},
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "api.memegoat.fr",
|
||||
hostname: getHostname(apiUrl),
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@memegoat/frontend",
|
||||
"version": "1.8.3",
|
||||
"version": "1.9.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -63,7 +63,9 @@ export default function HelpPage() {
|
||||
<p className="text-muted-foreground">
|
||||
N'hésitez pas à nous contacter sur nos réseaux sociaux ou par email.
|
||||
</p>
|
||||
<p className="font-semibold text-primary">contact@memegoat.fr</p>
|
||||
<p className="font-semibold text-primary">
|
||||
{process.env.NEXT_PUBLIC_CONTACT_EMAIL || "contact@memegoat.fr"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import { fr } from "date-fns/locale";
|
||||
import { Search, Send, UserPlus, X } from "lucide-react";
|
||||
import { ArrowLeft, Search, Send, UserPlus, X } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import * as React from "react";
|
||||
@@ -32,8 +32,29 @@ export default function MessagesPage() {
|
||||
const [activeConv, setActiveConv] = React.useState<Conversation | null>(null);
|
||||
const [messages, setMessages] = React.useState<Message[]>([]);
|
||||
const [newMessage, setNewMessage] = React.useState("");
|
||||
const typingTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
const handleTyping = () => {
|
||||
if (!socket || !activeConv) return;
|
||||
|
||||
socket.emit("typing", {
|
||||
recipientId: activeConv.recipient.uuid,
|
||||
isTyping: true,
|
||||
});
|
||||
|
||||
if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
|
||||
|
||||
typingTimeoutRef.current = setTimeout(() => {
|
||||
socket.emit("typing", {
|
||||
recipientId: activeConv.recipient.uuid,
|
||||
isTyping: false,
|
||||
});
|
||||
}, 3000);
|
||||
};
|
||||
const [isLoadingConvs, setIsLoadingConvs] = React.useState(true);
|
||||
const [isLoadingMsgs, setIsLoadingMsgs] = React.useState(false);
|
||||
const [isOtherTyping, setIsOtherTyping] = React.useState(false);
|
||||
const [onlineUsers, setOnlineUsers] = React.useState<Set<string>>(new Set());
|
||||
|
||||
const [searchQuery, setSearchQuery] = React.useState("");
|
||||
const [searchResults, setSearchResults] = React.useState<User[]>([]);
|
||||
@@ -120,6 +141,7 @@ export default function MessagesPage() {
|
||||
(data: { conversationId: string; message: Message }) => {
|
||||
if (activeConv?.id === data.conversationId) {
|
||||
setMessages((prev) => [...prev, data.message]);
|
||||
setIsOtherTyping(false); // S'il a envoyé un message, il ne tape plus
|
||||
}
|
||||
// Mettre à jour la liste des conversations
|
||||
setConversations((prev) => {
|
||||
@@ -144,8 +166,28 @@ export default function MessagesPage() {
|
||||
},
|
||||
);
|
||||
|
||||
socket.on("user_status", (data: { userId: string; status: string }) => {
|
||||
setOnlineUsers((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (data.status === "online") {
|
||||
next.add(data.userId);
|
||||
} else {
|
||||
next.delete(data.userId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("user_typing", (data: { userId: string; isTyping: boolean }) => {
|
||||
if (activeConv?.recipient.uuid === data.userId) {
|
||||
setIsOtherTyping(data.isTyping);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.off("new_message");
|
||||
socket.off("user_status");
|
||||
socket.off("user_typing");
|
||||
};
|
||||
}
|
||||
}, [socket, activeConv]);
|
||||
@@ -196,7 +238,11 @@ export default function MessagesPage() {
|
||||
return (
|
||||
<div className="h-[calc(100vh-4rem)] flex overflow-hidden bg-white dark:bg-zinc-950">
|
||||
{/* Sidebar - Liste des conversations */}
|
||||
<div className="w-80 border-r flex flex-col">
|
||||
<div
|
||||
className={`w-full md:w-80 border-r flex flex-col ${
|
||||
activeConv ? "hidden md:flex" : "flex"
|
||||
}`}
|
||||
>
|
||||
<div className="p-4 border-b">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-bold">Messages</h2>
|
||||
@@ -336,14 +382,26 @@ export default function MessagesPage() {
|
||||
</div>
|
||||
|
||||
{/* Zone de chat */}
|
||||
<div className="flex-1 flex flex-col">
|
||||
<div
|
||||
className={`flex-1 flex flex-col ${
|
||||
!activeConv ? "hidden md:flex" : "flex"
|
||||
}`}
|
||||
>
|
||||
{activeConv ? (
|
||||
<>
|
||||
{/* Header */}
|
||||
<div className="p-4 border-b flex items-center justify-between">
|
||||
<div className="p-4 border-b flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="md:hidden rounded-full"
|
||||
onClick={() => setActiveConv(null)}
|
||||
>
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
<Link
|
||||
href={`/user/${activeConv.recipient.username}`}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity"
|
||||
className="flex-1 flex items-center gap-3 hover:opacity-80 transition-opacity"
|
||||
>
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={activeConv.recipient.avatarUrl} />
|
||||
@@ -355,7 +413,17 @@ export default function MessagesPage() {
|
||||
<h3 className="font-bold leading-none">
|
||||
{activeConv.recipient.displayName || activeConv.recipient.username}
|
||||
</h3>
|
||||
<span className="text-xs text-green-500 font-medium">En ligne</span>
|
||||
<span
|
||||
className={`text-xs font-medium ${
|
||||
onlineUsers.has(activeConv.recipient.uuid)
|
||||
? "text-green-500"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{onlineUsers.has(activeConv.recipient.uuid)
|
||||
? "En ligne"
|
||||
: "Hors ligne"}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
@@ -406,6 +474,17 @@ export default function MessagesPage() {
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{isOtherTyping && (
|
||||
<div className="flex justify-start">
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 p-3 rounded-2xl rounded-bl-none">
|
||||
<div className="flex gap-1">
|
||||
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce [animation-delay:-0.3s]" />
|
||||
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce [animation-delay:-0.15s]" />
|
||||
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
@@ -415,7 +494,10 @@ export default function MessagesPage() {
|
||||
<Input
|
||||
placeholder="Écrivez un message..."
|
||||
value={newMessage}
|
||||
onChange={(e) => setNewMessage(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setNewMessage(e.target.value);
|
||||
handleTyping();
|
||||
}}
|
||||
className="rounded-full px-4"
|
||||
/>
|
||||
<Button
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Ubuntu_Mono, Ubuntu_Sans } from "next/font/google";
|
||||
import { NotificationHandler } from "@/components/notification-handler";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { AudioProvider } from "@/providers/audio-provider";
|
||||
import { AuthProvider } from "@/providers/auth-provider";
|
||||
@@ -31,7 +32,7 @@ export const metadata: Metadata = {
|
||||
openGraph: {
|
||||
type: "website",
|
||||
locale: "fr_FR",
|
||||
url: "https://memegoat.local",
|
||||
url: "/",
|
||||
siteName: "MemeGoat",
|
||||
title: "MemeGoat | Partagez vos meilleurs mèmes",
|
||||
description: "La plateforme ultime pour les mèmes. Rejoignez le troupeau !",
|
||||
@@ -76,6 +77,7 @@ export default function RootLayout({
|
||||
<SocketProvider>
|
||||
<AudioProvider>
|
||||
{children}
|
||||
<NotificationHandler />
|
||||
<Toaster />
|
||||
</AudioProvider>
|
||||
</SocketProvider>
|
||||
|
||||
@@ -35,6 +35,7 @@ import { useAuth } from "@/providers/auth-provider";
|
||||
import { ContentService } from "@/services/content.service";
|
||||
import { FavoriteService } from "@/services/favorite.service";
|
||||
import type { Content } from "@/types/content";
|
||||
import { ShareDialog } from "./share-dialog";
|
||||
import { UserContentEditDialog } from "./user-content-edit-dialog";
|
||||
import { ViewCounter } from "./view-counter";
|
||||
|
||||
@@ -51,6 +52,7 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
const [isLiked, setIsLiked] = React.useState(content.isLiked || false);
|
||||
const [likesCount, setLikesCount] = React.useState(content.favoritesCount);
|
||||
const [editDialogOpen, setEditDialogOpen] = React.useState(false);
|
||||
const [shareDialogOpen, setShareDialogOpen] = React.useState(false);
|
||||
const [_reportDialogOpen, setReportDialogOpen] = React.useState(false);
|
||||
|
||||
const isAuthor = user?.uuid === content.authorId;
|
||||
@@ -190,7 +192,15 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => toast.success("Lien copié !")}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (!isAuthenticated) {
|
||||
toast.error("Connectez-vous pour partager");
|
||||
return;
|
||||
}
|
||||
setShareDialogOpen(true);
|
||||
}}
|
||||
>
|
||||
<Share2 className="h-4 w-4 mr-2" />
|
||||
Partager
|
||||
</DropdownMenuItem>
|
||||
@@ -263,10 +273,11 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(
|
||||
`${window.location.origin}/meme/${content.slug}`,
|
||||
);
|
||||
toast.success("Lien copié !");
|
||||
if (!isAuthenticated) {
|
||||
toast.error("Connectez-vous pour partager");
|
||||
return;
|
||||
}
|
||||
setShareDialogOpen(true);
|
||||
}}
|
||||
className="hover:text-muted-foreground"
|
||||
>
|
||||
@@ -322,6 +333,13 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
onOpenChange={setEditDialogOpen}
|
||||
onSuccess={() => onUpdate?.()}
|
||||
/>
|
||||
<ShareDialog
|
||||
contentId={content.id}
|
||||
contentTitle={content.title}
|
||||
contentUrl={`${typeof window !== "undefined" ? window.location.origin : ""}/meme/${content.slug}`}
|
||||
open={shareDialogOpen}
|
||||
onOpenChange={setShareDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
108
frontend/src/components/notification-handler.tsx
Normal file
108
frontend/src/components/notification-handler.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
"use client";
|
||||
|
||||
import { Bell, Heart, MessageCircle, Reply } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useSocket } from "@/providers/socket-provider";
|
||||
|
||||
interface NotificationData {
|
||||
type: "comment" | "reply" | "like_comment" | "message";
|
||||
userId: string;
|
||||
username: string;
|
||||
contentId?: string;
|
||||
commentId?: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export function NotificationHandler() {
|
||||
const { socket } = useSocket();
|
||||
const router = useRouter();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!socket) return;
|
||||
|
||||
const handleNotification = (data: NotificationData) => {
|
||||
// Ne pas afficher de toast si on est déjà sur la page des messages pour un nouveau message
|
||||
if (data.type === "message" && window.location.pathname === "/messages") {
|
||||
return;
|
||||
}
|
||||
|
||||
toast.custom(
|
||||
(t) => (
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-start gap-3 bg-white dark:bg-zinc-900 p-4 rounded-xl shadow-lg border border-zinc-200 dark:border-zinc-800 w-full max-w-sm cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors text-left"
|
||||
onClick={() => {
|
||||
toast.dismiss(t);
|
||||
if (data.type === "message") {
|
||||
router.push("/messages");
|
||||
} else if (data.contentId) {
|
||||
router.push(`/meme/${data.contentId}`);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="bg-primary/10 p-2 rounded-full shrink-0">
|
||||
{data.type === "comment" && (
|
||||
<MessageCircle className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
{data.type === "reply" && <Reply className="h-4 w-4 text-primary" />}
|
||||
{data.type === "like_comment" && (
|
||||
<Heart className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
{data.type === "message" && (
|
||||
<MessageCircle className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<p className="text-sm font-bold">@{data.username}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{data.text}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground p-1 rounded-full hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toast.dismiss(t);
|
||||
}}
|
||||
>
|
||||
<Bell className="h-3 w-3" />
|
||||
</button>
|
||||
</button>
|
||||
),
|
||||
{
|
||||
duration: 5000,
|
||||
position: "top-right",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
socket.on("notification", handleNotification);
|
||||
|
||||
// Aussi pour les nouveaux messages (si on veut un toast global)
|
||||
socket.on(
|
||||
"new_message",
|
||||
(data: { message: { text: string; sender?: { username: string } } }) => {
|
||||
if (window.location.pathname !== "/messages") {
|
||||
toast(
|
||||
`Nouveau message de @${data.message.sender?.username || "un membre"}`,
|
||||
{
|
||||
description: data.message.text.substring(0, 50),
|
||||
action: {
|
||||
label: "Voir",
|
||||
onClick: () => router.push("/messages"),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return () => {
|
||||
socket.off("notification");
|
||||
socket.off("new_message");
|
||||
};
|
||||
}, [socket, router]);
|
||||
|
||||
return null;
|
||||
}
|
||||
186
frontend/src/components/share-dialog.tsx
Normal file
186
frontend/src/components/share-dialog.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
"use client";
|
||||
|
||||
import { Search, Send, X } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { MessageService } from "@/services/message.service";
|
||||
import { UserService } from "@/services/user.service";
|
||||
import type { User } from "@/types/user";
|
||||
|
||||
interface ShareDialogProps {
|
||||
contentId: string;
|
||||
contentTitle: string;
|
||||
contentUrl: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ShareDialog({
|
||||
contentId,
|
||||
contentTitle,
|
||||
contentUrl: _unused, // Support legacy prop
|
||||
open,
|
||||
onOpenChange,
|
||||
}: ShareDialogProps) {
|
||||
const [searchQuery, setSearchQuery] = React.useState("");
|
||||
const [results, setResults] = React.useState<User[]>([]);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [sendingTo, setSendingTo] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) {
|
||||
setSearchQuery("");
|
||||
setResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchInitial = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Par défaut, montrer les conversations récentes ou suggérer des gens
|
||||
const recent = await UserService.search("");
|
||||
setResults(recent);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch users", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchInitial();
|
||||
}, [open]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (searchQuery.length < 2) return;
|
||||
|
||||
const timeout = setTimeout(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await UserService.search(searchQuery);
|
||||
setResults(data);
|
||||
} catch (error) {
|
||||
console.error("Search failed", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [searchQuery]);
|
||||
|
||||
const handleShare = async (user: User) => {
|
||||
setSendingTo(user.uuid);
|
||||
try {
|
||||
const shareUrl = `${window.location.origin}/meme/${contentId}`;
|
||||
await MessageService.sendMessage(
|
||||
user.uuid,
|
||||
`Regarde ce mème : ${contentTitle}\n${shareUrl}`,
|
||||
);
|
||||
toast.success(`Partagé avec @${user.username}`);
|
||||
onOpenChange(false);
|
||||
} catch (_error) {
|
||||
toast.error("Échec du partage");
|
||||
} finally {
|
||||
setSendingTo(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px] p-0 gap-0 overflow-hidden">
|
||||
<DialogHeader className="p-4 border-b">
|
||||
<DialogTitle>Partager avec</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="p-4 border-b">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Rechercher un membre..."
|
||||
className="pl-9 h-9"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSearchQuery("")}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-0.5 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-full"
|
||||
>
|
||||
<X className="h-3 w-3 text-muted-foreground" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ScrollArea className="h-[300px]">
|
||||
<div className="p-2 space-y-1">
|
||||
{isLoading && results.length === 0 ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
Chargement...
|
||||
</div>
|
||||
) : results.length === 0 ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
Aucun membre trouvé.
|
||||
</div>
|
||||
) : (
|
||||
results.map((user) => (
|
||||
<div
|
||||
key={user.uuid}
|
||||
className="flex items-center justify-between p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-900"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarImage src={user.avatarUrl} />
|
||||
<AvatarFallback>{user.username[0].toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-bold leading-none">
|
||||
{user.displayName || user.username}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
@{user.username}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={sendingTo === user.uuid ? "outline" : "default"}
|
||||
disabled={sendingTo !== null}
|
||||
onClick={() => handleShare(user)}
|
||||
className="h-8 px-4 rounded-full"
|
||||
>
|
||||
{sendingTo === user.uuid ? "Envoi..." : "Envoyer"}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="p-4 border-t bg-zinc-50 dark:bg-zinc-900/50">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-2 h-10 rounded-xl"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(
|
||||
`${window.location.origin}/meme/${contentId}`,
|
||||
);
|
||||
toast.success("Lien copié !");
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
Copier le lien
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -29,6 +29,7 @@ export function TwoFactorSetup() {
|
||||
const [secret, setSecret] = useState<string | null>(null);
|
||||
const [otpValue, setOtpValue] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isRevealed, setIsRevealed] = useState(false);
|
||||
|
||||
const handleSetup = async () => {
|
||||
setIsLoading(true);
|
||||
@@ -152,24 +153,59 @@ export function TwoFactorSetup() {
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col items-center gap-6">
|
||||
{qrCode && (
|
||||
<div className="bg-white p-4 rounded-xl border-4 border-zinc-100">
|
||||
<Image
|
||||
src={qrCode}
|
||||
alt="QR Code 2FA"
|
||||
width={192}
|
||||
height={192}
|
||||
className="w-48 h-48"
|
||||
unoptimized
|
||||
/>
|
||||
<div className="relative group">
|
||||
<div
|
||||
className={`bg-white p-4 rounded-xl border-4 border-zinc-100 transition-all duration-300 ${
|
||||
!isRevealed ? "blur-md select-none" : ""
|
||||
}`}
|
||||
>
|
||||
<Image
|
||||
src={qrCode}
|
||||
alt="QR Code 2FA"
|
||||
width={192}
|
||||
height={192}
|
||||
className="w-48 h-48"
|
||||
unoptimized
|
||||
/>
|
||||
</div>
|
||||
{!isRevealed && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setIsRevealed(true)}
|
||||
className="shadow-lg"
|
||||
>
|
||||
Afficher le QR Code
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="w-full space-y-2">
|
||||
<p className="text-sm font-medium text-center">
|
||||
Ou entrez ce code manuellement :
|
||||
</p>
|
||||
<code className="block p-2 bg-muted text-center rounded text-xs font-mono break-all">
|
||||
{secret}
|
||||
</code>
|
||||
<div className="relative group">
|
||||
<code
|
||||
className={`block p-2 bg-muted text-center rounded text-xs font-mono break-all transition-all duration-300 ${
|
||||
!isRevealed ? "blur-[3px] select-none" : ""
|
||||
}`}
|
||||
>
|
||||
{secret}
|
||||
</code>
|
||||
{!isRevealed && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsRevealed(true)}
|
||||
className="text-[10px] font-bold uppercase tracking-wider text-primary hover:underline"
|
||||
>
|
||||
Afficher le code
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-4 w-full border-t pt-6">
|
||||
<p className="text-sm font-medium">
|
||||
|
||||
@@ -24,15 +24,25 @@ export function SocketProvider({ children }: { children: React.ReactNode }) {
|
||||
React.useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
|
||||
|
||||
// Initialisation du socket avec configuration optimisée pour la production
|
||||
const socketInstance = io(apiUrl, {
|
||||
withCredentials: true,
|
||||
transports: ["websocket"],
|
||||
transports: ["websocket"], // Recommandé pour éviter les problèmes de sticky sessions
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000,
|
||||
});
|
||||
|
||||
socketInstance.on("connect", () => {
|
||||
console.log("WebSocket connected to:", apiUrl);
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
socketInstance.on("connect_error", (error) => {
|
||||
console.error("WebSocket connection error:", error);
|
||||
// Si le websocket pur échoue, on peut tenter le polling en fallback (optionnel)
|
||||
});
|
||||
|
||||
socketInstance.on("disconnect", () => {
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@memegoat/source",
|
||||
"version": "1.8.3",
|
||||
"version": "1.9.1",
|
||||
"description": "",
|
||||
"scripts": {
|
||||
"version:get": "cmake -P version.cmake GET",
|
||||
|
||||
Reference in New Issue
Block a user