Compare commits
31 Commits
ace438be6b
...
v1.9.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7615ec670e
|
||
|
|
40cfff683d
|
||
|
|
bb52782226
|
||
|
|
6a70274623
|
||
|
|
aabc615b89
|
||
|
|
f9b202375f
|
||
|
|
6398965f16
|
||
|
|
9e9b1db012
|
||
|
|
62bf03d07a
|
||
|
|
c83ba6eb7d
|
||
|
|
05a05a1940
|
||
|
|
7c065a2fb9
|
||
|
|
001cdaff8f
|
||
|
|
0eb940c5ce
|
||
|
|
f0617c8ba5
|
||
|
|
27ea6fa413
|
||
|
|
e2146f4502
|
||
|
|
484b775923
|
||
|
|
5b05a14932
|
||
|
|
2704f7d5c5
|
||
|
|
d271cc215b
|
||
|
|
9eb5a60fb2
|
||
|
|
950646a426
|
||
|
|
a9b80e66cd
|
||
|
|
307655371d
|
||
|
|
8eb0cba050
|
||
|
|
50787c9357
|
||
|
|
0972ed951f
|
||
|
|
f852835c59
|
||
|
|
2c18fd1c1a
|
||
|
|
6d80795e44
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@memegoat/backend",
|
||||
"version": "1.8.2",
|
||||
"version": "1.9.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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";
|
||||
import { CommentsService } from "./comments.service";
|
||||
@@ -7,7 +9,12 @@ import { CommentLikesRepository } from "./repositories/comment-likes.repository"
|
||||
import { CommentsRepository } from "./repositories/comments.repository";
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, S3Module],
|
||||
imports: [
|
||||
AuthModule,
|
||||
S3Module,
|
||||
RealtimeModule,
|
||||
forwardRef(() => ContentsModule),
|
||||
],
|
||||
controllers: [CommentsController],
|
||||
providers: [CommentsService, CommentsRepository, CommentLikesRepository],
|
||||
exports: [CommentsService],
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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";
|
||||
import { CommentLikesRepository } from "./repositories/comment-likes.repository";
|
||||
@@ -13,6 +15,7 @@ describe("CommentsService", () => {
|
||||
create: jest.fn(),
|
||||
findAllByContentId: jest.fn(),
|
||||
findOne: jest.fn(),
|
||||
findOneEnriched: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
};
|
||||
|
||||
@@ -23,10 +26,19 @@ 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 () => {
|
||||
jest.clearAllMocks();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
@@ -34,7 +46,9 @@ describe("CommentsService", () => {
|
||||
CommentsService,
|
||||
{ provide: CommentsRepository, useValue: mockCommentsRepository },
|
||||
{ provide: CommentLikesRepository, useValue: mockCommentLikesRepository },
|
||||
{ provide: ContentsRepository, useValue: mockContentsRepository },
|
||||
{ provide: S3Service, useValue: mockS3Service },
|
||||
{ provide: EventsGateway, useValue: mockEventsGateway },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
@@ -51,7 +65,11 @@ describe("CommentsService", () => {
|
||||
const userId = "user1";
|
||||
const contentId = "content1";
|
||||
const dto = { text: "Nice meme", parentId: undefined };
|
||||
mockCommentsRepository.create.mockResolvedValue({ id: "c1", ...dto });
|
||||
const createdComment = { id: "c1", ...dto, user: { username: "u1" } };
|
||||
mockCommentsRepository.create.mockResolvedValue(createdComment);
|
||||
mockCommentsRepository.findOneEnriched.mockResolvedValue(createdComment);
|
||||
mockCommentLikesRepository.countByCommentId.mockResolvedValue(0);
|
||||
mockCommentLikesRepository.isLikedByUser.mockResolvedValue(false);
|
||||
|
||||
const result = await service.create(userId, contentId, dto);
|
||||
expect(result.id).toBe("c1");
|
||||
@@ -61,6 +79,11 @@ describe("CommentsService", () => {
|
||||
text: dto.text,
|
||||
parentId: undefined,
|
||||
});
|
||||
expect(mockEventsGateway.sendToContent).toHaveBeenCalledWith(
|
||||
contentId,
|
||||
"new_comment",
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
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";
|
||||
import { CommentLikesRepository } from "./repositories/comment-likes.repository";
|
||||
@@ -13,7 +17,10 @@ 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,
|
||||
) {}
|
||||
|
||||
async create(userId: string, contentId: string, dto: CreateCommentDto) {
|
||||
@@ -24,11 +31,74 @@ export class CommentsService {
|
||||
parentId: dto.parentId,
|
||||
});
|
||||
|
||||
// Enrichir le commentaire créé (pour le retour API)
|
||||
// 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 (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;
|
||||
}
|
||||
|
||||
async findOneEnriched(commentId: string, currentUserId?: string) {
|
||||
const comment = await this.commentsRepository.findOneEnriched(commentId);
|
||||
if (!comment) return null;
|
||||
|
||||
const [likesCount, isLiked] = await Promise.all([
|
||||
this.commentLikesRepository.countByCommentId(comment.id),
|
||||
currentUserId
|
||||
? this.commentLikesRepository.isLikedByUser(comment.id, currentUserId)
|
||||
: Promise.resolve(false),
|
||||
]);
|
||||
|
||||
return {
|
||||
...comment,
|
||||
likesCount: 0,
|
||||
isLiked: false,
|
||||
likesCount,
|
||||
isLiked,
|
||||
user: {
|
||||
...comment.user,
|
||||
avatarUrl: comment.user.avatarUrl
|
||||
? this.s3Service.getPublicUrl(comment.user.avatarUrl)
|
||||
: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -78,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) {
|
||||
|
||||
@@ -45,6 +45,27 @@ export class CommentsRepository {
|
||||
return results[0];
|
||||
}
|
||||
|
||||
async findOneEnriched(id: string) {
|
||||
const results = await this.databaseService.db
|
||||
.select({
|
||||
id: comments.id,
|
||||
text: comments.text,
|
||||
parentId: comments.parentId,
|
||||
createdAt: comments.createdAt,
|
||||
updatedAt: comments.updatedAt,
|
||||
user: {
|
||||
uuid: users.uuid,
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
},
|
||||
})
|
||||
.from(comments)
|
||||
.innerJoin(users, eq(comments.userId, users.uuid))
|
||||
.where(and(eq(comments.id, id), isNull(comments.deletedAt)));
|
||||
return results[0];
|
||||
}
|
||||
|
||||
async delete(id: string) {
|
||||
await this.databaseService.db
|
||||
.update(comments)
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,22 @@ export class MessagesController {
|
||||
return this.messagesService.getConversations(req.user.sub);
|
||||
}
|
||||
|
||||
@Get("unread-count")
|
||||
getUnreadCount(@Req() req: AuthenticatedRequest) {
|
||||
return this.messagesService.getUnreadCount(req.user.sub);
|
||||
}
|
||||
|
||||
@Get("conversations/with/:userId")
|
||||
getConversationWithUser(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
@Param("userId") targetUserId: string,
|
||||
) {
|
||||
return this.messagesService.getConversationWithUser(
|
||||
req.user.sub,
|
||||
targetUserId,
|
||||
);
|
||||
}
|
||||
|
||||
@Get("conversations/:id")
|
||||
getMessages(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
|
||||
@@ -17,6 +17,8 @@ describe("MessagesService", () => {
|
||||
findAllConversations: jest.fn(),
|
||||
isParticipant: jest.fn(),
|
||||
findMessagesByConversationId: jest.fn(),
|
||||
markAsRead: jest.fn(),
|
||||
countUnreadMessages: jest.fn(),
|
||||
};
|
||||
|
||||
const mockEventsGateway = {
|
||||
|
||||
@@ -42,6 +42,17 @@ export class MessagesService {
|
||||
return this.messagesRepository.findAllConversations(userId);
|
||||
}
|
||||
|
||||
async getUnreadCount(userId: string) {
|
||||
return this.messagesRepository.countUnreadMessages(userId);
|
||||
}
|
||||
|
||||
async getConversationWithUser(userId: string, targetUserId: string) {
|
||||
return this.messagesRepository.findConversationBetweenUsers(
|
||||
userId,
|
||||
targetUserId,
|
||||
);
|
||||
}
|
||||
|
||||
async getMessages(userId: string, conversationId: string) {
|
||||
const isParticipant = await this.messagesRepository.isParticipant(
|
||||
conversationId,
|
||||
@@ -51,6 +62,20 @@ export class MessagesService {
|
||||
throw new ForbiddenException("You are not part of this conversation");
|
||||
}
|
||||
|
||||
// Marquer comme lus
|
||||
await this.messagesRepository.markAsRead(conversationId, userId);
|
||||
|
||||
return this.messagesRepository.findMessagesByConversationId(conversationId);
|
||||
}
|
||||
|
||||
async markAsRead(userId: string, conversationId: string) {
|
||||
const isParticipant = await this.messagesRepository.isParticipant(
|
||||
conversationId,
|
||||
userId,
|
||||
);
|
||||
if (!isParticipant) {
|
||||
throw new ForbiddenException("You are not part of this conversation");
|
||||
}
|
||||
return this.messagesRepository.markAsRead(conversationId, userId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,4 +133,35 @@ export class MessagesRepository {
|
||||
.from(conversationParticipants)
|
||||
.where(eq(conversationParticipants.conversationId, conversationId));
|
||||
}
|
||||
|
||||
async markAsRead(conversationId: string, userId: string) {
|
||||
await this.databaseService.db
|
||||
.update(messages)
|
||||
.set({ readAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(messages.conversationId, conversationId),
|
||||
sql`${messages.senderId} != ${userId}`,
|
||||
sql`${messages.readAt} IS NULL`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async countUnreadMessages(userId: string) {
|
||||
const result = await this.databaseService.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(messages)
|
||||
.innerJoin(
|
||||
conversationParticipants,
|
||||
eq(messages.conversationId, conversationParticipants.conversationId),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(conversationParticipants.userId, userId),
|
||||
sql`${messages.senderId} != ${userId}`,
|
||||
sql`${messages.readAt} IS NULL`,
|
||||
),
|
||||
);
|
||||
return Number(result[0]?.count || 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { Logger } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import {
|
||||
ConnectedSocket,
|
||||
MessageBody,
|
||||
OnGatewayConnection,
|
||||
OnGatewayDisconnect,
|
||||
OnGatewayInit,
|
||||
SubscribeMessage,
|
||||
WebSocketGateway,
|
||||
WebSocketServer,
|
||||
} from "@nestjs/websockets";
|
||||
@@ -13,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
|
||||
@@ -25,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,
|
||||
@@ -54,16 +88,30 @@ export class EventsGateway
|
||||
|
||||
if (!session.accessToken) {
|
||||
this.logger.warn(`Client ${client.id} unauthorized connection`);
|
||||
// Permettre les connexions anonymes pour voir les commentaires en temps réel ?
|
||||
// Pour l'instant on déconnecte car le système actuel semble exiger l'auth
|
||||
client.disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
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}`);
|
||||
@@ -72,11 +120,67 @@ 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}`);
|
||||
}
|
||||
|
||||
@SubscribeMessage("join_content")
|
||||
handleJoinContent(
|
||||
@ConnectedSocket() client: Socket,
|
||||
@MessageBody() contentId: string,
|
||||
) {
|
||||
client.join(`content:${contentId}`);
|
||||
this.logger.log(`Client ${client.id} joined content room: ${contentId}`);
|
||||
}
|
||||
|
||||
@SubscribeMessage("leave_content")
|
||||
handleLeaveContent(
|
||||
@ConnectedSocket() client: Socket,
|
||||
@MessageBody() contentId: string,
|
||||
) {
|
||||
client.leave(`content:${contentId}`);
|
||||
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);
|
||||
}
|
||||
|
||||
sendToContent(contentId: string, event: string, data: any) {
|
||||
this.server.to(`content:${contentId}`).emit(event, data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { and, eq, lte, sql } from "drizzle-orm";
|
||||
import { and, eq, ilike, lte, or, sql } from "drizzle-orm";
|
||||
import { DatabaseService } from "../../database/database.service";
|
||||
import { contents, favorites, users } from "../../database/schemas";
|
||||
|
||||
@@ -97,6 +97,24 @@ export class UsersRepository {
|
||||
return result[0] || null;
|
||||
}
|
||||
|
||||
async search(query: string) {
|
||||
return this.databaseService.db
|
||||
.select({
|
||||
uuid: users.uuid,
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
})
|
||||
.from(users)
|
||||
.where(
|
||||
or(
|
||||
ilike(users.username, `%${query}%`),
|
||||
ilike(users.displayName, `%${query}%`),
|
||||
),
|
||||
)
|
||||
.limit(10);
|
||||
}
|
||||
|
||||
async findOne(uuid: string) {
|
||||
const result = await this.databaseService.db
|
||||
.select()
|
||||
|
||||
@@ -54,6 +54,12 @@ export class UsersController {
|
||||
return this.usersService.findPublicProfile(username);
|
||||
}
|
||||
|
||||
@Get("search")
|
||||
@UseGuards(AuthGuard)
|
||||
search(@Query("q") query: string) {
|
||||
return this.usersService.search(query);
|
||||
}
|
||||
|
||||
// Gestion de son propre compte
|
||||
@Get("me")
|
||||
@UseGuards(AuthGuard)
|
||||
|
||||
@@ -106,6 +106,16 @@ export class UsersService {
|
||||
};
|
||||
}
|
||||
|
||||
async search(query: string) {
|
||||
const users = await this.usersRepository.search(query);
|
||||
return users.map((user) => ({
|
||||
...user,
|
||||
avatarUrl: user.avatarUrl
|
||||
? this.s3Service.getPublicUrl(user.avatarUrl)
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
|
||||
async findOne(uuid: string) {
|
||||
const user = await this.usersRepository.findOne(uuid);
|
||||
if (!user) return null;
|
||||
|
||||
@@ -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.2",
|
||||
"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,9 @@
|
||||
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import { fr } from "date-fns/locale";
|
||||
import { Search, Send } 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";
|
||||
import { toast } from "sonner";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
@@ -16,23 +18,75 @@ import {
|
||||
type Message,
|
||||
MessageService,
|
||||
} from "@/services/message.service";
|
||||
import { UserService } from "@/services/user.service";
|
||||
import type { User } from "@/types/user";
|
||||
|
||||
export default function MessagesPage() {
|
||||
const { user } = useAuth();
|
||||
const { socket } = useSocket();
|
||||
const _router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const targetUserId = searchParams.get("user");
|
||||
|
||||
const [conversations, setConversations] = React.useState<Conversation[]>([]);
|
||||
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[]>([]);
|
||||
const [isSearching, setIsSearching] = React.useState(false);
|
||||
|
||||
const scrollRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
// Charger les conversations initiales
|
||||
React.useEffect(() => {
|
||||
const fetchConvs = async () => {
|
||||
try {
|
||||
const data = await MessageService.getConversations();
|
||||
setConversations(data);
|
||||
|
||||
// Si un utilisateur est spécifié dans l'URL, essayer de trouver la conversation
|
||||
if (targetUserId) {
|
||||
const existing = data.find((c) => c.recipient.uuid === targetUserId);
|
||||
if (existing) {
|
||||
setActiveConv(existing);
|
||||
} else {
|
||||
// Chercher les infos de l'utilisateur pour afficher une interface de chat vide
|
||||
try {
|
||||
const conv = await MessageService.getConversationWith(targetUserId);
|
||||
if (conv) {
|
||||
setConversations((prev) => [conv, ...prev]);
|
||||
setActiveConv(conv);
|
||||
}
|
||||
} catch (_e) {
|
||||
// Peut-être que l'utilisateur n'existe pas ou erreur
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_error) {
|
||||
toast.error("Erreur lors du chargement des conversations");
|
||||
} finally {
|
||||
@@ -40,7 +94,28 @@ export default function MessagesPage() {
|
||||
}
|
||||
};
|
||||
fetchConvs();
|
||||
}, []);
|
||||
}, [targetUserId]);
|
||||
|
||||
// Recherche d'utilisateurs
|
||||
React.useEffect(() => {
|
||||
const delayDebounceFn = setTimeout(async () => {
|
||||
if (searchQuery.length > 1) {
|
||||
setIsSearching(true);
|
||||
try {
|
||||
const results = await UserService.search(searchQuery);
|
||||
setSearchResults(results.filter((u) => u.uuid !== user?.uuid));
|
||||
} catch (_error) {
|
||||
console.error("Search failed");
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
} else {
|
||||
setSearchResults([]);
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(delayDebounceFn);
|
||||
}, [searchQuery, user?.uuid]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (activeConv) {
|
||||
@@ -66,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) => {
|
||||
@@ -90,15 +166,40 @@ 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]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
const scrollContainer = scrollRef.current.querySelector(
|
||||
"[data-slot='scroll-area-viewport']",
|
||||
);
|
||||
if (scrollContainer) {
|
||||
scrollContainer.scrollTop = scrollContainer.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -114,7 +215,21 @@ export default function MessagesPage() {
|
||||
activeConv.recipient.uuid,
|
||||
text,
|
||||
);
|
||||
setMessages((prev) => [...prev, msg]);
|
||||
|
||||
// Si c'était une conv temporaire, on la remplace par la vraie
|
||||
if (activeConv.id.startsWith("temp-")) {
|
||||
const fetchConvs = async () => {
|
||||
const data = await MessageService.getConversations();
|
||||
setConversations(data);
|
||||
const realConv = data.find(
|
||||
(c) => c.recipient.uuid === activeConv.recipient.uuid,
|
||||
);
|
||||
if (realConv) setActiveConv(realConv);
|
||||
};
|
||||
fetchConvs();
|
||||
} else {
|
||||
setMessages((prev) => [...prev, msg]);
|
||||
}
|
||||
} catch (_error) {
|
||||
toast.error("Erreur lors de l'envoi");
|
||||
}
|
||||
@@ -123,17 +238,100 @@ 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">
|
||||
<h2 className="text-xl font-bold mb-4">Messages</h2>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-bold">Messages</h2>
|
||||
<Button variant="ghost" size="icon" className="rounded-full">
|
||||
<UserPlus className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
<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..." className="pl-9" />
|
||||
<Input
|
||||
placeholder="Rechercher un membre..."
|
||||
className="pl-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="flex-1">
|
||||
<div className="p-2 space-y-1">
|
||||
{isLoadingConvs ? (
|
||||
{searchQuery.length > 0 ? (
|
||||
<>
|
||||
<p className="px-3 py-2 text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
|
||||
Membres
|
||||
</p>
|
||||
{isSearching ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
Recherche...
|
||||
</div>
|
||||
) : searchResults.length === 0 ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
Aucun membre trouvé.
|
||||
</div>
|
||||
) : (
|
||||
searchResults.map((result) => (
|
||||
<button
|
||||
key={result.uuid}
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
setSearchQuery("");
|
||||
// Chercher si une conv existe déjà
|
||||
const existing = conversations.find(
|
||||
(c) => c.recipient.uuid === result.uuid,
|
||||
);
|
||||
if (existing) {
|
||||
setActiveConv(existing);
|
||||
} else {
|
||||
// Créer une interface de conv temporaire
|
||||
const newConv: Conversation = {
|
||||
id: `temp-${result.uuid}`,
|
||||
updatedAt: new Date().toISOString(),
|
||||
recipient: {
|
||||
uuid: result.uuid,
|
||||
username: result.username,
|
||||
displayName: result.displayName,
|
||||
avatarUrl: result.avatarUrl,
|
||||
},
|
||||
};
|
||||
setConversations((prev) => [newConv, ...prev]);
|
||||
setActiveConv(newConv);
|
||||
}
|
||||
}}
|
||||
className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-zinc-100 dark:hover:bg-zinc-900 transition-colors"
|
||||
>
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarImage src={result.avatarUrl} />
|
||||
<AvatarFallback>{result.username[0].toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 text-left overflow-hidden">
|
||||
<span className="font-bold block truncate">
|
||||
{result.displayName || result.username}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground block truncate">
|
||||
@{result.username}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
) : isLoadingConvs ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
Chargement...
|
||||
</div>
|
||||
@@ -184,23 +382,50 @@ 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 gap-3">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={activeConv.recipient.avatarUrl} />
|
||||
<AvatarFallback>
|
||||
{activeConv.recipient.username[0].toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<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>
|
||||
</div>
|
||||
<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-1 flex items-center gap-3 hover:opacity-80 transition-opacity"
|
||||
>
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={activeConv.recipient.avatarUrl} />
|
||||
<AvatarFallback>
|
||||
{activeConv.recipient.username[0].toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<h3 className="font-bold leading-none">
|
||||
{activeConv.recipient.displayName || activeConv.recipient.username}
|
||||
</h3>
|
||||
<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>
|
||||
|
||||
{/* Messages */}
|
||||
@@ -226,22 +451,40 @@ export default function MessagesPage() {
|
||||
}`}
|
||||
>
|
||||
<p className="whitespace-pre-wrap">{msg.text}</p>
|
||||
<p
|
||||
className={`text-[10px] mt-1 ${
|
||||
<div
|
||||
className={`flex items-center gap-1 text-[10px] mt-1 ${
|
||||
msg.senderId === user?.uuid
|
||||
? "text-primary-foreground/70"
|
||||
? "text-primary-foreground/70 justify-end"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{new Date(msg.createdAt).toLocaleTimeString([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</p>
|
||||
<span>
|
||||
{new Date(msg.createdAt).toLocaleTimeString([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</span>
|
||||
{msg.senderId === user?.uuid && (
|
||||
<span className="font-bold">
|
||||
{msg.readAt ? "• Lu" : "• Envoyé"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</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>
|
||||
|
||||
@@ -251,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,12 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { Calendar, Share2, User as UserIcon } from "lucide-react";
|
||||
import {
|
||||
Calendar,
|
||||
MessageCircle,
|
||||
Share2,
|
||||
User as UserIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { ContentList } from "@/components/content-list";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { useAuth } from "@/providers/auth-provider";
|
||||
import { ContentService } from "@/services/content.service";
|
||||
import { UserService } from "@/services/user.service";
|
||||
import type { User } from "@/types/user";
|
||||
@@ -17,9 +24,12 @@ export default function PublicProfilePage({
|
||||
params: Promise<{ username: string }>;
|
||||
}) {
|
||||
const { username } = React.use(params);
|
||||
const { user: currentUser, isAuthenticated } = useAuth();
|
||||
const [user, setUser] = React.useState<User | null>(null);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
|
||||
const isOwnProfile = currentUser?.username === username;
|
||||
|
||||
React.useEffect(() => {
|
||||
UserService.getProfile(username)
|
||||
.then(setUser)
|
||||
@@ -93,7 +103,15 @@ export default function PublicProfilePage({
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-center md:justify-start pt-2">
|
||||
<div className="flex flex-wrap justify-center md:justify-start gap-2 pt-2">
|
||||
{!isOwnProfile && isAuthenticated && (
|
||||
<Button size="sm" className="h-9 px-4" asChild>
|
||||
<Link href={`/messages?user=${user.uuid}`}>
|
||||
<MessageCircle className="h-4 w-4 mr-2" />
|
||||
Message
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSub,
|
||||
@@ -54,7 +55,9 @@ import {
|
||||
SidebarTrigger,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { useAuth } from "@/providers/auth-provider";
|
||||
import { useSocket } from "@/providers/socket-provider";
|
||||
import { CategoryService } from "@/services/category.service";
|
||||
import { MessageService } from "@/services/message.service";
|
||||
import type { Category } from "@/types/content";
|
||||
|
||||
const mainNav = [
|
||||
@@ -79,15 +82,46 @@ export function AppSidebar() {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const { user, logout, isAuthenticated } = useAuth();
|
||||
const { socket } = useSocket();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const [categories, setCategories] = React.useState<Category[]>([]);
|
||||
const [mounted, setMounted] = React.useState(false);
|
||||
const [unreadMessages, setUnreadMessages] = React.useState(0);
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true);
|
||||
CategoryService.getAll().then(setCategories).catch(console.error);
|
||||
}, []);
|
||||
|
||||
// Gérer le compteur de messages non-lus
|
||||
React.useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
MessageService.getUnreadCount().then(setUnreadMessages).catch(console.error);
|
||||
}
|
||||
}, [isAuthenticated]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (socket && isAuthenticated) {
|
||||
socket.on("new_message", () => {
|
||||
// Incrémenter si on n'est pas sur la page messages
|
||||
if (pathname !== "/messages") {
|
||||
setUnreadMessages((prev) => prev + 1);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.off("new_message");
|
||||
};
|
||||
}
|
||||
}, [socket, isAuthenticated, pathname]);
|
||||
|
||||
// Remettre à zéro si on arrive sur la page messages
|
||||
React.useEffect(() => {
|
||||
if (pathname === "/messages") {
|
||||
setUnreadMessages(0);
|
||||
}
|
||||
}, [pathname]);
|
||||
|
||||
const logoSrc = React.useMemo(() => {
|
||||
if (!mounted) return "/memegoat-color.svg";
|
||||
return resolvedTheme === "dark"
|
||||
@@ -193,6 +227,11 @@ export function AppSidebar() {
|
||||
<span>Messages</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
{unreadMessages > 0 && (
|
||||
<SidebarMenuBadge className="bg-red-500 text-white border-none h-5 min-w-5 flex items-center justify-center p-1 text-[10px]">
|
||||
{unreadMessages > 9 ? "9+" : unreadMessages}
|
||||
</SidebarMenuBadge>
|
||||
)}
|
||||
</SidebarMenuItem>
|
||||
)}
|
||||
</SidebarMenu>
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useAuth } from "@/providers/auth-provider";
|
||||
import { useSocket } from "@/providers/socket-provider";
|
||||
import { type Comment, CommentService } from "@/services/comment.service";
|
||||
|
||||
interface CommentSectionProps {
|
||||
@@ -24,6 +25,7 @@ interface CommentSectionProps {
|
||||
|
||||
export function CommentSection({ contentId }: CommentSectionProps) {
|
||||
const { user, isAuthenticated } = useAuth();
|
||||
const { socket } = useSocket();
|
||||
const [comments, setComments] = React.useState<Comment[]>([]);
|
||||
const [newComment, setNewComment] = React.useState("");
|
||||
const [replyingTo, setReplyingTo] = React.useState<Comment | null>(null);
|
||||
@@ -45,6 +47,26 @@ export function CommentSection({ contentId }: CommentSectionProps) {
|
||||
fetchComments();
|
||||
}, [fetchComments]);
|
||||
|
||||
// Gestion du WebSocket
|
||||
React.useEffect(() => {
|
||||
if (socket) {
|
||||
socket.emit("join_content", contentId);
|
||||
|
||||
socket.on("new_comment", (comment: Comment) => {
|
||||
setComments((prev) => {
|
||||
// Éviter les doublons si l'auteur reçoit son propre commentaire via WS
|
||||
if (prev.some((c) => c.id === comment.id)) return prev;
|
||||
return [comment, ...prev];
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.emit("leave_content", contentId);
|
||||
socket.off("new_comment");
|
||||
};
|
||||
}
|
||||
}, [socket, contentId]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newComment.trim() || isSubmitting) return;
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2, Shield, ShieldAlert, ShieldCheck } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -28,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);
|
||||
@@ -76,9 +78,7 @@ export function TwoFactorSetup() {
|
||||
};
|
||||
|
||||
// Note: We need a way to know if 2FA is enabled.
|
||||
// Assuming user object might have twoFactorEnabled property or similar.
|
||||
// For now, let's assume it's on the user object (we might need to add it to the type).
|
||||
const isEnabled = (user as any)?.twoFactorEnabled;
|
||||
const isEnabled = user?.twoFactorEnabled;
|
||||
|
||||
if (step === "idle") {
|
||||
return (
|
||||
@@ -153,17 +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">
|
||||
<img src={qrCode} alt="QR Code 2FA" className="w-48 h-48" />
|
||||
<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,4 +1,5 @@
|
||||
import api from "@/lib/api";
|
||||
import type { User } from "@/types/user";
|
||||
import type { Report, ReportStatus } from "./report.service";
|
||||
|
||||
export interface AdminStats {
|
||||
@@ -29,7 +30,7 @@ export const adminService = {
|
||||
await api.delete(`/users/${userId}`);
|
||||
},
|
||||
|
||||
updateUser: async (userId: string, data: any): Promise<void> => {
|
||||
updateUser: async (userId: string, data: Partial<User>): Promise<void> => {
|
||||
await api.patch(`/users/admin/${userId}`, data);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -29,6 +29,11 @@ export const MessageService = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async getUnreadCount(): Promise<number> {
|
||||
const { data } = await api.get<number>("/messages/unread-count");
|
||||
return data;
|
||||
},
|
||||
|
||||
async getMessages(conversationId: string): Promise<Message[]> {
|
||||
const { data } = await api.get<Message[]>(
|
||||
`/messages/conversations/${conversationId}`,
|
||||
@@ -36,6 +41,13 @@ export const MessageService = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async getConversationWith(userId: string): Promise<Conversation | null> {
|
||||
const { data } = await api.get<Conversation | null>(
|
||||
`/messages/conversations/with/${userId}`,
|
||||
);
|
||||
return data;
|
||||
},
|
||||
|
||||
async sendMessage(recipientId: string, text: string): Promise<Message> {
|
||||
const { data } = await api.post<Message>("/messages", {
|
||||
recipientId,
|
||||
|
||||
@@ -12,6 +12,13 @@ export const UserService = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async search(query: string): Promise<User[]> {
|
||||
const { data } = await api.get<User[]>("/users/search", {
|
||||
params: { q: query },
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
async updateMe(update: Partial<User>): Promise<User> {
|
||||
const { data } = await api.patch<User>("/users/me", update);
|
||||
return data;
|
||||
@@ -54,8 +61,8 @@ export const UserService = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async exportData(): Promise<any> {
|
||||
const { data } = await api.get("/users/me/export");
|
||||
async exportData(): Promise<Record<string, unknown>> {
|
||||
const { data } = await api.get<Record<string, unknown>>("/users/me/export");
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface User {
|
||||
bio?: string;
|
||||
role?: "user" | "admin" | "moderator";
|
||||
status?: "active" | "verification" | "suspended" | "pending" | "deleted";
|
||||
twoFactorEnabled?: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@memegoat/source",
|
||||
"version": "1.8.2",
|
||||
"version": "1.9.1",
|
||||
"description": "",
|
||||
"scripts": {
|
||||
"version:get": "cmake -P version.cmake GET",
|
||||
|
||||
Reference in New Issue
Block a user