Browse Source

Merge commit '67e167b361e69abfc61413857f76e5958cfc6d66' into v2

master
nicolas-arnaud 2 years ago
parent
commit
aaf9c4fc95
  1. 1
      back/package.json
  2. 6
      back/src/app.module.ts
  3. 8
      back/src/chat/chat.gateway.ts
  4. 22
      back/src/chat/chat.service.ts
  5. 10
      back/src/users/users.service.ts
  6. 58
      front/src/App.svelte
  7. 62
      front/src/components/Chat.svelte

1
back/package.json

@ -48,7 +48,6 @@
"cookie-parser": "^1.4.6",
"express": "^4.18.2",
"express-session": "^1.17.3",
"joi": "^17.8.3",
"multer": "^1.4.5-lts.1",
"nestjs-paginate": "^4.13.0",
"nodemailer": "^6.9.1",

6
back/src/app.module.ts

@ -1,7 +1,5 @@
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { TypeOrmModule } from '@nestjs/typeorm'
import * as Joi from 'joi'
import { ScheduleModule } from '@nestjs/schedule'
import { AuthModule } from './auth/auth.module'
@ -13,9 +11,7 @@ import { UsersModule } from './users/users.module'
imports: [
ScheduleModule.forRoot(),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
useFactory: () => ({
type: 'postgres',
host: process.env.POSTGRES_HOST || 'localhost',
port: (process.env.POSTGRES_PORT || 5432) as number,

8
back/src/chat/chat.gateway.ts

@ -58,7 +58,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
async onJoinChannel(socket: Socket, connect: ConnectionDto): Promise<void> {
await this.connectedUserRepository.delete({ user: connect.UserId })
const channel = await this.chatService.getFullChannel(connect.ChannelId);
if (channel.banned.findIndex((ban) => +ban[0] === +connect.UserId) !== -1) {
if (channel.banned.some((ban) => +ban[0] === +connect.UserId)) {
this.server
.to(socket.id)
.emit('failedJoin', 'You are banned from this channel');
@ -101,7 +101,9 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
this.server.in(channel.id.toString()).disconnectSockets();
await this.chatService.removeChannel(channel.id);
} else {
channel.users = channel.users.filter((e) => e.ftId !== connect.user);
channel.users = channel.users.filter((usr: User) => usr.ftId !== connect.user);
channel.admins = channel.admins.filter((usr: User) => usr.ftId !== connect.user);
await this.chatService.save(channel);
}
await this.connectedUserRepository.delete({ socket: socket.id });
}
@ -131,7 +133,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
}
if (
channel.owner.ftId !== kick.from &&
channel.admins.findIndex((usr) => +usr.ftId === kick.from) === -1
!channel.admins.some((usr) => +usr.ftId === kick.from)
) {
throw new WsException('You do not have the required privileges')
}

22
back/src/chat/chat.service.ts

@ -19,7 +19,7 @@ export class ChatService {
) {}
async createChannel (channel: CreateChannelDto): Promise<Channel> {
const user: User | null = await this.usersService.findUser(channel.owner)
const user: User | null = await this.usersService.getFullUser(channel.owner)
if (user == null) {
throw new BadRequestException(`User #${channel.owner} not found`)
}
@ -29,14 +29,10 @@ export class ChatService {
const otherUser: User | null = await this.usersService.findUserByName(
channel.otherDMedUsername
)
if (otherUser == null) {
throw new BadRequestException(
`User #${channel.otherDMedUsername} not found`
)
}
if (otherUser.id === user.id) {
throw new BadRequestException('Cannot DM yourself')
}
if (otherUser == null) throw new BadRequestException(`User #${channel.otherDMedUsername} not found`)
if (user.blocked.some((usr: User) => usr.ftId === otherUser.ftId))
throw new BadRequestException(`User ${otherUser.username} is blocked`)
if (otherUser.id === user.id) throw new BadRequestException('Cannot DM yourself')
const channels = await this.getChannelsForUser(user.id)
const dmAlreadyExists = channels.find((channel: Channel) => {
@ -186,7 +182,7 @@ export class ChatService {
if (channel === null) {
throw new BadRequestException(`Channel #${id} not found`)
}
return channel.admins.findIndex((user) => user.ftId === userId) !== -1
return channel.admins.some((user) => user.ftId === userId)
}
async isUser (id: number, userId: number): Promise<boolean> {
@ -197,7 +193,7 @@ export class ChatService {
if (channel === null) {
throw new BadRequestException(`Channel #${id} not found`)
}
return channel.users.findIndex((user) => user.ftId === userId) !== -1
return channel.users.some((user) => user.ftId === userId)
}
async isBanned (id: number, userId: number): Promise<boolean> {
@ -207,7 +203,7 @@ export class ChatService {
if (channel === null) {
throw new BadRequestException(`Channel #${id} not found`)
}
return channel.banned.findIndex((ban) => +ban[0] === userId) !== -1
return channel.banned.some((ban) => +ban[0] === userId)
}
async isMuted (id: number, userId: number): Promise<boolean> {
@ -217,6 +213,6 @@ export class ChatService {
if (channel === null) {
throw new BadRequestException(`Channel #${id} not found`)
}
return channel.muted.findIndex((mute) => +mute[0] === userId) !== -1
return channel.muted.some((mute) => +mute[0] === userId)
}
}

10
back/src/users/users.service.ts

@ -151,7 +151,7 @@ export class UsersService {
}
})
if (user === null) throw new BadRequestException('User not found.')
if (user.friends.findIndex((friend) => friend.ftId === targetFtId) !== -1) {
if (user.friends.some((friend) => friend.ftId === targetFtId)) {
return 'You are already friends.'
}
const target: User | null = await this.usersRepository.findOne({
@ -165,14 +165,10 @@ export class UsersService {
const id = user.followers.findIndex(
(follower) => follower.ftId === targetFtId
)
if (
target.followers.findIndex((follower) => follower.ftId === user.ftId) !==
-1
) {
if (target.followers.some((follower) => follower.ftId === user.ftId)) {
return 'Invitation already sent.'
} else if (
user.followers.findIndex((follower) => follower.ftId === targetFtId) !==
-1
user.followers.some((follower) => follower.ftId === targetFtId)
) {
user.friends.push(target)
target.friends.push(user)

58
front/src/App.svelte

@ -68,63 +68,6 @@
setAppState(APPSTATE.PROFILE_ID);
}
$: console.log("New profileUsername:", profileUsername)
async function getDMs(username: string): Promise<Response | null> {
const res = await fetch(API_URL + "/channels/dms/" + username, {
credentials: "include",
mode: "cors",
})
if (res.ok)
return res;
else
return null;
}
async function openDirectChat(event: CustomEvent<string>) {
const DMUsername = event.detail;
let DMChannel: Array<ChannelsType> = [];
const res = await getDMs(DMUsername)
if (res && res.ok) {
DMChannel = await res.json();
if (DMChannel.length != 0)
await formatChannelNames(DMChannel)
setAppState(APPSTATE.CHANNELS + "#" + DMChannel[0].name)
} else {
console.log("Creating DMChannel: " + $store.username + "&" + DMUsername)
fetch(API_URL + "/channels", {
credentials: "include",
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "none",
owner: $store.ftId,
password: "",
isPrivate: true,
isDM: true,
otherDMedUsername: DMUsername
}),
}).then(async () => {
const response = await getDMs(DMUsername)
if (response && response.ok) {
DMChannel = await response.json();
if (DMChannel.length != 0) {
await formatChannelNames(DMChannel)
setAppState(APPSTATE.CHANNELS + "#" + DMChannel[0].name)
} else {
show_popup("Error: Couldn't create DM.", false)
}
} else {
show_popup("Error: Couldn't create DM.", false)
}
}).catch(() => {
show_popup("Error: Couldn't create DM.", false)
})
}
}
async function clickHistory() {
setAppState(APPSTATE.HISTORY);
}
@ -196,7 +139,6 @@
on:view-profile={openIdProfile}
on:add-friend={addFriend}
on:invite-to-game={pong.inviteToGame}
on:send-message={openDirectChat}
on:return-home={resetAppState}
/>
</div>

62
front/src/components/Chat.svelte

@ -153,6 +153,62 @@
//--------------------------------------------------------------------------------/
async function getDMs(username: string): Promise<Response | null> {
const res = await fetch(API_URL + "/channels/dms/" + username, {
credentials: "include",
mode: "cors",
})
if (res.ok)
return res;
else
return null;
}
async function openDirectChat() {
const DMUsername = selectedUser;
let DMChannel: Array<ChannelsType> = [];
const res = await getDMs(DMUsername)
if (res && res.ok) {
DMChannel = await res.json();
if (DMChannel.length != 0)
await formatChannelNames(DMChannel)
setAppState(APPSTATE.CHANNELS + "#" + DMChannel[0].name)
} else {
console.log("Creating DMChannel: " + $store.username + "&" + DMUsername)
fetch(API_URL + "/channels", {
credentials: "include",
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "none",
owner: $store.ftId,
password: "",
isPrivate: true,
isDM: true,
otherDMedUsername: DMUsername
}),
}).then(async () => {
const response = await getDMs(DMUsername)
if (response && response.ok) {
DMChannel = await response.json();
if (DMChannel.length != 0) {
await formatChannelNames(DMChannel)
setAppState(APPSTATE.CHANNELS + "#" + DMChannel[0].name)
} else {
show_popup("Error: Couldn't create DM.", false)
}
} else {
show_popup("Error: Couldn't create DM.", false)
}
}).catch(() => {
show_popup("Error: Couldn't create DM.", false)
})
}
}
const blockUser = async (username: string) => {
let response = await fetch(API_URL + "/users/" + username + "/byname", {
credentials: "include",
@ -366,10 +422,6 @@
socket.disconnect();
}
};
function onSendMessage() {
dispatch("send-message", selectedUser);
showProfileMenu = false;
}
</script>
<div class="overlay">
@ -398,7 +450,7 @@
>
<ul>
<li>
<button on:click={onSendMessage}> Send Message </button>
<button on:click={openDirectChat}> Send Message </button>
</li>
<li>
<button on:click={() => dispatch("view-profile", selectedUser)}>

Loading…
Cancel
Save