Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat <back> <chat, websockets>: storing websockets and userIds + receiver joins DM Room when creating DM room #58

Merged
merged 7 commits into from
Sep 26, 2022
4 changes: 0 additions & 4 deletions backend/shared/interfaces/ChatRoom.ts

This file was deleted.

4 changes: 4 additions & 0 deletions backend/shared/interfaces/UserWebsockets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class UsersWebsockets {
userId: number;
socketId: string;
}
39 changes: 38 additions & 1 deletion backend/src/chat/chat.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import {
import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
OnGatewayInit,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
Expand Down Expand Up @@ -40,7 +43,7 @@ async function passwordCompare(
transport: ['websocket'],
cors: '*/*',
})
export class ChatGateway {
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
private channelLobby = 'channelLobby';
constructor(
private readonly chatService: ChatService,
Expand All @@ -49,7 +52,27 @@ export class ChatGateway {

@WebSocketServer()
server: Server;
async handleConnection(@ConnectedSocket() client: Socket) {
const user = await this.chatService.getUserFromSocket(client);

const isRegistered = ChatService.userWebsockets.find(
(element) => element.userId === user.id,
);

if (!isRegistered) {
const newWebsocket = { userId: user.id, socketId: client.id };
ChatService.userWebsockets = [
...ChatService.userWebsockets,
newWebsocket,
];
}
}

handleDisconnect(@ConnectedSocket() client: Socket) {
ChatService.userWebsockets = ChatService.userWebsockets.filter(
(websocket) => websocket.socketId !== client.id,
);
}
/* JOIN CHANNEL LOBBY */
@UseGuards(JwtWsGuard)
@SubscribeMessage(ROUTES_BASE.CHAT.JOIN_CHANNEL_LOBBY_REQUEST)
Expand Down Expand Up @@ -174,6 +197,20 @@ export class ChatGateway {

await client.join(newDMRoom.roomName);

const receiverSocketId = this.chatService.getUserIdWebsocket(friendId);

if (receiverSocketId) {
/** Retrieve receiver's socket with the socket ID
* https://stackoverflow.com/questions/67361211/socket-io-4-0-1-get-socket-by-id
*/

const receiverSocket = this.server.sockets.sockets.get(
receiverSocketId.socketId,
DaiClement marked this conversation as resolved.
Show resolved Hide resolved
);

await receiverSocket.join(newDMRoom.roomName);
}

this.server
.in(newDMRoom.roomName)
.emit(ROUTES_BASE.CHAT.CONFIRM_DM_CHANNEL_CREATION, {
Expand Down
21 changes: 6 additions & 15 deletions backend/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { AuthService } from '../auth/auth.service';
import { Socket } from 'socket.io';
import { Server, Socket } from 'socket.io';
import { parse } from 'cookie';
import { WsException } from '@nestjs/websockets';
import { InjectRepository } from '@nestjs/typeorm';
Expand All @@ -10,7 +10,7 @@ import { User } from 'src/user/user.entity';
import Room from './room.entity';
import { UsersService } from 'src/user/user.service';
import { v4 as uuidv4 } from 'uuid';
import { ChatRoom } from 'shared/interfaces/ChatRoom';
import { UsersWebsockets } from 'shared/interfaces/UserWebsockets';
import ChannelData from 'shared/interfaces/ChannelData';
@Injectable()
export class ChatService {
Expand All @@ -24,7 +24,7 @@ export class ChatService {
private usersRepository: Repository<User>,
private userService: UsersService,
) {}
private static chatRoomList: ChatRoom[] = [];
public static userWebsockets: UsersWebsockets[] = [];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As we said by oral, i prefer having a userGateway.
But i need your code, so a approve it 😅


public async getAllPublicRooms(): Promise<ChannelData[]> {
return this.roomsRepository
Expand Down Expand Up @@ -246,18 +246,9 @@ export class ChatService {
return user;
}

//Unused fct
removeUserConnectedToRooms(roomName: string, userId): number[] {
const chatRoomIndex = ChatService.chatRoomList.findIndex(
(chatRoom) => chatRoom.roomName == roomName,
getUserIdWebsocket(receiverId: number): UsersWebsockets | undefined {
return ChatService.userWebsockets.find(
(receiver) => receiver.userId === receiverId,
);
if (ChatService.chatRoomList[chatRoomIndex].userIdList.includes(userId)) {
ChatService.chatRoomList[chatRoomIndex].userIdList =
ChatService.chatRoomList[chatRoomIndex].userIdList.filter(
(id) => id !== userId,
);
}
return ChatService.chatRoomList[chatRoomIndex].userIdList;
}
/** END ChatRoomConnectedUsers methods */
}