wip try to make chatrooms db remember users

This commit is contained in:
simplonco
2023-01-07 17:27:15 +01:00
parent 41dbee1cc0
commit d21c1d1e4e
11 changed files with 425 additions and 175 deletions

View File

@@ -14,24 +14,19 @@ export class ChatController {
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Get('rooms') @Get('rooms')
async getRooms() async getRooms(@Req() req, @Res() res)
{ {
const rooms = await this.chatService.getRooms(); console.log("in getRooms");
return { rooms }; return await this.chatService.getRooms(req.user, res);
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Post('join') @Post('join')
async joinRoom(@Body() joinRoomDto: joinRoomDto, @Req() req) async joinRoom(@Body() joinRoomDto: joinRoomDto, @Req() req, @Res() res)
{ {
const user: User = req.user; const user: User = req.user;
return await this.chatService.addUserToRoom(user, joinRoomDto, res);
let room = await this.chatService.addUserToRoom(user, joinRoomDto);
//return { message: 'Successfully joined room.' };
//return res.status(HttpStatus.BAD_REQUEST).json({message : 'You can\'t grant a ticket to another user'});
return { room };
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)

View File

@@ -1,5 +1,6 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable, Res } from '@nestjs/common';
import { User } from 'src/users/entities/user.entity'; import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
import { Chatroom } from './entities/chatroom.entity'; import { Chatroom } from './entities/chatroom.entity';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
@@ -9,6 +10,7 @@ import { joinRoomDto } from './dto/joinRoom.dto';
export class ChatService { export class ChatService {
constructor( constructor(
private usersService: UsersService,
@InjectRepository(User) @InjectRepository(User)
private readonly userRepository: Repository<User>, private readonly userRepository: Repository<User>,
@InjectRepository(Chatroom) @InjectRepository(Chatroom)
@@ -19,17 +21,22 @@ export class ChatService {
// return server.emit('message', message); // return server.emit('message', message);
//} //}
async getRooms() async getRooms(user: User, @Res() res)
{ {
/*
const room = await this.chatroomRepository
.createQueryBuilder('chatroom')
.where(':user_id IN chatroom.users', { user_id: user.fortyTwoId })
.getMany();
console.log(room);
*/
//return chatrooms;
} }
async getUserRooms() async addUserToRoom(user: User, joinRoomDto: joinRoomDto, @Res() res)
{ {
}
async addUserToRoom(user: User, joinRoomDto: joinRoomDto)
{
//const room = await this.chatroomRepository.findOneBy({ name : joinRoomDto.room_name });
const room = await this.chatroomRepository const room = await this.chatroomRepository
.createQueryBuilder('chatroom') .createQueryBuilder('chatroom')
.where('chatroom.name = :name', { name: joinRoomDto.room_name }) .where('chatroom.name = :name', { name: joinRoomDto.room_name })
@@ -38,15 +45,15 @@ export class ChatService {
if (room) if (room)
throw new HttpException(`This room already exist`, HttpStatus.CONFLICT); throw new HttpException(`This room already exist`, HttpStatus.CONFLICT);
// create chatroom
const newChatroom = new Chatroom(); const newChatroom = new Chatroom();
newChatroom.name = joinRoomDto.room_name; newChatroom.name = joinRoomDto.room_name;
newChatroom.type = joinRoomDto.room_type; newChatroom.type = joinRoomDto.room_type;
newChatroom.owner = user; newChatroom.owner = user.fortyTwoId;
newChatroom.users = [user]; newChatroom.users = [user.fortyTwoId];
const savedChatroom = await this.chatroomRepository.save(newChatroom); this.chatroomRepository.save(newChatroom);
console.log(savedChatroom);
return "good room"; return res.status(HttpStatus.OK).json({ room_name: joinRoomDto.room_name, message: "successfull room creation" });
} }
async removeUserFromRoom(user: User, room_name: string) async removeUserFromRoom(user: User, room_name: string)

View File

@@ -19,11 +19,17 @@ export class Chatroom {
@Column() @Column()
type: string; type: string;
@ManyToOne(type => User, user => user.ownedRooms) // @ManyToOne(type => User, user => user.ownedRooms)
owner: User; // owner: User;
//
// @ManyToMany(type => User)
// @JoinTable()
// users: User[];
@ManyToMany(type => User) @Column()
@JoinTable() owner: string; // fortytwo id
users: User[];
@Column({ type: "simple-array" })
users: string[]; // fortytwo id
} }

View File

@@ -54,10 +54,10 @@ export class User {
@OneToOne(() => UserStats, { cascade: true }) @OneToOne(() => UserStats, { cascade: true })
stats: UserStats; stats: UserStats;
@OneToMany(type => Chatroom, chatroom => chatroom.owner) // @OneToMany(type => Chatroom, chatroom => chatroom.owner)
ownedRooms: Chatroom[]; // ownedRooms: Chatroom[];
//
@ManyToMany(type => Chatroom) // @ManyToMany(type => Chatroom)
@JoinTable() // @JoinTable()
userRooms: Chatroom[]; // userRooms: Chatroom[];
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -14,6 +14,7 @@
// { // {
// //
// await init_socket(); // await init_socket();
// init_socket();
// pbm: sometimes socket is still undefined here // pbm: sometimes socket is still undefined here
socket.on('connect', function(){ socket.on('connect', function(){

View File

@@ -9,7 +9,7 @@
let room_type: string; let room_type: string;
let room_password: string; let room_password: string;
let response_data: string; let response_data: string;
let response_status: number = 200; let response_status: number = 0;
let response_message: string; let response_message: string;
async function handleSubmit(evt) async function handleSubmit(evt)
@@ -26,20 +26,23 @@
}; };
console.log("formData:", formData); console.log("formData:", formData);
//const response = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/chat/join`, { // send the new room
const response = await fetch('/api/v2/chat/join', { const response = await fetch('/api/v2/chat/join', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData), body: JSON.stringify(formData),
}); });
// get response status and message
response_status = response.status;
response_data = await response.json(); response_data = await response.json();
console.log(response_data);
if (response_data.statusCode)
response_status = response_data.statusCode;
else
response_status = 200;
if (response_data.message) if (response_data.message)
response_message = response_data.message; response_message = response_data.message;
console.log("response:", response_data, "status:", response_status, "message:", response_message);
// go to room
if (response_status === 200 && response_message === "successfull room creation")
layout = "room";
} }
</script> </script>
@@ -64,7 +67,7 @@
<!-- panel_create --> <!-- panel_create -->
<div class="panel panel_create __border_top"> <div class="panel panel_create __border_top">
<form on:submit|preventDefault={handleSubmit}> <form on:submit|preventDefault={handleSubmit}>
{#if response_status !== 200} {#if response_status >= 300}
<Warning content={response_message}/> <Warning content={response_message}/>
{/if} {/if}
<!-- name: --> <!-- name: -->

View File

@@ -1,9 +1,29 @@
<script> <script>
import { onMount } from 'svelte';
import Button from './Chat_button.svelte'; import Button from './Chat_button.svelte';
export let layout; export let layout;
let rooms = [
{room_name: 'my room'},
{room_name: 'better room'},
{room_name: 'best room'},
{room_name: 'ho room'},
];
// ask for the rooms
onMount(() => {
console.log("onmount");
const get_rooms = fetch('/api/v2/chat/rooms')
.then(resp => resp.json())
.then(data =>
{
console.log(data);
//rooms = data;
});
});
</script> </script>
<div class="grid_box"> <div class="grid_box">
@@ -30,10 +50,13 @@
<div class="__show_if_only_child"> <div class="__show_if_only_child">
<p class="__center">/ you have no chat room yet /</p> <p class="__center">/ you have no chat room yet /</p>
</div> </div>
<!-- placeholders {#each rooms as room}
<Button bind:layout new_layout="room" my_class="list"> <Button bind:layout new_layout="room" my_class="list">
a room {room.room_name}
</Button> </Button>
{/each}
<!-- placeholders
<Button bind:layout new_layout="room" my_class="list"> <Button bind:layout new_layout="room" my_class="list">
another room another room
</Button> </Button>

View File

@@ -29,7 +29,7 @@
text_area.focus(); text_area.focus();
} }
function send_msg_if(evt) function enter_send_msg(evt)
{ {
if (evt.shiftKey && evt.key === "Enter") if (evt.shiftKey && evt.key === "Enter")
{ {
@@ -72,7 +72,7 @@
class="text_area" class="text_area"
bind:innerHTML={msg} bind:innerHTML={msg}
bind:this={text_area} bind:this={text_area}
on:keypress={send_msg_if} on:keypress={enter_send_msg}
contenteditable="true" contenteditable="true"
></div> ></div>
</div> </div>

View File

@@ -3,6 +3,9 @@ import io from 'socket.io-client';
export let user; export let user;
export let socket; export let socket;
export let temp = "foo";
export function change_temp(){temp = "bar";};
const address = `http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}`; const address = `http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}`;
export function init_socket() export function init_socket()
@@ -19,7 +22,7 @@ export function init_socket()
{ {
username: user.username, username: user.username,
}, },
}); })
}); });
} }