Websocket :
- Connect with token : good - Connect with mail/pass : good but wait for front - Open private msg : good but it cant send message - fixed some bug on printDebug on class User on wsServer
This commit is contained in:
@ -1,68 +0,0 @@
|
|||||||
# async def sendData(websocket):
|
|
||||||
# while True:
|
|
||||||
# try:
|
|
||||||
# await websocket.send(json.dumps({"message": "Hello client"}))
|
|
||||||
# except websockets.exceptions.ConnectionClosed as e:
|
|
||||||
# connected_clients.remove(websocket)
|
|
||||||
# print("Client disconnected with error :", e)
|
|
||||||
# break
|
|
||||||
# await asyncio.sleep(1)
|
|
||||||
|
|
||||||
# async def receiveData(websocket):
|
|
||||||
# try :
|
|
||||||
# async for message in websocket:
|
|
||||||
# print(f"Message reçu : {message}")
|
|
||||||
# except websockets.exceptions.ConnectionClosed as e:
|
|
||||||
# print("Client disconnected with error :", e)
|
|
||||||
|
|
||||||
# def verifyToken(websocket):
|
|
||||||
# try:
|
|
||||||
# token = websocket.request_headers["Sec-WebSocket-Protocol"]
|
|
||||||
# print(f"Token reçu : {token}")
|
|
||||||
# if token == validTokens:
|
|
||||||
# return True
|
|
||||||
# else:
|
|
||||||
# return False
|
|
||||||
# except KeyError as e:
|
|
||||||
# print(f"Error: {e}")
|
|
||||||
# return False
|
|
||||||
|
|
||||||
# async def handler(websocket, path):
|
|
||||||
# print("client connected")
|
|
||||||
# connected_clients.add(websocket)
|
|
||||||
# websocket.request_headers["Sec-WebSocket-Protocol"] = "123456"
|
|
||||||
# await websocket.send("Connection established")
|
|
||||||
|
|
||||||
# # try:
|
|
||||||
# # if path != "/":
|
|
||||||
# # print("client disconnected")
|
|
||||||
# # await websocket.send(json.dumps({"error": "Invalid path", "code": 9010}))
|
|
||||||
# # await websocket.close()
|
|
||||||
# # return
|
|
||||||
# # if verifyToken(websocket) == False:
|
|
||||||
# # print("client disconnected")
|
|
||||||
# # await websocket.send(json.dumps({"error": "Invalid token", "code": 9000}))
|
|
||||||
# # await websocket.close()
|
|
||||||
# # return
|
|
||||||
|
|
||||||
# # send_task = asyncio.create_task(sendData(websocket))
|
|
||||||
# # receive_task = asyncio.create_task(receiveData(websocket))
|
|
||||||
# # await asyncio.gather(receive_task, send_task)
|
|
||||||
# # # except websockets.exceptions.ConnectionClosed as e:
|
|
||||||
# # # print("Client disconnected with error :", e)
|
|
||||||
# # # connected_clients.remove(websocket)
|
|
||||||
# # # return
|
|
||||||
# # # finally:
|
|
||||||
# # # connected_clients.remove(websocket)
|
|
||||||
# # # websocket.close()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# try:
|
|
||||||
# start_server = websockets.serve(handler, "localhost", 8000, reuse_address=True)
|
|
||||||
# except OSError as e:
|
|
||||||
# print(f"Error: {e}")
|
|
||||||
# exit(1)
|
|
||||||
# asyncio.get_event_loop().run_until_complete(start_server)
|
|
||||||
# print("Server started")
|
|
||||||
# asyncio.get_event_loop().run_forever()
|
|
@ -6,7 +6,7 @@
|
|||||||
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
||||||
# +#+#+#+#+#+ +#+ #
|
# +#+#+#+#+#+ +#+ #
|
||||||
# Created: 2024/08/03 15:54:14 by edbernar #+# #+# #
|
# Created: 2024/08/03 15:54:14 by edbernar #+# #+# #
|
||||||
# Updated: 2024/08/03 17:17:39 by edbernar ### ########.fr #
|
# Updated: 2024/08/03 23:30:42 by edbernar ### ########.fr #
|
||||||
# #
|
# #
|
||||||
# **************************************************************************** #
|
# **************************************************************************** #
|
||||||
|
|
||||||
@ -15,7 +15,7 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
|
|
||||||
|
|
||||||
class User(websockets.WebSocketServerProtocol):
|
class User():
|
||||||
debugMode = True
|
debugMode = True
|
||||||
websocket = None
|
websocket = None
|
||||||
username = ""
|
username = ""
|
||||||
@ -24,56 +24,92 @@ class User(websockets.WebSocketServerProtocol):
|
|||||||
|
|
||||||
def __init__(self, websocket):
|
def __init__(self, websocket):
|
||||||
if (self.debugMode):
|
if (self.debugMode):
|
||||||
print("\033[0;34m|------ New user Connected ------|\033[0;0m")
|
print("\033[42m|------ New user Connected ------|\033[1;0m")
|
||||||
self.websocket = websocket
|
self.websocket = websocket
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
if (self.debugMode):
|
if (self.debugMode):
|
||||||
print("\033[0;31m|------ User disconnected ------|\033[0;0m")
|
print("\033[43m|------ User disconnected -------|\033[1;0m")
|
||||||
|
print("User :", self.username)
|
||||||
|
print("Id :", self.id)
|
||||||
|
|
||||||
|
async def sendError(self, message, code, error=None):
|
||||||
|
try:
|
||||||
|
jsonVar = {"type": "error", "content": message, "code": code}
|
||||||
|
self.printDebug(jsonVar, 2, error)
|
||||||
|
await self.websocket.send(json.dumps(jsonVar))
|
||||||
|
except:
|
||||||
|
if (self.debugMode):
|
||||||
|
print("\033[0;31m|------ Error in sendError ------|\033[0;0m")
|
||||||
|
|
||||||
async def sendError(self, message, code):
|
|
||||||
jsonVar = {"type": "error", "content": message, "code": code}
|
|
||||||
self.printDebug( jsonVar, 2)
|
|
||||||
await self.websocket.send(json.dumps(jsonVar))
|
|
||||||
|
|
||||||
async def send(self, content):
|
async def send(self, content):
|
||||||
self.printDebug(content, 1)
|
try:
|
||||||
if (type(content) == dict):
|
if (type(content) == dict):
|
||||||
await self.websocket.send(json.dumps(content))
|
self.printDebug(content, 1)
|
||||||
else:
|
await self.websocket.send(json.dumps(content))
|
||||||
await self.websocket.send(content)
|
else:
|
||||||
|
self.printDebug(json.loads(content), 1)
|
||||||
|
await self.websocket.send(content)
|
||||||
|
except Exception as e:
|
||||||
|
if (self.debugMode):
|
||||||
|
print("\033[0;31m|--------- Error in send --------|\033[0;0m")
|
||||||
|
print("Error message :", e)
|
||||||
|
|
||||||
async def verifyToken(self, token):
|
async def verifyToken(self, token):
|
||||||
if (self.token != token or self.token == ""):
|
|
||||||
await self.sendError("Invalid token", 9001)
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
def printDebug(self, infoUser, request, typeRequest):
|
|
||||||
try:
|
try:
|
||||||
|
if (self.token != token or self.token == ""):
|
||||||
|
await self.sendError("Invalid token", 9001)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
except:
|
||||||
|
if (self.debugMode):
|
||||||
|
print("\033[0;31m|----- Error in verifyToken -----|\033[0;0m")
|
||||||
|
|
||||||
|
def printDebug(self, request, typeRequest, error=None):
|
||||||
|
try:
|
||||||
if (self.debugMode and typeRequest == 0):
|
if (self.debugMode and typeRequest == 0):
|
||||||
print("\033[0;34m|----- New received request -----|\033[0;0m")
|
print("\033[0;34m|----- New received request -----|\033[0;0m")
|
||||||
print("User :", infoUser.username)
|
print("User :", self.username)
|
||||||
print("Token :", infoUser.token)
|
print("Token :", self.token)
|
||||||
print("Id :", infoUser.id)
|
print("Id :", self.id)
|
||||||
print("Var type :", type(request["type"]))
|
try:
|
||||||
print("Type :", request["type"])
|
print("Var type :", type(request["type"]))
|
||||||
print("Content :", request["content"])
|
print("Type :", request["type"])
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
print("Content type :", type(request["content"]))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
elif (self.debugMode and typeRequest == 1):
|
elif (self.debugMode and typeRequest == 1):
|
||||||
print("\033[0;32m|------- New sent request -------|\033[0;0m")
|
print("\033[0;32m|------- New sent request -------|\033[0;0m")
|
||||||
print("To :", infoUser.username)
|
print("To :", self.username)
|
||||||
print("Var type :", type(request["type"]))
|
print("Id :", self.id)
|
||||||
print("Type :", request["type"])
|
try:
|
||||||
print("Content :", request["content"])
|
print("Var type :", type(request["type"]))
|
||||||
|
print("Type :", request["type"])
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
print("Content :", request["content"])
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
if ("type" not in request or "content" not in request):
|
||||||
|
print("Warning : not usual json format")
|
||||||
elif (self.debugMode and typeRequest == 2):
|
elif (self.debugMode and typeRequest == 2):
|
||||||
print("\033[0;31m|------------- Error ------------|\033[0;0m")
|
print("\033[0;31m|------------- Error ------------|\033[0;0m")
|
||||||
print("User :", infoUser.username)
|
print("User :", self.username)
|
||||||
print("Token :", infoUser.token)
|
print("Token :", self.token)
|
||||||
print("Id :", infoUser.id)
|
print("Id :", self.id)
|
||||||
print("Error message :", request["content"])
|
print("Error message :", request["content"])
|
||||||
print("Error code :", request["code"])
|
print("Error code :", request["code"])
|
||||||
|
if (error != None):
|
||||||
|
print("Error python :", error)
|
||||||
|
print("File :", error.__traceback__.tb_frame.f_globals["__file__"])
|
||||||
|
print("Line :", error.__traceback__.tb_lineno)
|
||||||
except:
|
except:
|
||||||
print("\033[0;31m|------- Error in printDebug -----|\033[0;0m")
|
print("\033[0;31m|------ Error in printDebug -----|\033[0;0m")
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
try:
|
try:
|
||||||
|
Binary file not shown.
@ -6,10 +6,11 @@
|
|||||||
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
||||||
# +#+#+#+#+#+ +#+ #
|
# +#+#+#+#+#+ +#+ #
|
||||||
# Created: 2024/08/03 08:10:40 by edbernar #+# #+# #
|
# Created: 2024/08/03 08:10:40 by edbernar #+# #+# #
|
||||||
# Updated: 2024/08/03 17:20:07 by edbernar ### ########.fr #
|
# Updated: 2024/08/03 23:13:58 by edbernar ### ########.fr #
|
||||||
# #
|
# #
|
||||||
# **************************************************************************** #
|
# **************************************************************************** #
|
||||||
|
|
||||||
|
from typeRequets.getPrivateListMessage import getPrivateListMessage
|
||||||
from typeRequets.getPrivateListUser import getPrivateListUser
|
from typeRequets.getPrivateListUser import getPrivateListUser
|
||||||
from typeRequets.login import login
|
from typeRequets.login import login
|
||||||
from Class.User import User
|
from Class.User import User
|
||||||
@ -17,10 +18,15 @@ import websockets
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
|
||||||
connected_clients = set()
|
# Todo :
|
||||||
|
# - verifier que l'utilisateur n'est pas déjà connecté
|
||||||
|
# - envoyer des messages avec des caractères spéciaux type ", ', {, }, [, ]
|
||||||
|
|
||||||
typeRequest = ["login", "get_private_list_user"]
|
|
||||||
functionRequest = [login, getPrivateListUser]
|
connected_clients = []
|
||||||
|
|
||||||
|
typeRequest = ["login", "get_private_list_user", "get_private_list_message"]
|
||||||
|
functionRequest = [login, getPrivateListUser, getPrivateListMessage]
|
||||||
|
|
||||||
async def handler(websocket, path):
|
async def handler(websocket, path):
|
||||||
if (path != "/"):
|
if (path != "/"):
|
||||||
@ -28,7 +34,7 @@ async def handler(websocket, path):
|
|||||||
await websocket.close()
|
await websocket.close()
|
||||||
return
|
return
|
||||||
userClass = User(websocket)
|
userClass = User(websocket)
|
||||||
connected_clients.add(userClass)
|
connected_clients.append(userClass)
|
||||||
try:
|
try:
|
||||||
async for resquet in userClass.websocket:
|
async for resquet in userClass.websocket:
|
||||||
try:
|
try:
|
||||||
@ -37,17 +43,18 @@ async def handler(websocket, path):
|
|||||||
await userClass.sendError("Invalid JSON", 9002)
|
await userClass.sendError("Invalid JSON", 9002)
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
|
userClass.printDebug(jsonRequest, 0)
|
||||||
if (jsonRequest["type"] in typeRequest):
|
if (jsonRequest["type"] in typeRequest):
|
||||||
if jsonRequest["type"] == "login":
|
if jsonRequest["type"] == "login":
|
||||||
await functionRequest[typeRequest.index(jsonRequest["type"])](websocket, jsonRequest["content"])
|
await functionRequest[typeRequest.index(jsonRequest["type"])](userClass, jsonRequest["content"])
|
||||||
else:
|
else:
|
||||||
if (userClass.verifyToken(websocket, jsonRequest["token"]) == False):
|
if (await userClass.verifyToken(jsonRequest["token"]) == False):
|
||||||
continue
|
continue
|
||||||
await functionRequest[typeRequest.index(jsonRequest["type"])](websocket)
|
await functionRequest[typeRequest.index(jsonRequest["type"])](userClass, jsonRequest["content"])
|
||||||
else:
|
else:
|
||||||
await userClass.sendError("Invalid type", 9004)
|
await userClass.sendError("Invalid type", 9004)
|
||||||
except:
|
except Exception as e:
|
||||||
await userClass.sendError("Invalid request", 9005)
|
await userClass.sendError("Invalid request", 9005, e)
|
||||||
except websockets.ConnectionClosed:
|
except websockets.ConnectionClosed:
|
||||||
pass
|
pass
|
||||||
await userClass.close()
|
await userClass.close()
|
||||||
|
Binary file not shown.
Binary file not shown.
@ -0,0 +1,69 @@
|
|||||||
|
# **************************************************************************** #
|
||||||
|
# #
|
||||||
|
# ::: :::::::: #
|
||||||
|
# getPrivateListMessage.py :+: :+: :+: #
|
||||||
|
# +:+ +:+ +:+ #
|
||||||
|
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
||||||
|
# +#+#+#+#+#+ +#+ #
|
||||||
|
# Created: 2024/08/03 22:53:14 by edbernar #+# #+# #
|
||||||
|
# Updated: 2024/08/03 23:43:09 by edbernar ### ########.fr #
|
||||||
|
# #
|
||||||
|
# **************************************************************************** #
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
listMessage = {
|
||||||
|
"type": "private_list_message",
|
||||||
|
"content": [
|
||||||
|
{
|
||||||
|
"from": 0,
|
||||||
|
"content": "",
|
||||||
|
"date": "10:05 31/07/2024"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 0,
|
||||||
|
"content": "",
|
||||||
|
"date": "10:05 31/07/2024"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 0,
|
||||||
|
"content": "",
|
||||||
|
"date": "10:06 31/07/2024"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 0,
|
||||||
|
"content": "",
|
||||||
|
"date": "10:06 31/07/2024"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 0,
|
||||||
|
"content": "",
|
||||||
|
"date": "10:45 31/07/2024"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": 0,
|
||||||
|
"content": "",
|
||||||
|
"date": "10:46 31/07/2024"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
def generate_random_string():
|
||||||
|
char = "abcdefghijklmnopqrstuvwxyz 123456789"
|
||||||
|
string = ""
|
||||||
|
|
||||||
|
for i in range(20):
|
||||||
|
string += char[random.randint(0, len(char) - 1)]
|
||||||
|
return string
|
||||||
|
|
||||||
|
async def getPrivateListMessage(userClass, content):
|
||||||
|
# |TOM| Requete pour avoir la liste des messages privés grace à l'id de l'utilisateur
|
||||||
|
copyListMessage = listMessage.copy()
|
||||||
|
for message in copyListMessage["content"]:
|
||||||
|
if (random.randint(1, 10) % 2 == 0):
|
||||||
|
message["from"] = 4561268
|
||||||
|
else:
|
||||||
|
message["from"] = content["id"]
|
||||||
|
message["content"] = generate_random_string()
|
||||||
|
await userClass.send(copyListMessage)
|
||||||
|
|
@ -6,7 +6,7 @@
|
|||||||
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
||||||
# +#+#+#+#+#+ +#+ #
|
# +#+#+#+#+#+ +#+ #
|
||||||
# Created: 2024/08/03 15:10:23 by edbernar #+# #+# #
|
# Created: 2024/08/03 15:10:23 by edbernar #+# #+# #
|
||||||
# Updated: 2024/08/03 17:07:21 by edbernar ### ########.fr #
|
# Updated: 2024/08/03 22:30:13 by edbernar ### ########.fr #
|
||||||
# #
|
# #
|
||||||
# **************************************************************************** #
|
# **************************************************************************** #
|
||||||
|
|
||||||
@ -18,37 +18,43 @@ data = [
|
|||||||
{
|
{
|
||||||
"name": "Nessundorma",
|
"name": "Nessundorma",
|
||||||
"status": "online",
|
"status": "online",
|
||||||
"pfp": "https://wallpapers-clan.com/wp-content/uploads/2023/05/cool-pfp-02.jpg"
|
"pfp": "https://wallpapers-clan.com/wp-content/uploads/2023/05/cool-pfp-02.jpg",
|
||||||
|
"id": 145564
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Succotash",
|
"name": "Succotash",
|
||||||
"status": "offline",
|
"status": "offline",
|
||||||
"pfp": "https://i.pinimg.com/200x/28/75/96/287596f98304bf1adc2c411619ae8fef.jpg"
|
"pfp": "https://i.pinimg.com/200x/28/75/96/287596f98304bf1adc2c411619ae8fef.jpg",
|
||||||
|
"id": 256981
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Astropower",
|
"name": "Astropower",
|
||||||
"status": "online",
|
"status": "online",
|
||||||
"pfp": "https://ashisheditz.com/wp-content/uploads/2024/03/cool-anime-pfp-demon-slayer-HD.jpg"
|
"pfp": "https://ashisheditz.com/wp-content/uploads/2024/03/cool-anime-pfp-demon-slayer-HD.jpg",
|
||||||
|
"id": 301547
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Assaultive",
|
"name": "Assaultive",
|
||||||
"status": "offline",
|
"status": "offline",
|
||||||
"pfp": "https://i1.sndcdn.com/artworks-1Li0JIJrQGlojD3y-AEiNkw-t500x500.jpg"
|
"pfp": "https://i1.sndcdn.com/artworks-1Li0JIJrQGlojD3y-AEiNkw-t500x500.jpg",
|
||||||
|
"id": 432448
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Redshock",
|
"name": "Redshock",
|
||||||
"status": "offline",
|
"status": "offline",
|
||||||
"pfp": "https://cdn.pfps.gg/pfps/7094-boy-pfp.png"
|
"pfp": "https://cdn.pfps.gg/pfps/7094-boy-pfp.png",
|
||||||
|
"id": 543211
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Parley",
|
"name": "Parley",
|
||||||
"status": "offline",
|
"status": "offline",
|
||||||
"pfp": "https://pbs.twimg.com/media/EscE6ckU0AA-Uhe.png"
|
"pfp": "https://pbs.twimg.com/media/EscE6ckU0AA-Uhe.png",
|
||||||
|
"id": 654123
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
async def getPrivateListUser(userClass):
|
async def getPrivateListUser(userClass, content=None):
|
||||||
# |TOM| Faire une requête à la base de données pour récupérer la liste des
|
# |TOM| Faire une requête à la base de données pour récupérer la liste des
|
||||||
# utilisateurs qui doivent apparaitre dans la liste du chat privé
|
# utilisateurs qui doivent apparaitre dans la liste du chat privé
|
||||||
# (ceux qui ont eu conversation avec l'utilisateur)
|
# (ceux qui ont eu conversation avec l'utilisateur)
|
||||||
await userClass.send({"type": "get_private_list_user", "content": data})
|
await userClass.send({"type": "private_list_user", "content": data})
|
@ -6,7 +6,7 @@
|
|||||||
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
||||||
# +#+#+#+#+#+ +#+ #
|
# +#+#+#+#+#+ +#+ #
|
||||||
# Created: 2024/08/03 08:10:38 by edbernar #+# #+# #
|
# Created: 2024/08/03 08:10:38 by edbernar #+# #+# #
|
||||||
# Updated: 2024/08/03 17:08:07 by edbernar ### ########.fr #
|
# Updated: 2024/08/03 22:35:45 by edbernar ### ########.fr #
|
||||||
# #
|
# #
|
||||||
# **************************************************************************** #
|
# **************************************************************************** #
|
||||||
|
|
||||||
@ -21,11 +21,11 @@ import json
|
|||||||
|
|
||||||
userList = [
|
userList = [
|
||||||
{
|
{
|
||||||
"username": "user1",
|
"username": "Nexalith",
|
||||||
"token": "123456",
|
"token": "IDSNCSDAd465sd13215421",
|
||||||
"mail": "aa@aa.fr",
|
"mail": "eddy@ediwor.fr",
|
||||||
"password": "ABC123",
|
"password": "ABC123",
|
||||||
"id": 1
|
"id": 4561268
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"username": "user2",
|
"username": "user2",
|
||||||
@ -43,26 +43,31 @@ userList = [
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
async def loginByToken(websocket, content):
|
async def loginByToken(userClass, content):
|
||||||
# |TOM| Requete pour savoir si le token est valide
|
# |TOM| Requete pour savoir si le token est valide
|
||||||
for user in userList:
|
for user in userList:
|
||||||
if (user["token"] == content["token"]):
|
if (user["token"] == content["token"]):
|
||||||
jsonVar = {"type": "login", "content": {"username": user["username"], "token": user["token"], "id": user["id"]}}
|
jsonVar = {"type": "login", "content": {"username": user["username"], "token": user["token"], "id": user["id"]}}
|
||||||
await websocket.send(json.dumps(jsonVar))
|
userClass.username = jsonVar["content"]["username"]
|
||||||
|
userClass.token = jsonVar["content"]["token"]
|
||||||
|
userClass.id = jsonVar["content"]["id"]
|
||||||
|
await userClass.send(jsonVar)
|
||||||
return
|
return
|
||||||
jsonVar = {"type": "error", "content": "Invalid token", "code": 9001}
|
jsonVar = {"type": "error", "content": "Invalid token", "code": 9001}
|
||||||
await websocket.send(json.dumps(jsonVar))
|
await userClass.send(json.dumps(jsonVar))
|
||||||
|
|
||||||
async def loginByPass(websocket, content):
|
async def loginByPass(userClass, content):
|
||||||
# |TOM| Requete pour savoir si le mail et le mot de passe sont valides
|
# |TOM| Requete pour savoir si le mail et le mot de passe sont valides
|
||||||
# et créer un token s'il n'existe pas
|
# et créer un token si celui-ci n'existe pas
|
||||||
for user in userList:
|
for user in userList:
|
||||||
if (user["username"] == content["username"] and user["password"] == content["password"]):
|
if (user["mail"] == content["mail"] and user["password"] == content["password"]):
|
||||||
jsonVar = {"type": "login", "content": {"username": user["username"], "token": user["token"], "id": user["id"]}}
|
jsonVar = {"type": "login", "content": {"username": user["username"], "token": user["token"], "id": user["id"]}}
|
||||||
await websocket.send(json.dumps(jsonVar))
|
userClass.username = jsonVar["content"]["username"]
|
||||||
|
userClass.token = jsonVar["content"]["token"]
|
||||||
|
userClass.id = jsonVar["content"]["id"]
|
||||||
|
await userClass.send(jsonVar)
|
||||||
return
|
return
|
||||||
jsonVar = {"type": "error", "content": "Invalid username or password", "code": 9007}
|
await userClass.send({"type": "error", "content": "Invalid username or password", "code": 9007})
|
||||||
await websocket.send(json.dumps(jsonVar))
|
|
||||||
|
|
||||||
async def verifyToken42(token42):
|
async def verifyToken42(token42):
|
||||||
url = "https://api.intra.42.fr/v2/me"
|
url = "https://api.intra.42.fr/v2/me"
|
||||||
@ -74,30 +79,30 @@ async def verifyToken42(token42):
|
|||||||
# dans la base de données
|
# dans la base de données
|
||||||
return (response.status_code == 200)
|
return (response.status_code == 200)
|
||||||
|
|
||||||
async def loginBy42(websocket, content):
|
async def loginBy42(userClass, content):
|
||||||
# |TOM| Requete pour récuperer les informations de l'utilisateur selon l'intra de la personne
|
# |TOM| Requete pour récuperer les informations de l'utilisateur selon l'intra de la personne
|
||||||
# et créer un token s'il n'existe pas
|
# et créer un token si celui-ci n'existe pas
|
||||||
for user in userList:
|
for user in userList:
|
||||||
if (await verifyToken42(content["token42"])):
|
if (await verifyToken42(content["token42"])):
|
||||||
jsonVar = {"type": "login", "content": {"username": user["username"], "token": user["token"], "id": user["id"]}}
|
jsonVar = {"type": "login", "content": {"username": user["username"], "token": user["token"], "id": user["id"]}}
|
||||||
await websocket.send(json.dumps(jsonVar))
|
await userClass.send(json.dumps(jsonVar))
|
||||||
|
return
|
||||||
jsonVar = {"type": "error", "content": "Invalid 42 token", "code": 9008}
|
jsonVar = {"type": "error", "content": "Invalid 42 token", "code": 9008}
|
||||||
await websocket.send(json.dumps(jsonVar))
|
await userClass.send(json.dumps(jsonVar))
|
||||||
|
|
||||||
async def login(websocket, content):
|
async def login(userClass, content):
|
||||||
# |TOM| Faire 3 types de requêtes:
|
# |TOM| Faire 3 types de requêtes:
|
||||||
# - byToken: Récupérer les informations de l'utilisateur en fonction de son token
|
# - byToken: Récupérer les informations de l'utilisateur en fonction de son token
|
||||||
# - byPass: Récupérer les informations de l'utilisateur en fonction de mail et de son mot de passe
|
# - byPass: Récupérer les informations de l'utilisateur en fonction de mail et de son mot de passe
|
||||||
# - by42: Récupérer les informations de l'utilisateur en fonction de son token42 (qui sera different du token)
|
# - by42: Récupérer les informations de l'utilisateur en fonction de son token42 (qui sera different du token)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if (content["type"] == "byToken"):
|
if (content["type"] == "byToken"):
|
||||||
await loginByToken(websocket, content)
|
await loginByToken(userClass, content)
|
||||||
elif (content["type"] == "byPass"):
|
elif (content["type"] == "byPass"):
|
||||||
await loginByPass(websocket, content)
|
await loginByPass(userClass, content)
|
||||||
elif (content["type"] == "by42"):
|
elif (content["type"] == "by42"):
|
||||||
await loginBy42(websocket, content)
|
await loginBy42(userClass, content)
|
||||||
else:
|
else:
|
||||||
await sendError(websocket, "Invalid login type", 9006)
|
await userClass.sendError("Invalid login type", 9006)
|
||||||
except:
|
except Exception as e:
|
||||||
await sendError(websocket, "Invalid request", 9005)
|
await userClass.sendError("Invalid request", 9005, e)
|
@ -6,12 +6,14 @@
|
|||||||
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
|
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
|
||||||
/* +#+#+#+#+#+ +#+ */
|
/* +#+#+#+#+#+ +#+ */
|
||||||
/* Created: 2024/07/30 13:50:35 by edbernar #+# #+# */
|
/* Created: 2024/07/30 13:50:35 by edbernar #+# #+# */
|
||||||
/* Updated: 2024/08/03 14:57:19 by edbernar ### ########.fr */
|
/* Updated: 2024/08/03 23:44:10 by edbernar ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
import { socket, sendRequest } from "./websocket.js";
|
import { sendRequest } from "./websocket.js";
|
||||||
import { userList, waitForUserList } from "./typeResponse/typePrivateListUser.js";
|
import { userList, waitForUserList } from "./typeResponse/typePrivateListUser.js";
|
||||||
|
import { messageList, waitForMessageList } from "./typeResponse/typePrivateListMessage.js";
|
||||||
|
import { userMeInfo } from "./typeResponse/typeLogin.js";
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
liveChat();
|
liveChat();
|
||||||
@ -72,17 +74,17 @@ async function showListUserMessage() {
|
|||||||
divMessageListChatHome.innerHTML += "<p style='text-align: center; margin-top: 20px;'>New conversation +</p>";
|
divMessageListChatHome.innerHTML += "<p style='text-align: center; margin-top: 20px;'>New conversation +</p>";
|
||||||
divUser = document.getElementsByClassName("user");
|
divUser = document.getElementsByClassName("user");
|
||||||
for (let i = 0; i < divUser.length; i++) {
|
for (let i = 0; i < divUser.length; i++) {
|
||||||
divUser[i].addEventListener("click", () => {
|
divUser[i].addEventListener("click", async () => {
|
||||||
launchPrivateChat(userList[i]);
|
await launchPrivateChat(userList[i]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showActualGameMessage() {
|
function showActualGameMessage(id) {
|
||||||
const divMessageListChatHome = document.getElementById("messageListChatHome");
|
const divMessageListChatHome = document.getElementById("messageListChatHome");
|
||||||
let me = "Kumita";
|
let me = "Kumita";
|
||||||
let request = {
|
let request = {
|
||||||
isInGame: true,
|
isInGame: false,
|
||||||
opponent: {
|
opponent: {
|
||||||
name: "Astropower",
|
name: "Astropower",
|
||||||
pfp: "https://ashisheditz.com/wp-content/uploads/2024/03/cool-anime-pfp-demon-slayer-HD.jpg"
|
pfp: "https://ashisheditz.com/wp-content/uploads/2024/03/cool-anime-pfp-demon-slayer-HD.jpg"
|
||||||
@ -147,50 +149,13 @@ function showActualGameMessage() {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function launchPrivateChat(user) {
|
async function launchPrivateChat(user) {
|
||||||
const divMessageListChatHome = document.getElementById("messageListChatHome");
|
const divMessageListChatHome = document.getElementById("messageListChatHome");
|
||||||
const divButtonTypeChatHome = document.getElementById("buttonTypeChatHome");
|
const divButtonTypeChatHome = document.getElementById("buttonTypeChatHome");
|
||||||
let returnButton;
|
let returnButton;
|
||||||
let me = "Kumita";
|
|
||||||
let request = {
|
sendRequest("get_private_list_message", {id: user.id});
|
||||||
opponent: {
|
await waitForMessageList();
|
||||||
name: user.name,
|
|
||||||
pfp: user.pfp
|
|
||||||
},
|
|
||||||
listMessage: [
|
|
||||||
{
|
|
||||||
from: user.name,
|
|
||||||
content: "Salut !",
|
|
||||||
date: "10:05 31/07/2024"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
from: "Kumita",
|
|
||||||
content: "Hey",
|
|
||||||
date: "10:05 31/07/2024"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
from: user.name,
|
|
||||||
content: "Tu veux coder un peu ?",
|
|
||||||
date: "10:06 31/07/2024"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
from: "Kumita",
|
|
||||||
content: "Ouais, je suis partant !",
|
|
||||||
date: "10:06 31/07/2024"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
from: "Kumita",
|
|
||||||
content: "Ce bug était vraiment galère à résoudre, mais on y est arrivé.",
|
|
||||||
date: "10:45 31/07/2024"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
from: user.name,
|
|
||||||
content: "Ouais, mais t'as trouvé la solution. À la prochaine !",
|
|
||||||
date: "10:46 31/07/2024"
|
|
||||||
},
|
|
||||||
]
|
|
||||||
}; //Remplace temporairement la requete qui devra être de la meme forme
|
|
||||||
|
|
||||||
let h2Button = divButtonTypeChatHome.getElementsByTagName("h2");
|
let h2Button = divButtonTypeChatHome.getElementsByTagName("h2");
|
||||||
let len = h2Button.length;
|
let len = h2Button.length;
|
||||||
for (let i = 0; i < len; i++) {
|
for (let i = 0; i < len; i++) {
|
||||||
@ -208,17 +173,16 @@ function launchPrivateChat(user) {
|
|||||||
<h2 id="selected">Private</h2>
|
<h2 id="selected">Private</h2>
|
||||||
<h2>Game</h2>
|
<h2>Game</h2>
|
||||||
`;
|
`;
|
||||||
liveChat();
|
showListUserMessage();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
divMessageListChatHome.style.height = "230px";
|
divMessageListChatHome.style.height = "230px";
|
||||||
divMessageListChatHome.style.paddingBottom = "20px";
|
divMessageListChatHome.style.paddingBottom = "20px";
|
||||||
divMessageListChatHome.innerHTML = '';
|
divMessageListChatHome.innerHTML = '';
|
||||||
request.listMessage.forEach(element => {
|
messageList.forEach(element => {
|
||||||
divMessageListChatHome.innerHTML += `
|
divMessageListChatHome.innerHTML += `
|
||||||
<div class="${element.from === me ? "meMessage" : "opponentMessage"}">
|
<div class="${element.from === userMeInfo.id ? "meMessage" : "opponentMessage"}">
|
||||||
<p class="content">${element.content}</p>
|
<p class="content">${element.content}</p>
|
||||||
<p class="time">${element.date}</p>
|
<p class="time">${element.date}</p>
|
||||||
</div>
|
</div>
|
||||||
|
@ -6,13 +6,20 @@
|
|||||||
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
|
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
|
||||||
/* +#+#+#+#+#+ +#+ */
|
/* +#+#+#+#+#+ +#+ */
|
||||||
/* Created: 2024/08/02 00:39:53 by edbernar #+# #+# */
|
/* Created: 2024/08/02 00:39:53 by edbernar #+# #+# */
|
||||||
/* Updated: 2024/08/02 00:46:21 by edbernar ### ########.fr */
|
/* Updated: 2024/08/03 23:37:33 by edbernar ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
|
let userMeInfo = {
|
||||||
|
username: "",
|
||||||
|
id: 42
|
||||||
|
};
|
||||||
|
|
||||||
function typeLogin(content)
|
function typeLogin(content)
|
||||||
{
|
{
|
||||||
console.log("Welcome " + content.username + "\nYou're id is " + content.id);
|
console.log("Welcome " + content.username + "\nYou're id is " + content.id);
|
||||||
|
userMeInfo.username = content.username;
|
||||||
|
userMeInfo.id = content.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { typeLogin };
|
export { userMeInfo, typeLogin };
|
@ -0,0 +1,36 @@
|
|||||||
|
/* ************************************************************************** */
|
||||||
|
/* */
|
||||||
|
/* ::: :::::::: */
|
||||||
|
/* typePrivateListMessage.js :+: :+: :+: */
|
||||||
|
/* +:+ +:+ +:+ */
|
||||||
|
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
|
||||||
|
/* +#+#+#+#+#+ +#+ */
|
||||||
|
/* Created: 2024/08/03 22:20:35 by edbernar #+# #+# */
|
||||||
|
/* Updated: 2024/08/03 23:23:42 by edbernar ### ########.fr */
|
||||||
|
/* */
|
||||||
|
/* ************************************************************************** */
|
||||||
|
|
||||||
|
let messageList = [];
|
||||||
|
let messageListAvailable = false;
|
||||||
|
let messageListResolve = null;
|
||||||
|
|
||||||
|
function waitForMessageList() {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
if (messageListAvailable)
|
||||||
|
resolve();
|
||||||
|
else
|
||||||
|
messageListResolve = resolve;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function typePrivateListMessage(list) {
|
||||||
|
messageList = list;
|
||||||
|
messageListAvailable = true;
|
||||||
|
if (messageListResolve)
|
||||||
|
{
|
||||||
|
messageListResolve();
|
||||||
|
messageListResolve = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { messageList, typePrivateListMessage, waitForMessageList };
|
@ -6,23 +6,27 @@
|
|||||||
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
|
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
|
||||||
/* +#+#+#+#+#+ +#+ */
|
/* +#+#+#+#+#+ +#+ */
|
||||||
/* Created: 2024/07/31 22:17:24 by edbernar #+# #+# */
|
/* Created: 2024/07/31 22:17:24 by edbernar #+# #+# */
|
||||||
/* Updated: 2024/08/03 15:04:37 by edbernar ### ########.fr */
|
/* Updated: 2024/08/03 23:23:45 by edbernar ### ########.fr */
|
||||||
/* */
|
/* */
|
||||||
/* ************************************************************************** */
|
/* ************************************************************************** */
|
||||||
|
|
||||||
import { typeLogin } from "./typeResponse/typeLogin.js";
|
import { typeLogin } from "./typeResponse/typeLogin.js";
|
||||||
import { typePrivateListUser } from "./typeResponse/typePrivateListUser.js";
|
import { typePrivateListUser } from "./typeResponse/typePrivateListUser.js";
|
||||||
|
import { typePrivateListMessage } from "./typeResponse/typePrivateListMessage.js";
|
||||||
|
|
||||||
const socket = new WebSocket('ws://localhost:8000/');
|
const socket = new WebSocket('ws://localhost:8000/');
|
||||||
const token = "123456";
|
const token = "IDSNCSDAd465sd13215421";
|
||||||
|
|
||||||
const typeResponse = ["login", "private_list_user"];
|
const typeResponse = ["login", "private_list_user", "private_list_message"];
|
||||||
const functionResponse = [typeLogin, typePrivateListUser];
|
const functionResponse = [typeLogin, typePrivateListUser, typePrivateListMessage];
|
||||||
|
|
||||||
socket.onopen = () => {
|
socket.onopen = () => {
|
||||||
console.log('Connected');
|
console.log('Connected');
|
||||||
if (token)
|
if (token)
|
||||||
sendRequest("login", {"type": "byToken", "token": token});
|
sendRequest("login", {"type": "byToken", "token": token});
|
||||||
|
// |Eddy| Requete pour se connecter par mail et password. En attente du front pour le faire (déjà fonctionnel côté back)
|
||||||
|
// sendRequest("login", {type: "byPass", mail: "aa@aa.fr", password: "ABC123"});
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
socket.onmessage = (event) => {
|
socket.onmessage = (event) => {
|
||||||
|
Reference in New Issue
Block a user