Browse Source

messages start to work, still wip

chat in progress
master
nicolas-arnaud 2 years ago
parent
commit
b0bb4f4dbe
  1. 11
      back/volume/src/chat/chat.controller.ts
  2. 47
      back/volume/src/chat/chat.gateway.ts
  3. 10
      back/volume/src/chat/chat.service.ts
  4. 12
      back/volume/src/chat/message.service.ts
  5. 4
      back/volume/src/users/users.controller.ts
  6. 4
      back/volume/src/users/users.service.ts
  7. 7
      front/volume/src/components/Chat.svelte

11
back/volume/src/chat/chat.controller.ts

@ -210,13 +210,20 @@ export class ChatController {
} }
@Get('dms/:otherId') @Get('dms/:otherId')
async getDMsForUser (@Profile42() profile: Profile, @Param('otherName') otherName: string): Promise<Channel[]> { async getDMsForUser (
@Profile42() profile: Profile,
@Param('otherName') otherName: string
): Promise<Channel[]> {
const other = await this.usersService.findUserByName(otherName) const other = await this.usersService.findUserByName(otherName)
const otherId = other.ftId const otherId = other.ftId
const channels = await this.channelService.getChannelsForUser(+profile.id) const channels = await this.channelService.getChannelsForUser(+profile.id)
return channels.filter((channel: Channel) => { return channels.filter((channel: Channel) => {
return channel.users?.some((ch) => ch.id === otherId) && channel.isPrivate && channel.password === '' return (
channel.users?.some((ch) => ch.id === otherId) &&
channel.isPrivate &&
channel.password === ''
)
}) })
} }

47
back/volume/src/chat/chat.gateway.ts

@ -19,6 +19,7 @@ import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm' import { Repository } from 'typeorm'
import ConnectedUser from './entity/connection.entity' import ConnectedUser from './entity/connection.entity'
import { ConnectionDto } from './dto/connection.dto' import { ConnectionDto } from './dto/connection.dto'
import { plainToClass } from 'class-transformer'
@WebSocketGateway({ @WebSocketGateway({
cors: { origin: /^(http|ws):\/\/localhost(:\d+)?$/ } cors: { origin: /^(http|ws):\/\/localhost(:\d+)?$/ }
@ -43,32 +44,42 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@SubscribeMessage('joinChannel') @SubscribeMessage('joinChannel')
async onJoinChannel (socket: Socket, connect: ConnectionDto): Promise<void> { async onJoinChannel (socket: Socket, connect: ConnectionDto): Promise<void> {
console.log(connect.ChannelId, connect.UserId, connect.pwd) console.log(
'User %s is trying to join channel %s',
connect.UserId,
connect.ChannelId,
connect.pwd
)
const channel = await this.chatService.getFullChannel(connect.ChannelId) const channel = await this.chatService.getFullChannel(connect.ChannelId)
if (channel.banned.find((ban) => ban.id === connect.UserId) !== null) { console.log('1')
if (channel.banned.findIndex((ban) => ban.ftId === connect.UserId) !== -1) {
throw new WsException('You are banned from entering this channel') throw new WsException('You are banned from entering this channel')
} }
const user = (await this.userService.findUser(connect.UserId)) as User console.log('2')
if ( channel.password !== '' && const user = await this.userService.getFullUser(connect.UserId)
!(await bcrypt.compare(channel.password, connect.pwd)) console.log('3')
) { console.log('Channel psw: ', channel.password)
throw new WsException('Wrong password') if (channel.password && channel.password !== '') {
if (
!connect.pwd ||
!(await bcrypt.compare(connect.pwd, channel.password))
) {
throw new WsException('Wrong password')
}
} else await this.chatService.addUserToChannel(channel, user) } else await this.chatService.addUserToChannel(channel, user)
console.log('5')
{ const conUser = {
const conUser = new ConnectedUser() user,
conUser.user = user channel,
conUser.channel = channel socket: socket.id
conUser.socket = socket.id
await this.connectedUserRepository.save(conUser)
} }
this.connectedUserRepository.create(conUser)
const messages = await this.messageService.findMessagesInChannelForUser( const messages = await this.messageService.findMessagesInChannelForUser(
channel, channel,
user user
) )
this.server.to(socket.id).emit('messages', messages) this.server.to(socket.id).emit('messages', messages)
await socket.join(channel.name) await socket.join(channel.id.toString())
} }
@SubscribeMessage('leaveChannel') @SubscribeMessage('leaveChannel')
@ -80,7 +91,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@SubscribeMessage('addMessage') @SubscribeMessage('addMessage')
async onAddMessage (socket: Socket, message: CreateMessageDto): Promise<void> { async onAddMessage (socket: Socket, message: CreateMessageDto): Promise<void> {
console.log(JSON.stringify(message)); console.log(JSON.stringify(message))
const channel = await this.chatService.getChannel(message.ChannelId) const channel = await this.chatService.getChannel(message.ChannelId)
if ( if (
(await this.chatService.getMuteDuration(channel.id, message.UserId)) > 0 (await this.chatService.getMuteDuration(channel.id, message.UserId)) > 0
@ -90,7 +101,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
const createdMessage: Message = await this.messageService.createMessage( const createdMessage: Message = await this.messageService.createMessage(
message message
) )
socket.in(channel.name).emit('newMessage', createdMessage) socket.in(channel.toString()).emit('newMessage', createdMessage)
} }
@SubscribeMessage('kickUser') @SubscribeMessage('kickUser')

10
back/volume/src/chat/chat.service.ts

@ -25,9 +25,13 @@ export class ChatService {
let newChannel: Channel let newChannel: Channel
if (channel.isDM) { if (channel.isDM) {
const otherUser: User | null = await this.usersService.findUserByName(channel.otherDMedUsername) const otherUser: User | null = await this.usersService.findUserByName(
channel.otherDMedUsername
)
if (otherUser == null) { if (otherUser == null) {
throw new NotFoundException(`User #${channel.otherDMedUsername} not found`) throw new NotFoundException(
`User #${channel.otherDMedUsername} not found`
)
} }
newChannel = this.createDM(user, otherUser) newChannel = this.createDM(user, otherUser)
} else { } else {
@ -179,7 +183,7 @@ export class ChatService {
async getMuteDuration (id: number, userId: number): Promise<number> { async getMuteDuration (id: number, userId: number): Promise<number> {
const channel = await this.ChannelRepository.findOne({ const channel = await this.ChannelRepository.findOne({
where: { id }, where: { id }
}) })
if (channel === null) { if (channel === null) {
throw new NotFoundException(`Channel #${id} not found`) throw new NotFoundException(`Channel #${id} not found`)

12
back/volume/src/chat/message.service.ts

@ -30,12 +30,14 @@ export class MessageService {
channel: Channel, channel: Channel,
user: User user: User
): Promise<Message[]> { ): Promise<Message[]> {
return await this.MessageRepository.createQueryBuilder('message') console.log('findMessagesInChannelForUser', channel.id, user.ftId)
const blockeds = user.blocked.map((u) => +u.ftId)
console.log(JSON.stringify(blockeds))
const messages = await this.MessageRepository.createQueryBuilder('message')
.innerJoin('message.channel', 'channel') .innerJoin('message.channel', 'channel')
.where('message.channel = :chan', { chan: channel }) .where('channel.id = :chanId', { chanId: channel.id })
.andWhere('message.author NOT IN (:...blocked)', { .leftJoinAndSelect('message.author', 'author')
blocked: user.blocked
})
.getMany() .getMany()
return messages.filter((m) => !blockeds.includes(m.author.ftId))
} }
} }

4
back/volume/src/users/users.controller.ts

@ -37,9 +37,7 @@ export class UsersController {
@Get('blocked') @Get('blocked')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getBlockedUsers ( async getBlockedUsers (@Profile42() profile: Profile): Promise<User[]> {
@Profile42() profile: Profile
): Promise<User[]> {
const user = await this.usersService.getFullUser(profile.id) const user = await this.usersService.getFullUser(profile.id)
if (user === null) throw new BadRequestException('User not found') if (user === null) throw new BadRequestException('User not found')
return user.blocked return user.blocked

4
back/volume/src/users/users.service.ts

@ -59,15 +59,15 @@ export class UsersService {
} }
async getFullUser (ftId: number): Promise<User> { async getFullUser (ftId: number): Promise<User> {
let user = await this.usersRepository.findOne({ const user = await this.usersRepository.findOne({
where: { ftId }, where: { ftId },
relations: ['results', 'blocked', 'friends'] relations: ['results', 'blocked', 'friends']
}) })
if (user === null) throw new BadRequestException('User not found.') if (user === null) throw new BadRequestException('User not found.')
user.socketKey = ''
return user return user
} }
async findOnlineUsers (): Promise<User[]> { async findOnlineUsers (): Promise<User[]> {
const users = await this.usersRepository.find({ const users = await this.usersRepository.find({
where: { status: 'online' } where: { status: 'online' }

7
front/volume/src/components/Chat.svelte

@ -23,7 +23,6 @@
mode: "cors", mode: "cors",
}); });
if (res.ok) blockedUsers = await res.json(); if (res.ok) blockedUsers = await res.json();
}); });
socket.on("messages", (msgs: Array<chatMessagesType>) => { socket.on("messages", (msgs: Array<chatMessagesType>) => {
chatMessages = msgs; chatMessages = msgs;
@ -35,7 +34,7 @@
onDestroy(() => { onDestroy(() => {
socket.emit("leaveChannel"); socket.emit("leaveChannel");
}) });
//--------------------------------------------------------------------------------/ //--------------------------------------------------------------------------------/
@ -46,7 +45,7 @@
text: newText, text: newText,
UserId: $store.ftId, UserId: $store.ftId,
ChannelId: channel.id, ChannelId: channel.id,
}) });
newText = ""; newText = "";
const messagesDiv = document.querySelector(".messages"); const messagesDiv = document.querySelector(".messages");
if (messagesDiv) { if (messagesDiv) {
@ -276,7 +275,7 @@
on:keydown={() => openProfile(message.author.username)} on:keydown={() => openProfile(message.author.username)}
style="cursor: pointer;" style="cursor: pointer;"
> >
{message.author} {message.author.username}
</span>: {message.text} </span>: {message.text}
{/if} {/if}
</p> </p>

Loading…
Cancel
Save