From eda3a9cd3bfb3d95e2690356e99b5606bd47a7a7 Mon Sep 17 00:00:00 2001 From: Xarkam Date: Fri, 27 Mar 2026 12:08:22 +0100 Subject: [PATCH] =?UTF-8?q?Centralisation=20des=20constantes=20modifiable?= =?UTF-8?q?=20vers=20le=20m=C3=AAme=20fichier.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/PyQt6_LaTaniere.iml | 2 +- .idea/misc.xml | 2 +- src/config/constants.py | 32 ++++++++++++++++++----------- src/discord/discord_oauth.py | 21 ++++++++----------- src/discord/discord_tools.py | 5 ++--- src/fivemserver/fivemlauncher.py | 6 ++++-- src/fivemserver/get_server_token.py | 18 ++++++++-------- src/fivemserver/queuemanager.py | 8 ++++---- src/fivemserver/whitelistmanager.py | 8 +++----- 9 files changed, 53 insertions(+), 49 deletions(-) diff --git a/.idea/PyQt6_LaTaniere.iml b/.idea/PyQt6_LaTaniere.iml index 88a8457..3c24ad6 100644 --- a/.idea/PyQt6_LaTaniere.iml +++ b/.idea/PyQt6_LaTaniere.iml @@ -5,7 +5,7 @@ - + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index eb498d8..82828b5 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -3,5 +3,5 @@ - + \ No newline at end of file diff --git a/src/config/constants.py b/src/config/constants.py index 0fddd5d..53c46f0 100644 --- a/src/config/constants.py +++ b/src/config/constants.py @@ -6,10 +6,6 @@ from PySide6.QtGui import QColor # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- -FIVEMURL = "fivem://connect/prod.la-taniere.fun" -REDIRECT_URI = "http://localhost:5000/callback" -SCOPES = ["identify"] -CLIENT_ID = "1240007913175781508" AUTENTICATION_SUCCESS_MESSAGE = """ @@ -30,16 +26,28 @@ class Resources(Enum): FONT = ':/assets/Avocado-Cake-Demo.otf' class Urls(Enum): - DISCORD = 'https://discord.gg/A7eanmSkp2' - INTRANET = 'https://la-taniere.fun/connexion/' - API_URL = 'https://prod.la-taniere.fun:30121/' + DISCORD = 'https://discord.gg/A7eanmSkp2' # <- La Tanière invitation Discord + INTRANET = 'https://la-taniere.fun/connexion/' # <- La Tanière site web + API_URL = 'https://prod.la-taniere.fun:30121' # <- La Tanière Api url + FIVEMURL = 'fivem://connect/prod.la-taniere.fun' # <- La Tanière FiveM addresse + LOCAL_CALLBACK_PORT = 5000 + LOCAL_CALLBACK_HOST = 'localhost' + LOCAL_CALLBACK_URL = f'http://{LOCAL_CALLBACK_HOST}:{LOCAL_CALLBACK_PORT}/callback' # <- Url de Callback OAuth DiscordA class ApiEndPoints(Enum): - QUEUE_STATUS = '/queue/status/' - QUEUE_LEAVE = '/queue/leave' - QUEUE_JOIN = '/queue/join' - QUEUE_REFRESH = '/queue/refresh' - REGISTER_USER = '/api_v2/connection/register' + API_VERSION = 'api_v2' + QUEUE_STATUS = 'queue/status/' + QUEUE_LEAVE = 'queue/leave' + QUEUE_JOIN = 'queue/join' + QUEUE_REFRESH = 'queue/refresh' + WHITELIST_URL_ENDPOINT = "iswhitelist" + REGISTER_USER = f'{API_VERSION}/connection/register' + TOKEN_AUTH = f'{API_VERSION}/tkn_auth' + AUTHENTICATION = f'{API_VERSION}/auth' + +class DiscordApplicationReferences(Enum): + SCOPES = ["identify"] + CLIENT_ID = "1240007913175781508" class Glow(Enum): COLOR = QColor(255, 140, 0, 255) diff --git a/src/discord/discord_oauth.py b/src/discord/discord_oauth.py index 2b736e4..441cdda 100644 --- a/src/discord/discord_oauth.py +++ b/src/discord/discord_oauth.py @@ -3,7 +3,7 @@ import webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs, urlencode, urlparse -from config.constants import AUTENTICATION_SUCCESS_MESSAGE, CLIENT_ID, REDIRECT_URI, SCOPES +from config.constants import AUTENTICATION_SUCCESS_MESSAGE, DiscordApplicationReferences, Urls from fivemserver.get_server_token import GetServerTokenForDiscord from tools.http_client import ApiError, http_get, http_post @@ -13,8 +13,6 @@ os.environ['PYTHONWARNINGS'] = 'ignore' OAUTH_AUTHORIZE_URL = "https://discord.com/api/oauth2/authorize" OAUTH_TOKEN_URL = "https://discord.com/api/oauth2/token" DISCORD_ME_URL = "https://discord.com/api/users/@me" -LOCAL_CALLBACK_HOST = "localhost" -LOCAL_CALLBACK_PORT = 5000 class OAuthCallbackHandler(BaseHTTPRequestHandler): code: str | None = None @@ -45,7 +43,7 @@ def get_discord_client_id() -> str: """ return discord application id """ - return CLIENT_ID + return DiscordApplicationReferences.CLIENT_ID.value # return discord user id def get_discord_user_id() -> tuple[str, str]: @@ -57,17 +55,16 @@ def get_discord_user_id() -> tuple[str, str]: session_id = GetServerTokenForDiscord.authenticate() client_secret = GetServerTokenForDiscord.get_token(session_id) - auth_url = "https://discord.com/api/oauth2/authorize" params = { - "client_id": CLIENT_ID, - "redirect_uri": REDIRECT_URI, + "client_id": DiscordApplicationReferences.CLIENT_ID.value, + "redirect_uri": Urls.LOCAL_CALLBACK_URL.value, "response_type": "code", - "scope": " ".join(SCOPES), + "scope": " ".join(DiscordApplicationReferences.SCOPES.value), } - webbrowser.open(f"{auth_url}?{urlencode(params)}") + webbrowser.open(f"{OAUTH_AUTHORIZE_URL}?{urlencode(params)}") - server = HTTPServer((LOCAL_CALLBACK_HOST, LOCAL_CALLBACK_PORT), OAuthCallbackHandler) + server = HTTPServer((Urls.LOCAL_CALLBACK_HOST.value, Urls.LOCAL_CALLBACK_PORT.value), OAuthCallbackHandler) try: server.handle_request() @@ -81,11 +78,11 @@ def get_discord_user_id() -> tuple[str, str]: token = http_post( OAUTH_TOKEN_URL, data={ - "client_id": CLIENT_ID, + "client_id": DiscordApplicationReferences.CLIENT_ID.value, "client_secret": client_secret, "grant_type": "authorization_code", "code": OAuthCallbackHandler.code, - "redirect_uri": REDIRECT_URI, + "redirect_uri": Urls.LOCAL_CALLBACK_URL.value, }, headers={"Content-Type": "application/x-www-form-urlencoded"}, ).json() diff --git a/src/discord/discord_tools.py b/src/discord/discord_tools.py index 01c5515..ac60e49 100644 --- a/src/discord/discord_tools.py +++ b/src/discord/discord_tools.py @@ -1,8 +1,7 @@ import psutil from pypresence import Presence -from config.constants import Urls -from discord.discord_oauth import CLIENT_ID +from config.constants import Urls, DiscordApplicationReferences from fivemserver.get_server_token import GetServerTokenForDiscord @@ -40,7 +39,7 @@ class CheckDiscord: Vérifie si l'utilisateur Discord est connecté. ⚠️ne vérifie pas le user id discord. """ - rpc = Presence(CLIENT_ID) + rpc = Presence(DiscordApplicationReferences.CLIENT_ID.value) try: rpc.connect() return True diff --git a/src/fivemserver/fivemlauncher.py b/src/fivemserver/fivemlauncher.py index 43b8580..be19ec2 100644 --- a/src/fivemserver/fivemlauncher.py +++ b/src/fivemserver/fivemlauncher.py @@ -1,6 +1,8 @@ import os import subprocess +from config.constants import Urls + class FiveMLauncher: def __init__(self, fivem_path: str): @@ -15,5 +17,5 @@ class FiveMLauncher: subprocess.Popen(self.fivem_path, shell=True) """ - #subprocess.Popen(f"explorer {FIVEMURL}") - subprocess.Popen(r'explorer fivem://connect/prod.la-taniere.fun') + subprocess.Popen(f"explorer {Urls.FIVEMURL.value}") + #subprocess.Popen(r'explorer fivem://connect/prod.la-taniere.fun') diff --git a/src/fivemserver/get_server_token.py b/src/fivemserver/get_server_token.py index 8798bd9..1ed02b8 100644 --- a/src/fivemserver/get_server_token.py +++ b/src/fivemserver/get_server_token.py @@ -5,7 +5,7 @@ from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.hazmat.primitives.kdf.hkdf import HKDF -from config.constants import Urls +from config.constants import Urls, ApiEndPoints from tools.http_client import http_post, ApiError @@ -33,18 +33,18 @@ class GetServerTokenForDiscord: # ========================== try: auth = http_post( - f"{server}/api_v2/auth", + f"{server}/{ApiEndPoints.AUTHENTICATION.value}", json={"client_pub": base64.b64encode(client_pub_pem).decode()}, ).json() except ApiError: raise except ValueError as exc: - raise ApiError("Réponse JSON invalide lors de l'authentification.", url=f"{server}/api_v2/auth") from exc + raise ApiError("Réponse JSON invalide lors de l'authentification.", url=f"{server}/{ApiEndPoints.AUTHENTICATION.value}") from exc server_pub_b64 = auth.get("server_pub") session_id = auth.get("session_id") if not server_pub_b64 or not session_id: - raise ApiError("Réponse d'authentification invalide : données manquantes.", url=f"{server}/api_v2/auth") + raise ApiError("Réponse d'authentification invalide : données manquantes.", url=f"{server}/{ApiEndPoints.AUTHENTICATION.value}") server_pub = serialization.load_pem_public_key(base64.b64decode(server_pub_b64)) shared_key = client_private.exchange(ec.ECDH(), server_pub) @@ -71,19 +71,19 @@ class GetServerTokenForDiscord: try: download = http_post( - f"{server}/api_v2/tkn_auth", + f"{server}/{ApiEndPoints.TOKEN_AUTH.value}", headers={"x-session-id": session_id}, ).json() except ApiError: raise except ValueError as exc: raise ApiError("Réponse JSON invalide lors de la récupération du token.", - url=f"{server}/api_v2/tkn_auth") from exc + url=f"{server}/{ApiEndPoints.TOKEN_AUTH.value}") from exc nonce_b64 = download.get("nonce") encrypted_data_b64 = download.get("data") if not nonce_b64 or not encrypted_data_b64: - raise ApiError("Réponse de token invalide : nonce ou data manquant.", url=f"{server}/api_v2/tkn_auth") + raise ApiError("Réponse de token invalide : nonce ou data manquant.", url=f"{server}/{ApiEndPoints.TOKEN_AUTH.value}") nonce = base64.b64decode(nonce_b64) encrypted_data = base64.b64decode(encrypted_data_b64) @@ -99,7 +99,7 @@ class GetServerTokenForDiscord: try: registration_data = http_post( - f"{server}/api_v2/connection/register", + f"{server}/{ApiEndPoints.REGISTER_USER.value}", headers={"x-session-id": session_id}, json={"discord_id": discord_user_id}, ).json() @@ -108,7 +108,7 @@ class GetServerTokenForDiscord: except ValueError as exc: raise ApiError( "Réponse JSON invalide lors de l'enregistrement Discord.", - url=f"{server}/api_v2/connection/register", + url=f"{server}/{ApiEndPoints.REGISTER_USER.value}", ) from exc return bool(registration_data.get("success", False)) diff --git a/src/fivemserver/queuemanager.py b/src/fivemserver/queuemanager.py index b65117c..2efcf5e 100644 --- a/src/fivemserver/queuemanager.py +++ b/src/fivemserver/queuemanager.py @@ -20,7 +20,7 @@ class QueueManager: def join_queue(self) -> dict: res = requests.post( - f"{Urls.API_URL.value}{ApiEndPoints.QUEUE_JOIN.value}", + f"{Urls.API_URL.value}/{ApiEndPoints.QUEUE_JOIN.value}", json={"uuid": self.user_id}, verify=False ) @@ -28,13 +28,13 @@ class QueueManager: def check_status(self) -> dict: res = requests.get( - f"{Urls.API_URL.value}{ApiEndPoints.QUEUE_STATUS.value}/{self.user_id}" + f"{Urls.API_URL.value}/{ApiEndPoints.QUEUE_STATUS.value}/{self.user_id}" ) return res.json() def leave_queue(self): requests.post( - f"{Urls.API_URL.value}{ApiEndPoints.QUEUE_LEAVE.value}", + f"{Urls.API_URL.value}/{ApiEndPoints.QUEUE_LEAVE.value}", json={"uuid": self.user_id}, verify=False ) @@ -46,7 +46,7 @@ class QueueManager: return try: requests.post( - f"{Urls.API_URL.value}{ApiEndPoints.QUEUE_REFRESH.value}", + f"{Urls.API_URL.value}/{ApiEndPoints.QUEUE_REFRESH.value}", json={ "uuid": self.user_id, "session_id": session_id, diff --git a/src/fivemserver/whitelistmanager.py b/src/fivemserver/whitelistmanager.py index 7082995..a2ee6ad 100644 --- a/src/fivemserver/whitelistmanager.py +++ b/src/fivemserver/whitelistmanager.py @@ -1,20 +1,18 @@ from config.constants import PlayerServerInfo from tools.http_client import ApiError, http_get - -WHITELIST_URL_ENDPOINT = "iswhitelist/" - +from config.constants import ApiEndPoints class WhiteList: @staticmethod def check_whitelist(url: str, discord_user_id: str) -> None: try: - api_data = http_get(f"{url}{WHITELIST_URL_ENDPOINT}{discord_user_id}").json() + api_data = http_get(f"{url}/{ApiEndPoints.WHITELIST_URL_ENDPOINT.value}/{discord_user_id}").json() except ApiError: raise except ValueError as exc: raise ApiError( "Réponse JSON invalide lors de la vérification whitelist.", - url=f"{url}{WHITELIST_URL_ENDPOINT}{discord_user_id}", + url=f"{url}/{ApiEndPoints.WHITELIST_URL_ENDPOINT.value}/{discord_user_id}", ) from exc PlayerServerInfo.is_whitelist = api_data.get("whitelisted", False)