Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 79 additions & 4 deletions src/chat/chat.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@ import {
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { ChatService } from './chat.service';
import { Logger, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common';
import {
Logger,
UseGuards,
UsePipes,
ValidationPipe,
Inject,
forwardRef,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { UsersService } from '../users/users.service';
import { CreateMessageDto } from './dto/create-message.dto';
import { JoinRoomDto } from './dto/join-room.dto';
import { WsJwtGuard } from './guards/ws-jwt.guard';
import { NotificationService } from '../notifications/notifications.service';

@UsePipes(new ValidationPipe())
@WebSocketGateway({
Expand All @@ -30,12 +36,15 @@ export class ChatGateway
@WebSocketServer() server: Server;
private logger: Logger = new Logger('ChatGateway');
private wsJwtGuard: WsJwtGuard;
private userSocketMap = new Map<string, string[]>();

constructor(
private readonly chatService: ChatService,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
private readonly usersService: UsersService,
@Inject(forwardRef(() => NotificationService))
private readonly notificationService: NotificationService,
) {
this.wsJwtGuard = new WsJwtGuard(jwtService, configService, usersService);
}
Expand All @@ -53,9 +62,35 @@ export class ChatGateway
if (!canActivate) {
this.logger.warn(`Disconnecting unauthenticated client: ${client.id}`);
} else {
const userId = client.data.user?.userId;
this.logger.log(
`Client authenticated: ${client.id}, User ID: ${client.data.user?.userId}`,
`Client authenticated: ${client.id}, User ID: ${userId}`,
);
if (userId) {
const userSockets = this.userSocketMap.get(userId) || [];
userSockets.push(client.id);
this.userSocketMap.set(userId, userSockets);

const notificationRoom = `notifications_${userId}`;
client.join(notificationRoom);
this.logger.log(
`User ${userId} joined notification room: ${notificationRoom}`,
);
try {
const unreadNotifications =
await this.notificationService.getUserUnreadNotifications(userId);
if (unreadNotifications.length > 0) {
this.logger.log(
`Sending ${unreadNotifications.length} unread notifications to user ${userId}`,
);
client.emit('unreadNotifications', unreadNotifications);
}
} catch (error) {
this.logger.error(
`Error fetching unread notifications for user ${userId}: ${error.message}`,
);
}
}
}
} catch (e) {
this.logger.error(`Authentication error for ${client.id}: ${e.message}`);
Expand All @@ -65,6 +100,46 @@ export class ChatGateway

handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
const userId = client.data?.user?.userId;
if (userId) {
const userSockets = this.userSocketMap.get(userId) || [];
const updatedSockets = userSockets.filter(
(socketId) => socketId !== client.id,
);

if (updatedSockets.length > 0) {
this.userSocketMap.set(userId, updatedSockets);
} else {
this.userSocketMap.delete(userId);
}
}
}

sendNotificationToUser(userId: string, notification: any): void {
const notificationRoom = `notifications_${userId}`;
this.server.to(notificationRoom).emit('notification', notification);
this.logger.log(`Notification sent to user ${userId}`);
}

isUserOnline(userId: string): boolean {
return (
this.userSocketMap.has(userId) &&
this.userSocketMap.get(userId).length > 0
);
}

@UseGuards(WsJwtGuard)
@SubscribeMessage('subscribeToNotifications')
handleSubscribeToNotifications(@ConnectedSocket() client: Socket): void {
const userId = client.data.user.userId;
const notificationRoom = `notifications_${userId}`;

client.join(notificationRoom);
this.logger.log(`User ${userId} subscribed to notifications`);
client.emit('notificationSubscription', {
success: true,
message: 'Subscribed to notifications',
});
}

@SubscribeMessage('test')
Expand Down
2 changes: 2 additions & 0 deletions src/chat/chat.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { Service, ServiceSchema } from '../services/schemas/service.schema';
import { User, UserSchema } from '../users/schemas/user.schema';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { NotificationsModule } from '../notifications/notifications.module';

@Module({
imports: [
Expand All @@ -27,6 +28,7 @@ import { ConfigService } from '@nestjs/config';
forwardRef(() => UserModule),
forwardRef(() => ServiceBookingsModule),
forwardRef(() => ServicesModule),
forwardRef(() => NotificationsModule),
],
providers: [ChatGateway, ChatService, JwtService, ConfigService],
exports: [ChatService, ChatGateway],
Expand Down
4 changes: 3 additions & 1 deletion src/notifications/notifications.module.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { Module } from '@nestjs/common';
import { Module, forwardRef } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { NotificationService } from './notifications.service';
import { NotificationsController } from './notifications.controller';
import {
Notification,
NotificationSchema,
} from './schemas/notification.schema';
import { ChatModule } from '../chat/chat.module';

@Module({
imports: [
MongooseModule.forFeature([
{ name: Notification.name, schema: NotificationSchema },
]),
forwardRef(() => ChatModule),
],
controllers: [NotificationsController],
providers: [NotificationService],
Expand Down
22 changes: 21 additions & 1 deletion src/notifications/notifications.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable, Logger, forwardRef, Inject } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { Notification } from './schemas/notification.schema';
import { ChatGateway } from '../chat/chat.gateway';

@Injectable()
export class NotificationService {
Expand All @@ -10,6 +11,8 @@ export class NotificationService {
constructor(
@InjectModel(Notification.name)
private notificationModel: Model<Notification>,
@Inject(forwardRef(() => ChatGateway))
private readonly chatGateway: ChatGateway,
) {}

async createNotification(notificationData: {
Expand Down Expand Up @@ -52,6 +55,23 @@ export class NotificationService {
this.logger.log(
`Created notification ${savedNotification._id} for user ${recipientId}`,
);

const recipientIdString = recipientId.toString();
if (this.chatGateway.isUserOnline(recipientIdString)) {
const notificationToSend = savedNotification.toObject();
this.chatGateway.sendNotificationToUser(
recipientIdString,
notificationToSend,
);
this.logger.log(
`Real-time notification sent to user ${recipientIdString}`,
);
} else {
this.logger.log(
`User ${recipientIdString} is offline, notification will be delivered when they connect`,
);
}

return savedNotification;
} catch (error) {
this.logger.error(
Expand Down
Loading