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. 43
      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')
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 otherId = other.ftId
const channels = await this.channelService.getChannelsForUser(+profile.id)
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 === ''
)
})
}

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

@ -19,6 +19,7 @@ import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import ConnectedUser from './entity/connection.entity'
import { ConnectionDto } from './dto/connection.dto'
import { plainToClass } from 'class-transformer'
@WebSocketGateway({
cors: { origin: /^(http|ws):\/\/localhost(:\d+)?$/ }
@ -43,32 +44,42 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@SubscribeMessage('joinChannel')
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)
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')
}
const user = (await this.userService.findUser(connect.UserId)) as User
if ( channel.password !== '' &&
!(await bcrypt.compare(channel.password, connect.pwd))
console.log('2')
const user = await this.userService.getFullUser(connect.UserId)
console.log('3')
console.log('Channel psw: ', channel.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)
{
const conUser = new ConnectedUser()
conUser.user = user
conUser.channel = channel
conUser.socket = socket.id
await this.connectedUserRepository.save(conUser)
console.log('5')
const conUser = {
user,
channel,
socket: socket.id
}
this.connectedUserRepository.create(conUser)
const messages = await this.messageService.findMessagesInChannelForUser(
channel,
user
)
this.server.to(socket.id).emit('messages', messages)
await socket.join(channel.name)
await socket.join(channel.id.toString())
}
@SubscribeMessage('leaveChannel')
@ -80,7 +91,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@SubscribeMessage('addMessage')
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)
if (
(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(
message
)
socket.in(channel.name).emit('newMessage', createdMessage)
socket.in(channel.toString()).emit('newMessage', createdMessage)
}
@SubscribeMessage('kickUser')

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

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

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

@ -30,12 +30,14 @@ export class MessageService {
channel: Channel,
user: User
): 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')
.where('message.channel = :chan', { chan: channel })
.andWhere('message.author NOT IN (:...blocked)', {
blocked: user.blocked
})
.where('channel.id = :chanId', { chanId: channel.id })
.leftJoinAndSelect('message.author', 'author')
.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')
@UseGuards(AuthenticatedGuard)
async getBlockedUsers (
@Profile42() profile: Profile
): Promise<User[]> {
async getBlockedUsers (@Profile42() profile: Profile): Promise<User[]> {
const user = await this.usersService.getFullUser(profile.id)
if (user === null) throw new BadRequestException('User not found')
return user.blocked

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

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

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

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

Loading…
Cancel
Save