feat: tíng năng trò chuyện giữa các thành viên và tin nhắn trực tiếp cho bạn bè

This commit is contained in:
2026-06-21 09:46:37 +07:00
parent 392a4d4766
commit 8d79cd76f6
15 changed files with 3932 additions and 234 deletions
+484 -43
View File
@@ -48,7 +48,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommentGateway = exports.EmailService = exports.TourRoleGuard = exports.Roles = exports.ROLES_KEY = void 0;
exports.EmailService = exports.TourRoleGuard = exports.Roles = exports.ROLES_KEY = exports.CommentGateway = void 0;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const crypto = __importStar(require("crypto"));
@@ -80,6 +80,64 @@ const compress_cache_interceptor_1 = require("./common/compress-cache.intercepto
const gzip = (0, util_1.promisify)(zlib.gzip);
const gunzip = (0, util_1.promisify)(zlib.gunzip);
const UPLOAD_ROOT = path.join(process.cwd(), 'uploads');
let CommentGateway = class CommentGateway {
handleConnection(client) {
console.log(`[WS] Client connected: ${client.id}`);
}
handleJoinTour(client, tourId) {
client.join(`tour_${tourId}`);
console.log(`[WS] Client ${client.id} joined room: tour_${tourId}`);
}
handleJoinPhoto(client, photoId) {
client.join(`photo_${photoId}`);
console.log(`[WS] Client ${client.id} joined room: photo_${photoId}`);
}
notifyNewComment(tourId, data) {
this.server.to(`tour_${tourId}`).emit('commentAdded', data);
}
notifyNewPhotoComment(photoId, data) {
this.server.to(`photo_${photoId}`).emit('photoCommentAdded', data);
}
handleJoinUser(client, userId) {
client.join(`user_${userId}`);
console.log(`[WS] Client ${client.id} joined user room: user_${userId}`);
}
notifyNewMessage(receiverId, data) {
this.server.to(`user_${receiverId}`).emit('messageReceived', data);
}
notifyConnectionAccepted(requesterId, data) {
this.server.to(`user_${requesterId}`).emit('connectionAccepted', data);
}
notifyJoinRequestAccepted(userId, data) {
this.server.to(`user_${userId}`).emit('joinRequestAccepted', data);
}
};
exports.CommentGateway = CommentGateway;
__decorate([
(0, websockets_1.WebSocketServer)(),
__metadata("design:type", socket_io_1.Server)
], CommentGateway.prototype, "server", void 0);
__decorate([
(0, websockets_1.SubscribeMessage)('joinTour'),
__metadata("design:type", Function),
__metadata("design:paramtypes", [socket_io_1.Socket, String]),
__metadata("design:returntype", void 0)
], CommentGateway.prototype, "handleJoinTour", null);
__decorate([
(0, websockets_1.SubscribeMessage)('joinPhoto'),
__metadata("design:type", Function),
__metadata("design:paramtypes", [socket_io_1.Socket, String]),
__metadata("design:returntype", void 0)
], CommentGateway.prototype, "handleJoinPhoto", null);
__decorate([
(0, websockets_1.SubscribeMessage)('joinUser'),
__metadata("design:type", Function),
__metadata("design:paramtypes", [socket_io_1.Socket, String]),
__metadata("design:returntype", void 0)
], CommentGateway.prototype, "handleJoinUser", null);
exports.CommentGateway = CommentGateway = __decorate([
(0, websockets_1.WebSocketGateway)({ cors: { origin: '*' } })
], CommentGateway);
const CACHE_TTL = {
DEFAULT: 600000,
RESOURCE_TO_TOUR: 3600000,
@@ -454,6 +512,7 @@ let AuthController = class AuthController {
name: user.name,
avatar: user.avatar,
isAdmin: user.isAdmin,
isGoogle: true,
},
};
}
@@ -653,10 +712,11 @@ PublicTourController = __decorate([
__metadata("design:paramtypes", [prisma_service_1.PrismaService])
], PublicTourController);
let TourController = class TourController {
constructor(prisma, emailService, cacheManager) {
constructor(prisma, emailService, cacheManager, commentGateway) {
this.prisma = prisma;
this.emailService = emailService;
this.cacheManager = cacheManager;
this.commentGateway = commentGateway;
}
async createTour(body, req) {
const { title, description, startDate, endDate, adultCount, childCount, childDiscount, tags, members } = body;
@@ -1213,6 +1273,15 @@ let TourController = class TourController {
data: { status: 'ACCEPTED' },
}),
]);
const tour = await this.prisma.tour.findUnique({
where: { id: tourId },
select: { title: true }
});
this.commentGateway.notifyJoinRequestAccepted(joinRequest.userId, {
tourId,
tourTitle: tour?.title || 'Hành trình',
requestId
});
return { success: true, message: 'Đã chấp nhận yêu cầu tham gia.' };
}
async rejectJoinRequest(tourId, requestId, req) {
@@ -1707,7 +1776,7 @@ TourController = __decorate([
(0, common_1.Controller)('tours'),
__param(2, (0, common_1.Inject)(cache_manager_1.CACHE_MANAGER)),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
EmailService, Object])
EmailService, Object, CommentGateway])
], TourController);
let LocationController = class LocationController {
constructor(prisma, cacheManager) {
@@ -2361,45 +2430,6 @@ UserController = __decorate([
(0, exports.Roles)(client_1.ParticipantRole.OWNER, client_1.ParticipantRole.MANAGER),
__metadata("design:paramtypes", [prisma_service_1.PrismaService])
], UserController);
let CommentGateway = class CommentGateway {
handleConnection(client) {
console.log(`[WS] Client connected: ${client.id}`);
}
handleJoinTour(client, tourId) {
client.join(`tour_${tourId}`);
console.log(`[WS] Client ${client.id} joined room: tour_${tourId}`);
}
handleJoinPhoto(client, photoId) {
client.join(`photo_${photoId}`);
console.log(`[WS] Client ${client.id} joined room: photo_${photoId}`);
}
notifyNewComment(tourId, data) {
this.server.to(`tour_${tourId}`).emit('commentAdded', data);
}
notifyNewPhotoComment(photoId, data) {
this.server.to(`photo_${photoId}`).emit('photoCommentAdded', data);
}
};
exports.CommentGateway = CommentGateway;
__decorate([
(0, websockets_1.WebSocketServer)(),
__metadata("design:type", socket_io_1.Server)
], CommentGateway.prototype, "server", void 0);
__decorate([
(0, websockets_1.SubscribeMessage)('joinTour'),
__metadata("design:type", Function),
__metadata("design:paramtypes", [socket_io_1.Socket, String]),
__metadata("design:returntype", void 0)
], CommentGateway.prototype, "handleJoinTour", null);
__decorate([
(0, websockets_1.SubscribeMessage)('joinPhoto'),
__metadata("design:type", Function),
__metadata("design:paramtypes", [socket_io_1.Socket, String]),
__metadata("design:returntype", void 0)
], CommentGateway.prototype, "handleJoinPhoto", null);
exports.CommentGateway = CommentGateway = __decorate([
(0, websockets_1.WebSocketGateway)({ cors: { origin: '*' } })
], CommentGateway);
let CommentController = class CommentController {
constructor(prisma, commentGateway) {
this.prisma = prisma;
@@ -2961,6 +2991,417 @@ PublicPhotoController = __decorate([
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
CommentGateway])
], PublicPhotoController);
let ConnectionController = class ConnectionController {
constructor(prisma, commentGateway) {
this.prisma = prisma;
this.commentGateway = commentGateway;
}
async getConnections(req) {
const currentUserId = req.user.id;
const connections = await this.prisma.userConnection.findMany({
where: {
OR: [
{ requesterId: currentUserId },
{ receiverId: currentUserId }
],
status: 'ACCEPTED'
},
include: {
requester: { select: { id: true, name: true, email: true, avatar: true } },
receiver: { select: { id: true, name: true, email: true, avatar: true } }
}
});
const formattedConnections = connections.map(conn => {
const isRequester = conn.requesterId === currentUserId;
const targetUser = isRequester ? conn.receiver : conn.requester;
return {
id: conn.id,
targetUser,
type: conn.type,
status: conn.status,
createdAt: conn.createdAt
};
});
const receivedRequests = await this.prisma.userConnection.findMany({
where: {
receiverId: currentUserId,
status: 'PENDING'
},
include: {
requester: { select: { id: true, name: true, email: true, avatar: true } }
}
});
const sentRequests = await this.prisma.userConnection.findMany({
where: {
requesterId: currentUserId,
status: 'PENDING'
},
include: {
receiver: { select: { id: true, name: true, email: true, avatar: true } }
}
});
return {
connections: formattedConnections,
receivedRequests: receivedRequests.map(r => ({ id: r.id, requester: r.requester, type: r.type, createdAt: r.createdAt })),
sentRequests: sentRequests.map(r => ({ id: r.id, receiver: r.receiver, type: r.type, createdAt: r.createdAt }))
};
}
async sendRequest(req, body) {
const requesterId = req.user.id;
const { receiverId } = body;
if (requesterId === receiverId) {
throw new common_1.BadRequestException('Bạn không thể gửi lời mời kết nối cho chính mình.');
}
const receiver = await this.prisma.user.findUnique({ where: { id: receiverId } });
if (!receiver) {
throw new common_1.NotFoundException('Không tìm thấy người nhận.');
}
const existing = await this.prisma.userConnection.findFirst({
where: {
OR: [
{ requesterId, receiverId },
{ requesterId: receiverId, receiverId }
]
}
});
if (existing) {
if (existing.status === 'ACCEPTED') {
throw new common_1.BadRequestException('Hai bạn đã kết nối với nhau.');
}
if (existing.status === 'PENDING') {
throw new common_1.BadRequestException('Yêu cầu kết nối đang chờ xử lý.');
}
await this.prisma.userConnection.delete({ where: { id: existing.id } });
}
const newConn = await this.prisma.userConnection.create({
data: {
requesterId,
receiverId,
status: 'PENDING',
type: 'FRIEND'
}
});
return { success: true, connection: newConn };
}
async updateRequest(id, body, req) {
const currentUserId = req.user.id;
const conn = await this.prisma.userConnection.findUnique({ where: { id } });
if (!conn) {
throw new common_1.NotFoundException('Không tìm thấy bản ghi kết nối.');
}
if (body.status) {
if (conn.receiverId !== currentUserId) {
throw new common_1.ForbiddenException('Bạn không có quyền thực hiện hành động này.');
}
const updated = await this.prisma.userConnection.update({
where: { id },
data: { status: body.status }
});
if (body.status === 'ACCEPTED') {
const receiverUser = await this.prisma.user.findUnique({
where: { id: currentUserId },
select: { name: true }
});
this.commentGateway.notifyConnectionAccepted(conn.requesterId, {
connectionId: conn.id,
acceptedByName: receiverUser?.name || 'Ai đó',
acceptedById: currentUserId
});
}
return { success: true, connection: updated };
}
if (body.type) {
if (conn.requesterId !== currentUserId && conn.receiverId !== currentUserId) {
throw new common_1.ForbiddenException('Bạn không có quyền thực hiện hành động này.');
}
if (conn.status !== 'ACCEPTED') {
throw new common_1.BadRequestException('Chỉ có thể thay đổi phân nhóm sau khi đã chấp nhận kết nối.');
}
const updated = await this.prisma.userConnection.update({
where: { id },
data: { type: body.type }
});
return { success: true, connection: updated };
}
throw new common_1.BadRequestException('Yêu cầu không hợp lệ.');
}
async deleteConnection(id, req) {
const currentUserId = req.user.id;
const conn = await this.prisma.userConnection.findUnique({ where: { id } });
if (!conn) {
throw new common_1.NotFoundException('Không tìm thấy bản ghi kết nối.');
}
if (conn.requesterId !== currentUserId && conn.receiverId !== currentUserId) {
throw new common_1.ForbiddenException('Bạn không có quyền thực hiện hành động này.');
}
await this.prisma.userConnection.delete({ where: { id } });
return { success: true, message: 'Đã hủy kết nối thành công.' };
}
};
__decorate([
(0, common_1.Get)(),
__param(0, (0, common_1.Req)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], ConnectionController.prototype, "getConnections", null);
__decorate([
(0, common_1.Post)(),
__param(0, (0, common_1.Req)()),
__param(1, (0, common_1.Body)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], ConnectionController.prototype, "sendRequest", null);
__decorate([
(0, common_1.Patch)(':id'),
__param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
__param(1, (0, common_1.Body)()),
__param(2, (0, common_1.Req)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String, Object, Object]),
__metadata("design:returntype", Promise)
], ConnectionController.prototype, "updateRequest", null);
__decorate([
(0, common_1.Delete)(':id'),
__param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
__param(1, (0, common_1.Req)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String, Object]),
__metadata("design:returntype", Promise)
], ConnectionController.prototype, "deleteConnection", null);
ConnectionController = __decorate([
(0, common_1.UseGuards)(jwt_auth_guard_1.JwtAuthGuard),
(0, common_1.Controller)('connections'),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
CommentGateway])
], ConnectionController);
let DirectMessageController = class DirectMessageController {
constructor(prisma, commentGateway) {
this.prisma = prisma;
this.commentGateway = commentGateway;
}
async getMessages(userId, req) {
const currentUserId = req.user.id;
const conn = await this.prisma.userConnection.findFirst({
where: {
OR: [
{ requesterId: currentUserId, receiverId: userId },
{ requesterId: userId, receiverId: currentUserId }
],
status: 'ACCEPTED'
}
});
if (!conn) {
throw new common_1.ForbiddenException('Bạn chỉ có thể nhắn tin với người đã kết nối.');
}
const messages = await this.prisma.directMessage.findMany({
where: {
OR: [
{ senderId: currentUserId, receiverId: userId },
{ senderId: userId, receiverId: currentUserId }
]
},
orderBy: { createdAt: 'asc' }
});
return messages;
}
async sendMessage(req, body) {
const senderId = req.user.id;
const { receiverId, content, attachmentUrl, latitude, longitude } = body;
if ((!content || !content.trim()) && !attachmentUrl && latitude === undefined) {
throw new common_1.BadRequestException('Tin nhắn phải có nội dung, ảnh đính kèm hoặc vị trí.');
}
const conn = await this.prisma.userConnection.findFirst({
where: {
OR: [
{ requesterId: senderId, receiverId: receiverId },
{ requesterId: receiverId, receiverId: senderId }
],
status: 'ACCEPTED'
}
});
if (!conn) {
throw new common_1.ForbiddenException('Bạn chỉ có thể nhắn tin với người đã kết nối.');
}
const message = await this.prisma.directMessage.create({
data: {
senderId,
receiverId,
content: content || '',
attachmentUrl,
latitude,
longitude
},
include: {
sender: { select: { id: true, name: true, avatar: true } }
}
});
this.commentGateway.notifyNewMessage(receiverId, message);
return message;
}
};
__decorate([
(0, common_1.Get)(':userId'),
__param(0, (0, common_1.Param)('userId', common_1.ParseUUIDPipe)),
__param(1, (0, common_1.Req)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String, Object]),
__metadata("design:returntype", Promise)
], DirectMessageController.prototype, "getMessages", null);
__decorate([
(0, common_1.Post)(),
__param(0, (0, common_1.Req)()),
__param(1, (0, common_1.Body)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], DirectMessageController.prototype, "sendMessage", null);
DirectMessageController = __decorate([
(0, common_1.UseGuards)(jwt_auth_guard_1.JwtAuthGuard),
(0, common_1.Controller)('messages'),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
CommentGateway])
], DirectMessageController);
let UploadController = class UploadController {
async uploadAttachment(files) {
if (!files || files.length === 0) {
throw new common_1.BadRequestException('Vui lòng chọn ảnh.');
}
const file = files[0];
const attachmentsDir = path.join(UPLOAD_ROOT, 'attachments');
if (!fs.existsSync(attachmentsDir)) {
fs.mkdirSync(attachmentsDir, { recursive: true });
}
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const extension = path.extname(file.originalname).toLowerCase() || '.jpg';
const filename = `${uniqueSuffix}${extension}`;
const filePath = path.join(attachmentsDir, filename);
fs.writeFileSync(filePath, file.buffer);
return {
url: `/uploads/attachments/${filename}`
};
}
};
__decorate([
(0, common_1.Post)(),
(0, common_1.UseInterceptors)((0, platform_express_1.FilesInterceptor)('image', 1)),
__param(0, (0, common_1.UploadedFiles)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Array]),
__metadata("design:returntype", Promise)
], UploadController.prototype, "uploadAttachment", null);
UploadController = __decorate([
(0, common_1.UseGuards)(jwt_auth_guard_1.JwtAuthGuard),
(0, common_1.Controller)('upload')
], UploadController);
let TourMessageController = class TourMessageController {
constructor(prisma, commentGateway) {
this.prisma = prisma;
this.commentGateway = commentGateway;
}
async getTourMessages(tourId, req) {
const userId = req.user.id;
const participant = await this.prisma.tourParticipant.findFirst({
where: { tourId, userId }
});
if (!participant) {
throw new common_1.ForbiddenException('Bạn không phải là thành viên của hành trình này.');
}
const messages = await this.prisma.tourMessage.findMany({
where: { tourId },
include: {
sender: { select: { id: true, name: true, avatar: true } }
},
orderBy: { createdAt: 'asc' }
});
return messages;
}
async sendTourMessage(tourId, req, body) {
const senderId = req.user.id;
const { content, attachmentUrl, latitude, longitude, taggedUserIds } = body;
console.log(`[sendTourMessage] senderId=${senderId}, tourId=${tourId}, taggedUserIds=`, taggedUserIds);
if ((!content || !content.trim()) && !attachmentUrl && latitude === undefined) {
throw new common_1.BadRequestException('Tin nhắn phải có nội dung, ảnh đính kèm hoặc vị trí.');
}
const participant = await this.prisma.tourParticipant.findFirst({
where: { tourId, userId: senderId }
});
if (!participant) {
throw new common_1.ForbiddenException('Bạn không phải là thành viên của hành trình này.');
}
const tourMessage = await this.prisma.tourMessage.create({
data: {
tourId,
senderId,
content: content || '',
attachmentUrl,
latitude,
longitude
},
include: {
sender: { select: { id: true, name: true, avatar: true } }
}
});
this.commentGateway.server.to(`tour_${tourId}`).emit('tourMessageReceived', {
tourId,
message: tourMessage
});
const hasTags = Array.isArray(taggedUserIds) && taggedUserIds.length > 0;
const otherParticipants = await this.prisma.tourParticipant.findMany({
where: {
tourId,
userId: {
not: senderId,
in: hasTags ? taggedUserIds : undefined
},
NOT: { userId: null }
}
});
console.log(`[sendTourMessage] otherParticipants found count: ${otherParticipants.length}`, otherParticipants.map(o => o.userId));
const tour = await this.prisma.tour.findUnique({
where: { id: tourId },
select: { title: true }
});
for (const p of otherParticipants) {
if (p.userId) {
const isTagged = hasTags && taggedUserIds.includes(p.userId);
console.log(`[sendTourMessage] Emitting tourMessageNotification to user_${p.userId}, isTagged: ${isTagged}`);
this.commentGateway.server.to(`user_${p.userId}`).emit('tourMessageNotification', {
tourId,
senderName: req.user.name || 'Thành viên',
tourTitle: tour?.title || 'Hành trình',
content: isTagged ? `@Bạn: ${content || ''}` : content || (attachmentUrl ? '[Hình ảnh]' : '[Vị trí]'),
isTagged
});
}
}
return tourMessage;
}
};
__decorate([
(0, common_1.Get)(),
__param(0, (0, common_1.Param)('tourId', common_1.ParseUUIDPipe)),
__param(1, (0, common_1.Req)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String, Object]),
__metadata("design:returntype", Promise)
], TourMessageController.prototype, "getTourMessages", null);
__decorate([
(0, common_1.Post)(),
__param(0, (0, common_1.Param)('tourId', common_1.ParseUUIDPipe)),
__param(1, (0, common_1.Req)()),
__param(2, (0, common_1.Body)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [String, Object, Object]),
__metadata("design:returntype", Promise)
], TourMessageController.prototype, "sendTourMessage", null);
TourMessageController = __decorate([
(0, common_1.UseGuards)(jwt_auth_guard_1.JwtAuthGuard),
(0, common_1.Controller)('tours/:tourId/messages'),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
CommentGateway])
], TourMessageController);
let AppModule = class AppModule {
};
AppModule = __decorate([
@@ -2985,7 +3426,7 @@ AppModule = __decorate([
signOptions: { expiresIn: '1d' },
}),
],
controllers: [AppController, AuthController, PublicTourController, TourController, UserController, RoutingController, LegController, LocationController, CommentController, PhotoController, PublicPhotoController, AdminOtpController, AdminController],
controllers: [AppController, AuthController, PublicTourController, TourController, UserController, RoutingController, LegController, LocationController, CommentController, PhotoController, PublicPhotoController, AdminOtpController, AdminController, ConnectionController, DirectMessageController, UploadController, TourMessageController],
providers: [prisma_service_1.PrismaService, jwt_strategy_1.JwtStrategy, TourRoleGuard, jwt_auth_guard_1.JwtAuthGuard, admin_guard_1.AdminGuard, CommentGateway, core_2.Reflector, EmailService, config_1.ConfigService],
exports: [prisma_service_1.PrismaService]
})