Browse Source

fix chat socket not recreated

master
nicolas-arnaud 2 years ago
parent
commit
7b1fa18a84
  1. 68
      back/volume/src/chat/chat.controller.ts
  2. 16
      back/volume/src/chat/chat.gateway.ts
  3. 1
      back/volume/src/chat/message.service.ts
  4. 26
      front/volume/src/components/Channels.svelte
  5. 25
      front/volume/src/components/Chat.svelte

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

@ -30,6 +30,34 @@ export class ChatController {
private readonly usersService: UsersService private readonly usersService: UsersService
) {} ) {}
@Get('dms/:otherName')
async getDMsForUser (
@Profile42() profile: Profile,
@Param('otherName') otherName: string
): Promise<Channel[]> {
const user = await this.usersService.findUser(profile.fdId)
const other = await this.usersService.findUserByName(otherName)
const channels = await this.channelService.getChannelsForUser(+profile.id)
if (user === null) {
throw new BadRequestException('User not found')
}
const dms = channels.filter((channel: Channel) => {
return (
(channel.name === (user.ftId + '&' + other.ftId) ||
channel.name === (other.ftId + '&' + user.ftId)) &&
channel.isPrivate &&
(channel.password === undefined || channel.password === '')
)
})
dms.forEach((c) => {
c.users.forEach((u) => u.socketKey = '')
c.admins.forEach((u) => u.socketKey = '')
c.owner.socketKey = ''
})
return dms
}
@Post(':id/invite') @Post(':id/invite')
async addUser ( async addUser (
@Param('id', ParseIntPipe) id: number, @Param('id', ParseIntPipe) id: number,
@ -211,34 +239,6 @@ export class ChatController {
await this.channelService.updatePassword(id, data.password) await this.channelService.updatePassword(id, data.password)
} }
@Get()
async getChannelsForUser (@Profile42() profile: Profile): Promise<Channel[]> {
return await this.channelService.getChannelsForUser(+profile.id)
}
@Get('dms/:otherName')
async getDMsForUser (
@Profile42() profile: Profile,
@Param('otherName') otherName: string
): Promise<Channel[]> {
const user = await this.usersService.findUser(profile.fdId)
const other = await this.usersService.findUserByName(otherName)
const channels = await this.channelService.getChannelsForUser(+profile.id)
if (user === null) {
throw new BadRequestException('User not found')
}
const dms = channels.filter((channel: Channel) => {
return (
(channel.name === (user.ftId + '&' + other.ftId) ||
channel.name === (other.ftId + '&' + user.ftId)) &&
channel.isPrivate &&
(channel.password === undefined || channel.password === '')
)
})
return dms
}
@Get(':id/leave') @Get(':id/leave')
async leaveChannel ( async leaveChannel (
@Profile42() profile: Profile, @Profile42() profile: Profile,
@ -254,8 +254,18 @@ export class ChatController {
await this.channelService.save(channel) await this.channelService.save(channel)
} }
@Get()
async getChannelsForUser (@Profile42() profile: Profile): Promise<Channel[]> {
let chan = await this.channelService.getChannelsForUser(+profile.id)
return chan;
}
@Post() @Post()
async createChannel (@Body() channel: CreateChannelDto): Promise<Channel> { async createChannel (@Body() channel: CreateChannelDto): Promise<Channel> {
return await this.channelService.createChannel(channel) let chan = await this.channelService.createChannel(channel)
chan.users.forEach((u) => u.socketKey = '')
chan.admins.forEach((u) => u.socketKey = '')
chan.owner.socketKey = ''
return chan;
} }
} }

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

@ -45,14 +45,10 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
connect.pwd connect.pwd
) )
const channel = await this.chatService.getFullChannel(connect.ChannelId) const channel = await this.chatService.getFullChannel(connect.ChannelId)
console.log('1')
if (channel.banned.findIndex((ban) => ban.ftId === connect.UserId) !== -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')
} }
console.log('2')
const user = await this.userService.getFullUser(connect.UserId) const user = await this.userService.getFullUser(connect.UserId)
console.log('3')
console.log('Channel psw: ', channel.password)
if (channel.password && channel.password !== '') { if (channel.password && channel.password !== '') {
if ( if (
!connect.pwd || !connect.pwd ||
@ -61,18 +57,22 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
throw new WsException('Wrong password') throw new WsException('Wrong password')
} }
} else await this.chatService.addUserToChannel(channel, user) } else await this.chatService.addUserToChannel(channel, user)
console.log('5')
console.log('8')
const messages = await this.messageService.findMessagesInChannelForUser( const messages = await this.messageService.findMessagesInChannelForUser(
channel, channel,
user user
) )
console.log('9')
this.server.to(socket.id).emit('messages', messages) this.server.to(socket.id).emit('messages', messages)
console.log('10')
await socket.join(channel.id.toString()) await socket.join(channel.id.toString())
} }
@SubscribeMessage('getMessages')
async onGetMessages (socket: Socket, connect: ConnectionDto): Promise<void> {
const user = await this.userService.getFullUser(connect.UserId)
const channel = await this.chatService.getFullChannel(connect.ChannelId)
const messages = await this.messageService.findMessagesInChannelForUser(channel, user)
this.server.to(socket.id).emit('messages', messages)
}
@SubscribeMessage('leaveChannel') @SubscribeMessage('leaveChannel')
async onLeaveChannel (socket: Socket): Promise<void> { async onLeaveChannel (socket: Socket): Promise<void> {
const id = socket.id as any const id = socket.id as any

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

@ -37,6 +37,7 @@ export class MessageService {
.innerJoin('message.channel', 'channel') .innerJoin('message.channel', 'channel')
.where('channel.id = :chanId', { chanId: channel.id }) .where('channel.id = :chanId', { chanId: channel.id })
.leftJoinAndSelect('message.author', 'author') .leftJoinAndSelect('message.author', 'author')
.orderBy('message.created_at', 'ASC')
.getMany() .getMany()
return messages.filter((m) => !blockeds.includes(m.author.ftId)) return messages.filter((m) => !blockeds.includes(m.author.ftId))
} }

26
front/volume/src/components/Channels.svelte

@ -4,11 +4,12 @@
name: string; name: string;
isPrivate: boolean; isPrivate: boolean;
password: string; password: string;
owner: number; owner: User;
} }
import { onMount } from "svelte"; import { onMount } from "svelte";
import { API_URL, store } from "../Auth"; import { API_URL, store } from "../Auth";
import { socket } from "../socket"; import { socket } from "../socket";
import type User from "./Profile.svelte";
</script> </script>
<script lang="ts"> <script lang="ts">
@ -44,6 +45,7 @@
export let onSelectChannel: (channel: ChannelsType) => void; export let onSelectChannel: (channel: ChannelsType) => void;
export const selectChat = (id: number) => { export const selectChat = (id: number) => {
console.log("channel: ", id)
getChannels().then(() => { getChannels().then(() => {
const channel = channels.find((c) => c.id === id); const channel = channels.find((c) => c.id === id);
if (channel) { if (channel) {
@ -55,7 +57,6 @@
}); });
}; };
const createChannel = async () => { const createChannel = async () => {
let name, friend; let name, friend;
if (channelMode === "direct") { if (channelMode === "direct") {
@ -225,23 +226,20 @@
<div> <div>
{#if channels.length > 0} {#if channels.length > 0}
<h2>Channels</h2> <h2>Channels</h2>
{#each channels.slice(0, 10) as _channels} {#each channels.slice(0, 10) as channel}
<li> <li>
<span>{_channels.name}</span> <span>{channel.name}</span>
<div style="display:block; margin-right:10%"> <div style="display:block; margin-right:10%">
<button on:click={() => selectChat(_channels.id)}>🔌</button> <button on:click={() => selectChat(channel.id)}>🔌</button>
<button <button
on:click={() => removeChannel(_channels.id)} on:click={() => removeChannel(channel.id)}
on:keydown={() => removeChannel(_channels.id)}>🗑️</button on:keydown={() => removeChannel(channel.id)}>🗑️</button
>
<button on:click={() => inviteChannel(_channels.id)}>🤝</button>
{#if _channels.isPrivate}
<button on:click={() => changePassword(_channels.id)}
>Edit Password</button
> >
{/if} <button on:click={() => inviteChannel(channel.id)}>🤝</button>
<button on:click={() => changePassword(channel.id)}>🔑</button>
</div> </div>
</li>{/each} </li>
{/each}
{:else} {:else}
<p>No channels available</p> <p>No channels available</p>
{/if} {/if}

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

@ -18,32 +18,31 @@
let chatMessages: Array<chatMessagesType> = []; let chatMessages: Array<chatMessagesType> = [];
export let channel: ChannelsType; export let channel: ChannelsType;
let newText = ""; let newText = "";
onMount(async () => { onMount(async () => {
let res = await fetch(API_URL + "/users/blocked/", { socket.connect();
credentials: "include", getMembers();
mode: "cors",
});
if (res.ok) {
blockedUsers = await res.json();
usersInterval = setInterval(async () => { usersInterval = setInterval(async () => {
getMembers(); getMembers();
}, 1000); }, 3000);
}
}); });
socket.on("messages", (msgs: Array<chatMessagesType>) => { socket.on("messages", (msgs: Array<chatMessagesType>) => {
chatMessages = msgs; chatMessages = msgs;
}); });
async function getMembers() { async function getMembers() {
if (!channel) return; if (!channel) return;
const res = await fetch(`${API_URL}/channels/${channel.id}/users`, { let res = await fetch(API_URL + "/users/blocked/", {
credentials: "include",
mode: "cors",
});
if (res.ok) blockedUsers = await res.json();
res = await fetch(`${API_URL}/channels/${channel.id}/users`, {
credentials: "include", credentials: "include",
mode: "cors" mode: "cors"
}) })
if (res.ok) { if (res.ok) chatMembers = await res.json();
chatMembers = await res.json();
} else alert(res.text())
} }
socket.on("newMessage", (msg: chatMessagesType) => { socket.on("newMessage", (msg: chatMessagesType) => {

Loading…
Cancel
Save