Skip to content

Commit

Permalink
Merge pull request #270 from boostcampwm2023/BE-SendPush-#267
Browse files Browse the repository at this point in the history
[BE/#267] 채팅 푸시 알림 전송 구현
  • Loading branch information
namewhat99 authored Dec 3, 2023
2 parents c6eb04c + 2167616 commit c72911e
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 16 deletions.
1 change: 0 additions & 1 deletion BE/src/chat/chat.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { UserEntity } from 'src/entities/user.entity';
ChatEntity,
UserEntity,
RegistrationTokenEntity,

]),
],
controllers: [ChatController],
Expand Down
19 changes: 19 additions & 0 deletions BE/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ChatRoomEntity } from '../entities/chatRoom.entity';
import { ChatEntity } from 'src/entities/chat.entity';
import { ChatDto } from './dto/chat.dto';
import { UserEntity } from 'src/entities/user.entity';
import { FcmHandler, PushMessage } from '../utils/fcmHandler';

@Injectable()
export class ChatService {
Expand All @@ -18,6 +19,7 @@ export class ChatService {
private chatRepository: Repository<ChatEntity>,
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>,
private fcmHandler: FcmHandler,
) {}

async saveMessage(message: ChatDto) {
Expand Down Expand Up @@ -106,4 +108,21 @@ export class ChatService {
throw new HttpException('권한이 없습니다.', 403);
}
}

async sendPush(message: ChatDto) {
const chatRoom = await this.chatRoomRepository.findOne({
where: { id: message.room_id },
relations: ['writerUser', 'userUser'],
});
const receiver: UserEntity =
chatRoom.writerUser.user_hash === message.sender
? chatRoom.userUser
: chatRoom.writerUser;
const pushMessage: PushMessage = this.fcmHandler.makeChatPushMessage(
receiver.nickname,
message.message,
message.room_id,
);
await this.fcmHandler.sendPush(receiver.user_hash, pushMessage);
}
}
37 changes: 25 additions & 12 deletions BE/src/chat/chats.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
Expand All @@ -13,7 +14,7 @@ import { ChatDto } from './dto/chat.dto';
@WebSocketGateway({
path: 'chats',
})
export class ChatsGateway implements OnGatewayConnection {
export class ChatsGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer() server: Server;
private rooms = new Map<number, Set<Websocket>>();

Expand All @@ -25,6 +26,14 @@ export class ChatsGateway implements OnGatewayConnection {

handleDisconnect(client: Websocket) {
console.log(`on disconnect : ${client}`);
if (client.roomId) {
const roomId = client.roomId;
const room = this.rooms.get(roomId);
room.delete(client);
if (room.size === 0) {
this.rooms.delete(roomId);
}
}
}

@SubscribeMessage('send-message')
Expand All @@ -35,34 +44,38 @@ export class ChatsGateway implements OnGatewayConnection {
console.log(message);
const room = this.rooms.get(message['room_id']);
const sender = message['sender'];
console.log(room);
room.forEach((people) => {
if (people !== client)
people.send(JSON.stringify({ sender, message: message['message'] }));
});
await this.chatService.saveMessage(message);
if (room.size === 1) {
await this.chatService.sendPush(message);
} else {
room.forEach((people) => {
if (people !== client)
people.send(JSON.stringify({ sender, message: message['message'] }));
});
}
}

@SubscribeMessage('join-room')
joinRoom(
@MessageBody() message: object,
@ConnectedSocket() client: Websocket,
) {
const roomName = message['room_id'];
if (this.rooms.has(roomName)) this.rooms.get(roomName).add(client);
else this.rooms.set(roomName, new Set([client]));
const roomId = message['room_id'];
client.roomId = roomId;
if (this.rooms.has(roomId)) this.rooms.get(roomId).add(client);
else this.rooms.set(roomId, new Set([client]));
}

@SubscribeMessage('leave-room')
leaveRoom(
@MessageBody() message: object,
@ConnectedSocket() client: Websocket,
) {
const roomName = message['room'];
const room = this.rooms.get(roomName);
const roomId = message['room'];
const room = this.rooms.get(roomId);
room.delete(client);
if (room.size === 0) {
this.rooms.delete(roomName);
this.rooms.delete(roomId);
}
console.log(this.rooms);
}
Expand Down
19 changes: 16 additions & 3 deletions BE/src/utils/fcmHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RegistrationTokenEntity } from '../entities/registrationToken.entity';

interface PushMessage {
export interface PushMessage {
title: string;
body: string;
data: any;
Expand Down Expand Up @@ -40,14 +40,13 @@ export class FcmHandler {
},
},
data: {
room_id: pushMessage.data.room_id.toString(),
...pushMessage.data,
},
};
admin
.messaging()
.send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
Expand All @@ -64,4 +63,18 @@ export class FcmHandler {
}
return registrationToken.registration_token;
}

makeChatPushMessage(
nickname: string,
message: string,
roomId: number,
): PushMessage {
return {
title: nickname,
body: message,
data: {
room_id: roomId.toString(),
},
};
}
}

0 comments on commit c72911e

Please sign in to comment.