summaryrefslogtreecommitdiff
path: root/server/providers/gateways/chat_room.gateway.ts
blob: 9c305bf5a3eb0a90981d7409f26d46f87aba12a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { UseGuards } from '@nestjs/common';
import {
  ConnectedSocket,
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  OnGatewayInit,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsException,
} from '@nestjs/websockets';
import { GatewayJwtBody } from 'server/decorators/gateway_jwt_body.decorator';
import { JwtBodyDto } from 'server/dto/jwt_body.dto';
import { Server, Socket } from 'socket.io';
import { GatewayAuthGuard } from '../guards/gatewayauth.guard';
import { ChatRoomService } from '../services/chat_room.service';
import { JwtService } from '../services/jwt.service';
import { UsersService } from '../services/users.service';

@WebSocketGateway()
@UseGuards(GatewayAuthGuard)
export class ChatRoomGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  constructor(
    private jwtService: JwtService,
    private userService: UsersService,
    private chatRoomService: ChatRoomService,
  ) {
    setInterval(async () => {
      const inactiveRooms = await chatRoomService.inactiveRooms();
      inactiveRooms.forEach((room) => {
        this.server.to(room.id).emit('inactive', room.id);
        chatRoomService.remove(room);
      });
    }, 5 * (1000 * 60));
  }

  afterInit(server: Server) {
    console.log('Sockets initialized');
  }

  async handleConnection(client: Socket) {
    try {
      const jwtBody = this.jwtService.parseToken(client.handshake.auth.token);
      const user = await this.userService.find(jwtBody.userId);

      const chatRoom = await this.chatRoomService.findById(client.handshake.query.chatRoomId as unknown as string);
      if (chatRoom) {
        chatRoom.lastModified = new Date();
        this.chatRoomService.save(chatRoom);

        await this.chatRoomService.connectUser(chatRoom, user);
        client.join(chatRoom.id);
        this.server.to(chatRoom.id).emit('userlist', {
          users: await this.chatRoomService.connectedUsers(chatRoom),
        });
      }
    } catch (e) {
      throw new WsException(e.message);
    }
  }

  async handleDisconnect(client: Socket) {
    console.log('Client Disconnected');
    const jwtBody = this.jwtService.parseToken(client.handshake.auth.token);
    const user = await this.userService.find(jwtBody.userId);

    const chatRoom = await this.chatRoomService.findById(client.handshake.query.chatRoomId as unknown as string);
    if (chatRoom) {
      await this.chatRoomService.disconnectUser(chatRoom, user);
      this.server.to(chatRoom.id).emit('userlist', {
        users: await this.chatRoomService.connectedUsers(chatRoom),
      });
    }
  }

  @SubscribeMessage('message')
  public async handleMessage(
    @ConnectedSocket() client: Socket,
    @MessageBody() data: string,
    @GatewayJwtBody() jwtBody: JwtBodyDto,
  ) {
    const user = await this.userService.find(jwtBody.userId);

    const chatRoom = await this.chatRoomService.findById(client.handshake.query.chatRoomId as unknown as string);
    if (chatRoom) {
      chatRoom.lastModified = new Date();
      this.chatRoomService.save(chatRoom);

      this.server.to(chatRoom.id).emit('new-message', {
        id: user.id * Math.random() * Math.pow(2, 16) * Date.now(),
        content: data,
        userName: `${user.firstName} ${user.lastName}`,
        userId: user.id,
      });
    }
  }
}