Update to the 3.0.0 V

This commit is contained in:
adator
2025-10-18 20:49:21 +02:00
parent fd9643eddc
commit a043a58f45
18 changed files with 435 additions and 415 deletions

View File

@@ -9,6 +9,11 @@ class Admin:
UID_ADMIN_DB: list[MAdmin] = [] UID_ADMIN_DB: list[MAdmin] = []
def __init__(self, loader: 'Loader') -> None: def __init__(self, loader: 'Loader') -> None:
"""
Args:
loader (Loader): The Loader Instance.
"""
self.Logs = loader.Logs self.Logs = loader.Logs
self.Base = loader.Base self.Base = loader.Base
self.Setting = loader.Settings self.Setting = loader.Settings

View File

@@ -11,14 +11,16 @@ class Channel:
"""List that contains all the Channels objects (ChannelModel) """List that contains all the Channels objects (ChannelModel)
""" """
def __init__(self, loader: 'Loader') -> None: def __init__(self, loader: 'Loader'):
"""
Args:
loader (Loader): The Loader Instance
"""
self.Logs = loader.Logs self.Logs = loader.Logs
self.Base = loader.Base self.Base = loader.Base
self.Utils = loader.Utils self.Utils = loader.Utils
return None
def insert(self, new_channel: 'MChannel') -> bool: def insert(self, new_channel: 'MChannel') -> bool:
"""This method will insert a new channel and if the channel exist it will update the user list (uids) """This method will insert a new channel and if the channel exist it will update the user list (uids)
@@ -110,6 +112,7 @@ class Channel:
return result return result
except ValueError as ve: except ValueError as ve:
self.Logs.error(f'{ve}') self.Logs.error(f'{ve}')
return False
def delete_user_from_all_channel(self, uid:str) -> bool: def delete_user_from_all_channel(self, uid:str) -> bool:
"""Delete a client from all channels """Delete a client from all channels
@@ -134,6 +137,7 @@ class Channel:
return result return result
except ValueError as ve: except ValueError as ve:
self.Logs.error(f'{ve}') self.Logs.error(f'{ve}')
return False
def add_user_to_a_channel(self, channel_name: str, uid: str) -> bool: def add_user_to_a_channel(self, channel_name: str, uid: str) -> bool:
"""Add a client to a channel """Add a client to a channel
@@ -226,16 +230,18 @@ class Channel:
return False return False
pattern = fr'^#' pattern = fr'^#'
isChannel = findall(pattern, channel_to_check) is_channel = findall(pattern, channel_to_check)
if not isChannel: if not is_channel:
return False return False
else: else:
return True return True
except TypeError as te: except TypeError as te:
self.Logs.error(f'TypeError: [{channel_to_check}] - {te}') self.Logs.error(f'TypeError: [{channel_to_check}] - {te}')
return False
except Exception as err: except Exception as err:
self.Logs.error(f'Error Not defined: {err}') self.Logs.error(f'Error Not defined: {err}')
return False
def db_query_channel(self, action: Literal['add','del'], module_name: str, channel_name: str) -> bool: def db_query_channel(self, action: Literal['add','del'], module_name: str, channel_name: str) -> bool:
"""You can add a channel or delete a channel. """You can add a channel or delete a channel.
@@ -282,8 +288,7 @@ class Channel:
else: else:
return False return False
case _:
return False
except Exception as err: except Exception as err:
self.Logs.error(err) self.Logs.error(err)
return False

View File

@@ -10,7 +10,11 @@ class Client:
CLIENT_DB: list['MClient'] = [] CLIENT_DB: list['MClient'] = []
def __init__(self, loader: 'Loader'): def __init__(self, loader: 'Loader'):
"""
Args:
loader (Loader): The Loader instance.
"""
self.Logs = loader.Logs self.Logs = loader.Logs
self.Base = loader.Base self.Base = loader.Base
@@ -34,12 +38,12 @@ class Client:
return True return True
def update_nickname(self, uid: str, newNickname: str) -> bool: def update_nickname(self, uid: str, new_nickname: str) -> bool:
"""Update the nickname starting from the UID """Update the nickname starting from the UID
Args: Args:
uid (str): UID of the user uid (str): UID of the user
newNickname (str): New nickname new_nickname (str): New nickname
Returns: Returns:
bool: True if updated bool: True if updated
@@ -49,7 +53,7 @@ class Client:
if user_obj is None: if user_obj is None:
return False return False
user_obj.nickname = newNickname user_obj.nickname = new_nickname
return True return True
@@ -181,7 +185,7 @@ class Client:
return client_obj.to_dict() return client_obj.to_dict()
def is_exist(self, uidornikname: str) -> bool: def is_exist(self, uidornickname: str) -> bool:
"""Check if the UID or the nickname exist in the USER DB """Check if the UID or the nickname exist in the USER DB
Args: Args:
@@ -190,7 +194,7 @@ class Client:
Returns: Returns:
bool: True if exist bool: True if exist
""" """
user_obj = self.get_Client(uidornickname=uidornikname) user_obj = self.get_Client(uidornickname=uidornickname)
if user_obj is None: if user_obj is None:
return False return False
@@ -231,9 +235,9 @@ class Client:
""" """
pattern = fr'[:|@|%|\+|~|\*]*' pattern = fr'[:|@|%|\+|~|\*]*'
parsed_UID = sub(pattern, '', uid) parsed_uid = sub(pattern, '', uid)
if not parsed_UID: if not parsed_uid:
return None return None
return parsed_UID return parsed_uid

View File

@@ -9,6 +9,10 @@ class Command:
DB_COMMANDS: list['MCommand'] = [] DB_COMMANDS: list['MCommand'] = []
def __init__(self, loader: 'Loader'): def __init__(self, loader: 'Loader'):
"""
Args:
loader (Loader): The Loader instance.
"""
self.Loader = loader self.Loader = loader
self.Base = loader.Base self.Base = loader.Base
self.Logs = loader.Logs self.Logs = loader.Logs

View File

@@ -10,6 +10,11 @@ class CommandHandler:
DB_SUBSCRIBE: list = [] DB_SUBSCRIBE: list = []
def __init__(self, loader: 'Loader'): def __init__(self, loader: 'Loader'):
"""Init method
Args:
loader (Loader): The loader Object
"""
self.__Logs = loader.Logs self.__Logs = loader.Logs
def register(self, ircd_command_model: 'MIrcdCommand') -> None: def register(self, ircd_command_model: 'MIrcdCommand') -> None:
@@ -25,6 +30,7 @@ class CommandHandler:
return None return None
else: else:
self.__Logs.debug(f'[IRCD COMMAND HANDLER] This IRCD command ({ircd_command.command_name}) already exist in the handler.') self.__Logs.debug(f'[IRCD COMMAND HANDLER] This IRCD command ({ircd_command.command_name}) already exist in the handler.')
return None
def get_registred_ircd_command(self, command_name: str) -> Optional['MIrcdCommand']: def get_registred_ircd_command(self, command_name: str) -> Optional['MIrcdCommand']:
"""Get the registred IRCD command model """Get the registred IRCD command model

View File

@@ -9,6 +9,11 @@ if TYPE_CHECKING:
class ProtocolFactorty: class ProtocolFactorty:
def __init__(self, uplink: 'Irc'): def __init__(self, uplink: 'Irc'):
"""ProtocolFactory init.
Args:
uplink (Irc): The Irc object
"""
self.__Config = uplink.Config self.__Config = uplink.Config
self.__uplink = uplink self.__uplink = uplink

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,14 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import Optional, TYPE_CHECKING from typing import Optional, TYPE_CHECKING
from core.classes.protocols.command_handler import CommandHandler
if TYPE_CHECKING: if TYPE_CHECKING:
from core.classes.sasl import Sasl from core.definition import MClient, MSasl
from core.definition import MClient, MSasl, MRegister
from core.classes.protocols.command_handler import CommandHandler
class IProtocol(ABC): class IProtocol(ABC):
DB_REGISTER: list['MRegister'] = [] Handler: Optional[CommandHandler] = None
Handler: Optional['CommandHandler'] = None
@abstractmethod @abstractmethod
def get_ircd_protocol_poisition(self, cmd: list[str], log: bool = False) -> tuple[int, Optional[str]]: def get_ircd_protocol_poisition(self, cmd: list[str], log: bool = False) -> tuple[int, Optional[str]]:
@@ -33,7 +32,8 @@ class IProtocol(ABC):
"""Envoit les commandes à envoyer au serveur. """Envoit les commandes à envoyer au serveur.
Args: Args:
string (Str): contient la commande à envoyer au serveur. message (str): contient la commande à envoyer au serveur.
print_log (bool): If True then print logs
""" """
@abstractmethod @abstractmethod
@@ -65,15 +65,15 @@ class IProtocol(ABC):
@abstractmethod @abstractmethod
def send_gline(self, nickname: str, hostname: str, set_by: str, expire_timestamp: int, set_at_timestamp: int, reason: str) -> None: def send_gline(self, nickname: str, hostname: str, set_by: str, expire_timestamp: int, set_at_timestamp: int, reason: str) -> None:
"""_summary_ """Send a gline command to the server
Args: Args:
nickname (str): _description_ nickname (str): The nickname of the client.
hostname (str): _description_ hostname (str): The hostname of the client.
set_by (str): _description_ set_by (str): The nickname who send the gline
expire_timestamp (int): _description_ expire_timestamp (int): Expire timestamp
set_at_timestamp (int): _description_ set_at_timestamp (int): Set at timestamp
reason (str): _description_ reason (str): The reason of the gline.
""" """
@abstractmethod @abstractmethod
@@ -149,8 +149,7 @@ class IProtocol(ABC):
"""_summary_ """_summary_
Args: Args:
from_nick (str): _description_ nick_to_sapart (str): _description_
nick_to (str): _description_
channel_name (str): _description_ channel_name (str): _description_
""" """
@@ -215,18 +214,19 @@ class IProtocol(ABC):
"""Logout a client from his account """Logout a client from his account
Args: Args:
client_uid (str): The Client UID client_obj (MClient): The Client UID
""" """
@abstractmethod @abstractmethod
def send_quit(self, uid: str, reason: str, print_log: True) -> None: def send_quit(self, uid: str, reason: str, print_log: bool = True) -> None:
"""Send quit message """Send quit message
- Delete uid from User object - Delete uid from User object
- Delete uid from Reputation object - Delete uid from Reputation object
Args: Args:
uidornickname (str): The UID or the Nickname uid (str): The UID or the Nickname
reason (str): The reason for the quit reason (str): The reason for the quit
print_log (bool): If True then print logs
""" """
@abstractmethod @abstractmethod
@@ -288,46 +288,46 @@ class IProtocol(ABC):
# ------------------------------------------------------------------------ # ------------------------------------------------------------------------
@abstractmethod @abstractmethod
def parse_uid(self, serverMsg: list[str]) -> dict[str, str]: def parse_uid(self, server_msg: list[str]) -> dict[str, str]:
"""Parse UID and return dictionary. """Parse UID and return dictionary.
Args: Args:
serverMsg (list[str]): The UID IRCD message server_msg (list[str]): The UID IRCD message
Returns: Returns:
dict[str, str]: The response as dictionary. dict[str, str]: The response as dictionary.
""" """
@abstractmethod @abstractmethod
def parse_quit(self, serverMsg: list[str]) -> dict[str, str]: def parse_quit(self, server_msg: list[str]) -> dict[str, str]:
"""Parse quit and return dictionary. """Parse quit and return dictionary.
>>> [':97KAAAAAB', 'QUIT', ':Quit:', 'this', 'is', 'my', 'reason', 'to', 'quit'] >>> [':97KAAAAAB', 'QUIT', ':Quit:', 'this', 'is', 'my', 'reason', 'to', 'quit']
Args: Args:
serverMsg (list[str]): The server message to parse server_msg (list[str]): The server message to parse
Returns: Returns:
dict[str, str]: The response as dictionary. dict[str, str]: The response as dictionary.
""" """
@abstractmethod @abstractmethod
def parse_nick(self, serverMsg: list[str]) -> dict[str, str]: def parse_nick(self, server_msg: list[str]) -> dict[str, str]:
"""Parse nick changes and return dictionary. """Parse nick changes and return dictionary.
>>> [':97KAAAAAC', 'NICK', 'testinspir', '1757360740'] >>> [':97KAAAAAC', 'NICK', 'testinspir', '1757360740']
Args: Args:
serverMsg (list[str]): The server message to parse server_msg (list[str]): The server message to parse
Returns: Returns:
dict[str, str]: The response as dictionary. dict[str, str]: The response as dictionary.
""" """
@abstractmethod @abstractmethod
def parse_privmsg(self, serverMsg: list[str]) -> dict[str, str]: def parse_privmsg(self, server_msg: list[str]) -> dict[str, str]:
"""Parse PRIVMSG message. """Parse PRIVMSG message.
>>> [':97KAAAAAE', 'PRIVMSG', '#welcome', ':This', 'is', 'my', 'public', 'message'] >>> [':97KAAAAAE', 'PRIVMSG', '#welcome', ':This', 'is', 'my', 'public', 'message']
Args: Args:
serverMsg (list[str]): The server message to parse server_msg (list[str]): The server message to parse
Returns: Returns:
dict[str, str]: The response as dictionary. dict[str, str]: The response as dictionary.
@@ -345,175 +345,177 @@ class IProtocol(ABC):
# ------------------------------------------------------------------------ # ------------------------------------------------------------------------
@abstractmethod @abstractmethod
def on_svs2mode(self, serverMsg: list[str]) -> None: def on_svs2mode(self, server_msg: list[str]) -> None:
"""Handle svs2mode coming from a server """Handle svs2mode coming from a server
>>> [':00BAAAAAG', 'SVS2MODE', '001U01R03', '-r'] >>> [':00BAAAAAG', 'SVS2MODE', '001U01R03', '-r']
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_mode(self, serverMsg: list[str]) -> None: def on_mode(self, server_msg: list[str]) -> None:
"""Handle mode coming from a server """Handle mode coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_umode2(self, serverMsg: list[str]) -> None: def on_umode2(self, server_msg: list[str]) -> None:
"""Handle umode2 coming from a server """Handle umode2 coming from a server
>>> [':adator_', 'UMODE2', '-i'] >>> [':adator_', 'UMODE2', '-i']
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_quit(self, serverMsg: list[str]) -> None: def on_quit(self, server_msg: list[str]) -> None:
"""Handle quit coming from a server """Handle quit coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_squit(self, serverMsg: list[str]) -> None: def on_squit(self, server_msg: list[str]) -> None:
"""Handle squit coming from a server """Handle squit coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_protoctl(self, serverMsg: list[str]) -> None: def on_protoctl(self, server_msg: list[str]) -> None:
"""Handle protoctl coming from a server """Handle protoctl coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_nick(self, serverMsg: list[str]) -> None: def on_nick(self, server_msg: list[str]) -> None:
"""Handle nick coming from a server """Handle nick coming from a server
new nickname new nickname
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_sjoin(self, serverMsg: list[str]) -> None: def on_sjoin(self, server_msg: list[str]) -> None:
"""Handle sjoin coming from a server """Handle sjoin coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_part(self, serverMsg: list[str]) -> None: def on_part(self, server_msg: list[str]) -> None:
"""Handle part coming from a server """Handle part coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_eos(self, serverMsg: list[str]) -> None: def on_eos(self, server_msg: list[str]) -> None:
"""Handle EOS coming from a server """Handle EOS coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_reputation(self, serverMsg: list[str]) -> None: def on_reputation(self, server_msg: list[str]) -> None:
"""Handle REPUTATION coming from a server """Handle REPUTATION coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_uid(self, serverMsg: list[str]) -> None: def on_uid(self, server_msg: list[str]) -> None:
"""Handle uid message coming from the server """Handle uid message coming from the server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_privmsg(self, serverMsg: list[str]) -> None: def on_privmsg(self, server_msg: list[str]) -> None:
"""Handle PRIVMSG message coming from the server """Handle PRIVMSG message coming from the server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_server_ping(self, serverMsg: list[str]) -> None: def on_server_ping(self, server_msg: list[str]) -> None:
"""Send a PONG message to the server """Send a PONG message to the server
Args: Args:
serverMsg (list[str]): List of str coming from the server server_msg (list[str]): List of str coming from the server
""" """
@abstractmethod @abstractmethod
def on_server(self, serverMsg: list[str]) -> None: def on_server(self, server_msg: list[str]) -> None:
"""_summary_ """_summary_
Args: Args:
serverMsg (list[str]): _description_ server_msg (list[str]): _description_
""" """
@abstractmethod @abstractmethod
def on_version(self, serverMsg: list[str]) -> None: def on_version(self, server_msg: list[str]) -> None:
"""Sending Server Version to the server """Sending Server Version to the server
Args: Args:
serverMsg (list[str]): List of str coming from the server server_msg (list[str]): List of str coming from the server
""" """
@abstractmethod @abstractmethod
def on_time(self, serverMsg: list[str]) -> None: def on_time(self, server_msg: list[str]) -> None:
"""Sending TIME answer to a requestor """Sending TIME answer to a requestor
Args: Args:
serverMsg (list[str]): List of str coming from the server server_msg (list[str]): List of str coming from the server
""" """
@abstractmethod @abstractmethod
def on_ping(self, serverMsg: list[str]) -> None: def on_ping(self, server_msg: list[str]) -> None:
"""Sending a PING answer to requestor """Sending a PING answer to requestor
Args: Args:
serverMsg (list[str]): List of str coming from the server server_msg (list[str]): List of str coming from the server
""" """
@abstractmethod @abstractmethod
def on_version_msg(self, serverMsg: list[str]) -> None: def on_version_msg(self, server_msg: list[str]) -> None:
"""Handle version coming from the server """Handle version coming from the server
\n ex. /version Defender \n ex. /version Defender
Args: Args:
serverMsg (list[str]): Original message from the server server_msg (list[str]): Original message from the server
""" """
@abstractmethod @abstractmethod
def on_smod(self, serverMsg: list[str]) -> None: def on_smod(self, server_msg: list[str]) -> None:
"""Handle SMOD message coming from the server """Handle SMOD message coming from the server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
""" """
@abstractmethod @abstractmethod
def on_sasl(self, serverMsg: list[str], psasl: 'Sasl') -> Optional['MSasl']: def on_sasl(self, server_msg: list[str]) -> Optional['MSasl']:
"""Handle SASL coming from a server """Handle SASL coming from a server
Args: Args:
serverMsg (list[str]): Original server message server_msg (list[str]): Original server message
psasl (Sasl): The SASL process object
Returns:
""" """
@abstractmethod @abstractmethod
@@ -528,9 +530,9 @@ class IProtocol(ABC):
""" """
@abstractmethod @abstractmethod
def on_md(self, serverMsg: list[str]) -> None: def on_md(self, server_msg: list[str]) -> None:
"""Handle MD responses """Handle MD responses
[':001', 'MD', 'client', '001MYIZ03', 'certfp', ':d1235648...'] [':001', 'MD', 'client', '001MYIZ03', 'certfp', ':d1235648...']
Args: Args:
serverMsg (list[str]): The server reply server_msg (list[str]): The server reply
""" """

View File

@@ -202,43 +202,52 @@ class Unrealircd6(IProtocol):
"""Créer le link et envoyer les informations nécessaires pour la """Créer le link et envoyer les informations nécessaires pour la
connexion au serveur. connexion au serveur.
""" """
service_id = self.__Config.SERVICE_ID
nickname = self.__Config.SERVICE_NICKNAME service_nickname = self.__Config.SERVICE_NICKNAME
username = self.__Config.SERVICE_USERNAME service_username = self.__Config.SERVICE_USERNAME
realname = self.__Config.SERVICE_REALNAME service_realname = self.__Config.SERVICE_REALNAME
chan = self.__Config.SERVICE_CHANLOG service_channel_log = self.__Config.SERVICE_CHANLOG
info = self.__Config.SERVICE_INFO service_info = self.__Config.SERVICE_INFO
smodes = self.__Config.SERVICE_SMODES service_smodes = self.__Config.SERVICE_SMODES
cmodes = self.__Config.SERVICE_CMODES service_cmodes = self.__Config.SERVICE_CMODES
umodes = self.__Config.SERVICE_UMODES service_umodes = self.__Config.SERVICE_UMODES
host = self.__Config.SERVICE_HOST service_hostname = self.__Config.SERVICE_HOST
service_name = self.__Config.SERVICE_NAME service_name = self.__Config.SERVICE_NAME
protocolversion = self.protocol_version protocolversion = self.protocol_version
password = self.__Config.SERVEUR_PASSWORD server_password = self.__Config.SERVEUR_PASSWORD
link = self.__Config.SERVEUR_LINK server_link = self.__Config.SERVEUR_LINK
server_id = self.__Config.SERVEUR_ID server_id = self.__Config.SERVEUR_ID
service_id = self.__Config.SERVICE_ID
version = self.__Config.CURRENT_VERSION version = self.__Config.CURRENT_VERSION
unixtime = self.__Utils.get_unixtime() unixtime = self.__Utils.get_unixtime()
self.send2socket(f":{server_id} PASS :{password}", print_log=False) self.send2socket(f":{server_id} PASS :{server_password}", print_log=False)
self.send2socket(f":{server_id} PROTOCTL SID NOQUIT NICKv2 SJOIN SJ3 NICKIP TKLEXT2 NEXTBANS CLK EXTSWHOIS MLOCK MTAGS") self.send2socket(f":{server_id} PROTOCTL SID NOQUIT NICKv2 SJOIN SJ3 NICKIP TKLEXT2 NEXTBANS CLK EXTSWHOIS MLOCK MTAGS")
self.send2socket(f":{server_id} PROTOCTL EAUTH={link},{protocolversion},,{service_name}-v{version}") self.send2socket(f":{server_id} PROTOCTL EAUTH={server_link},{protocolversion},,{service_name}-v{version}")
self.send2socket(f":{server_id} PROTOCTL SID={server_id}") self.send2socket(f":{server_id} PROTOCTL SID={server_id}")
self.send2socket(f":{server_id} PROTOCTL BOOTED={unixtime}") self.send2socket(f":{server_id} PROTOCTL BOOTED={unixtime}")
self.send2socket(f":{server_id} SERVER {link} 1 :{info}") self.send2socket(f":{server_id} SERVER {server_link} 1 :{service_info}")
self.send2socket("EOS") self.send2socket("EOS")
self.send2socket(f":{server_id} {nickname} :Reserved for services") self.send2socket(f":{server_id} {service_nickname} :Reserved for services")
self.send2socket(f":{server_id} UID {nickname} 1 {unixtime} {username} {host} {service_id} * {smodes} * * fwAAAQ== :{realname}") self.send2socket(f":{server_id} UID {service_nickname} 1 {unixtime} {service_username} {service_hostname} {service_id} * {service_smodes} * * fwAAAQ== :{service_realname}")
self.send_sjoin(chan) self.send_sjoin(service_channel_log)
self.send2socket(f":{server_id} TKL + Q * {nickname} {host} 0 {unixtime} :Reserved for services") self.send2socket(f":{server_id} TKL + Q * {service_nickname} {service_hostname} 0 {unixtime} :Reserved for services")
self.send2socket(f":{service_id} MODE {chan} {cmodes}") self.send2socket(f":{service_id} MODE {service_channel_log} {service_cmodes}")
self.__Logs.debug(f'>> {__name__} Link information sent to the server') self.__Logs.debug(f'>> {__name__} Link information sent to the server')
def send_gline(self, nickname: str, hostname: str, set_by: str, expire_timestamp: int, set_at_timestamp: int, reason: str) -> None: def send_gline(self, nickname: str, hostname: str, set_by: str, expire_timestamp: int, set_at_timestamp: int, reason: str) -> None:
"""Send a gline command to the server
Args:
nickname (str): The nickname of the client.
hostname (str): The hostname of the client.
set_by (str): The nickname who send the gline
expire_timestamp (int): Expire timestamp
set_at_timestamp (int): Set at timestamp
reason (str): The reason of the gline.
"""
# TKL + G user host set_by expire_timestamp set_at_timestamp :reason # TKL + G user host set_by expire_timestamp set_at_timestamp :reason
self.send2socket(f":{self.__Config.SERVEUR_ID} TKL + G {nickname} {hostname} {set_by} {expire_timestamp} {set_at_timestamp} :{reason}") self.send2socket(f":{self.__Config.SERVEUR_ID} TKL + G {nickname} {hostname} {set_by} {expire_timestamp} {set_at_timestamp} :{reason}")
@@ -1286,7 +1295,7 @@ class Unrealircd6(IProtocol):
except AttributeError as ae: except AttributeError as ae:
self.__Logs.error(f"Attribute Error: {ae}") self.__Logs.error(f"Attribute Error: {ae}")
except Exception as err: except Exception as err:
self.__Logs.error(f"General Error: {err} - {srv_msg}") self.__Logs.error(f"General Error: {err} - {srv_msg}" , exc_info=True)
def on_server_ping(self, serverMsg: list[str]) -> None: def on_server_ping(self, serverMsg: list[str]) -> None:
"""Send a PONG message to the server """Send a PONG message to the server

View File

@@ -22,7 +22,12 @@ REHASH_MODULES = [
def restart_service(uplink: 'Irc', reason: str = "Restarting with no reason!") -> None: def restart_service(uplink: 'Irc', reason: str = "Restarting with no reason!") -> None:
"""
Args:
uplink (Irc): The Irc instance
reason (str): The reason of the restart.
"""
# reload modules. # reload modules.
for module in uplink.ModuleUtils.model_get_loaded_modules().copy(): for module in uplink.ModuleUtils.model_get_loaded_modules().copy():
uplink.ModuleUtils.unload_one_module(uplink, module.module_name) uplink.ModuleUtils.unload_one_module(uplink, module.module_name)
@@ -34,7 +39,7 @@ def restart_service(uplink: 'Irc', reason: str = "Restarting with no reason!") -
uplink.Base.garbage_collector_thread() uplink.Base.garbage_collector_thread()
uplink.Logs.debug(f'[{uplink.Config.SERVICE_NICKNAME} RESTART]: Reloading configuration!') uplink.Logs.debug(f'[{uplink.Config.SERVICE_NICKNAME} RESTART]: Reloading configuration!')
uplink.Protocol.send_squit(server_id=uplink.Config.SERVEUR_ID, server_link=uplink.Config.SERVEUR_LINK, reason="Defender Power off") uplink.Protocol.send_squit(server_id=uplink.Config.SERVEUR_ID, server_link=uplink.Config.SERVEUR_LINK, reason=reason)
uplink.Logs.debug('Restarting Defender ...') uplink.Logs.debug('Restarting Defender ...')
uplink.IrcSocket.shutdown(socket.SHUT_RDWR) uplink.IrcSocket.shutdown(socket.SHUT_RDWR)
uplink.IrcSocket.close() uplink.IrcSocket.close()
@@ -72,13 +77,13 @@ def rehash_service(uplink: 'Irc', nickname: str) -> None:
channel=uplink.Config.SERVICE_CHANLOG channel=uplink.Config.SERVICE_CHANLOG
) )
uplink.Utils = sys.modules['core.utils'] uplink.Utils = sys.modules['core.utils']
uplink.Loader.Config = uplink.Loader.ConfModule.Configuration(uplink.Loader).get_config_model() uplink.Config = uplink.Loader.ConfModule.Configuration(uplink.Loader).get_config_model()
uplink.Loader.Config.HSID = config_model_bakcup.HSID uplink.Config.HSID = config_model_bakcup.HSID
uplink.Loader.Config.DEFENDER_INIT = config_model_bakcup.DEFENDER_INIT uplink.Config.DEFENDER_INIT = config_model_bakcup.DEFENDER_INIT
uplink.Loader.Config.DEFENDER_RESTART = config_model_bakcup.DEFENDER_RESTART uplink.Config.DEFENDER_RESTART = config_model_bakcup.DEFENDER_RESTART
uplink.Loader.Config.SSL_VERSION = config_model_bakcup.SSL_VERSION uplink.Config.SSL_VERSION = config_model_bakcup.SSL_VERSION
uplink.Loader.Config.CURRENT_VERSION = config_model_bakcup.CURRENT_VERSION uplink.Config.CURRENT_VERSION = config_model_bakcup.CURRENT_VERSION
uplink.Loader.Config.LATEST_VERSION = config_model_bakcup.LATEST_VERSION uplink.Config.LATEST_VERSION = config_model_bakcup.LATEST_VERSION
conf_bkp_dict: dict = config_model_bakcup.to_dict() conf_bkp_dict: dict = config_model_bakcup.to_dict()
config_dict: dict = uplink.Config.to_dict() config_dict: dict = uplink.Config.to_dict()

View File

@@ -9,9 +9,14 @@ class Reputation:
UID_REPUTATION_DB: list[MReputation] = [] UID_REPUTATION_DB: list[MReputation] = []
def __init__(self, loader: 'Loader'): def __init__(self, loader: 'Loader'):
"""
Args:
loader (Loader): The Loader instance.
"""
self.Logs = loader.Logs self.Logs = loader.Logs
self.MReputation: MReputation = MReputation self.MReputation: Optional[MReputation] = None
def insert(self, new_reputation_user: MReputation) -> bool: def insert(self, new_reputation_user: MReputation) -> bool:
"""Insert a new Reputation User object """Insert a new Reputation User object
@@ -47,7 +52,7 @@ class Reputation:
Args: Args:
uid (str): UID of the user uid (str): UID of the user
newNickname (str): New nickname new_nickname (str): New nickname
Returns: Returns:
bool: True if updated bool: True if updated

View File

@@ -1,4 +1,4 @@
from typing import Optional, Union, TYPE_CHECKING from typing import Optional, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from core.definition import MSasl from core.definition import MSasl
@@ -9,13 +9,18 @@ class Sasl:
DB_SASL: list['MSasl'] = [] DB_SASL: list['MSasl'] = []
def __init__(self, loader: 'Loader'): def __init__(self, loader: 'Loader'):
"""
Args:
loader (Loader): The Loader instance.
"""
self.Logs = loader.Logs # logger self.Logs = loader.Logs # logger
def insert_sasl_client(self, psasl: 'MSasl') -> bool: def insert_sasl_client(self, psasl: 'MSasl') -> bool:
"""Insert a new Sasl authentication """Insert a new Sasl authentication
Args: Args:
new_user (UserModel): New userModel object psasl (MSasl): New userModel object
Returns: Returns:
bool: True if inserted bool: True if inserted
@@ -38,7 +43,7 @@ class Sasl:
"""Delete the User starting from the UID """Delete the User starting from the UID
Args: Args:
uid (str): UID of the user client_uid (str): UID of the user
Returns: Returns:
bool: True if deleted bool: True if deleted

View File

@@ -1,5 +1,5 @@
'''This class should never be reloaded. """This class should never be reloaded.
''' """
from logging import Logger from logging import Logger
from threading import Timer, Thread, RLock from threading import Timer, Thread, RLock
from socket import socket from socket import socket
@@ -18,7 +18,7 @@ class Settings:
RUNNING_TIMERS: list[Timer] = [] RUNNING_TIMERS: list[Timer] = []
RUNNING_THREADS: list[Thread] = [] RUNNING_THREADS: list[Thread] = []
RUNNING_SOCKETS: list[socket] = [] RUNNING_SOCKETS: list[socket] = []
PERIODIC_FUNC: dict[object] = {} PERIODIC_FUNC: dict[str, Any] = {}
LOCK: RLock = RLock() LOCK: RLock = RLock()
CONSOLE: bool = False CONSOLE: bool = False

View File

@@ -11,9 +11,13 @@ if TYPE_CHECKING:
class Translation: class Translation:
def __init__(self, loader: 'Loader') -> None: def __init__(self, loader: 'Loader') -> None:
"""
Args:
loader (Loader): The Loader instance.
"""
self.Logs = loader.Logs self.Logs = loader.Logs
self.Settings = loader.Settings self.Settings = loader.Settings
return None
def get_translation(self) -> dict[str, list[list[str]]]: def get_translation(self) -> dict[str, list[list[str]]]:
try: try:

View File

@@ -1014,7 +1014,7 @@ class Irc:
except KeyError as ke: except KeyError as ke:
self.Logs.error(f"Key Error: {ke} - list recieved: {cmd}") self.Logs.error(f"Key Error: {ke} - list recieved: {cmd}")
except Exception as err: except Exception as err:
self.Logs.error(f"General Error: {ke} - list recieved: {cmd}") self.Logs.error(f"General Error: {err} - list recieved: {cmd}", exc_info=True)
case 'unload': case 'unload':
# unload mod_defender # unload mod_defender

View File

@@ -206,6 +206,7 @@ class Module:
module = self.model_get_module(module_name) module = self.model_get_module(module_name)
if module is None: if module is None:
self.__Logs.debug(f"[ UNLOAD MODULE ERROR ] This module {module_name} is not loaded!") self.__Logs.debug(f"[ UNLOAD MODULE ERROR ] This module {module_name} is not loaded!")
self.db_delete_module(module_name)
uplink.Protocol.send_priv_msg( uplink.Protocol.send_priv_msg(
nick_from=self.__Config.SERVICE_NICKNAME, nick_from=self.__Config.SERVICE_NICKNAME,
msg=f"[ {red}UNLOAD MODULE ERROR{nogc} ] This module {module_name} is not loaded!", msg=f"[ {red}UNLOAD MODULE ERROR{nogc} ] This module {module_name} is not loaded!",

View File

@@ -1,13 +1,13 @@
import logging import logging
import asyncio import asyncio
from unrealircd_rpc_py.objects.Definition import LiveRPCResult
import mods.jsonrpc.utils as utils import mods.jsonrpc.utils as utils
import mods.jsonrpc.threads as thds import mods.jsonrpc.threads as thds
from time import sleep from time import sleep
from types import SimpleNamespace
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from dataclasses import dataclass from dataclasses import dataclass
from unrealircd_rpc_py.Live import LiveWebsocket, LiveUnixSocket from unrealircd_rpc_py.ConnectionFactory import ConnectionFactory
from unrealircd_rpc_py.Loader import Loader from unrealircd_rpc_py.LiveConnectionFactory import LiveConnectionFactory
if TYPE_CHECKING: if TYPE_CHECKING:
from core.irc import Irc from core.irc import Irc
@@ -85,43 +85,24 @@ class Jsonrpc():
self.__load_module_configuration() self.__load_module_configuration()
# End of mandatory methods you can start your customization # # End of mandatory methods you can start your customization #
self.UnrealIrcdRpcLive: LiveWebsocket = LiveWebsocket( try:
url=self.Config.JSONRPC_URL, self.Rpc = ConnectionFactory(self.Config.DEBUG_LEVEL).get(self.Config.JSONRPC_METHOD)
username=self.Config.JSONRPC_USER, self.LiveRpc = LiveConnectionFactory(self.Config.DEBUG_LEVEL).get(self.Config.JSONRPC_METHOD)
password=self.Config.JSONRPC_PASSWORD, self.Rpc.setup({'url': self.Config.JSONRPC_URL, 'username': self.Config.JSONRPC_USER, 'password': self.Config.JSONRPC_PASSWORD})
callback_object_instance=self, self.LiveRpc.setup({'url': self.Config.JSONRPC_URL, 'username': self.Config.JSONRPC_USER, 'password': self.Config.JSONRPC_PASSWORD,
callback_method_or_function_name='callback_sent_to_irc' 'callback_object_instance' : self, 'callback_method_or_function_name': 'callback_sent_to_irc'})
)
if self.UnrealIrcdRpcLive.get_error.code != 0:
self.Logs.error(f"{self.UnrealIrcdRpcLive.get_error.message} ({self.UnrealIrcdRpcLive.get_error.code})")
self.Protocol.send_priv_msg(
nick_from=self.Config.SERVICE_NICKNAME,
msg=f"[{self.Config.COLORS.red}ERROR{self.Config.COLORS.nogc}] {self.UnrealIrcdRpcLive.get_error.message}",
channel=self.Config.SERVICE_CHANLOG
)
raise Exception(f"[LIVE-JSONRPC ERROR] {self.UnrealIrcdRpcLive.get_error.message}")
self.Rpc: Loader = Loader(
req_method=self.Config.JSONRPC_METHOD,
url=self.Config.JSONRPC_URL,
username=self.Config.JSONRPC_USER,
password=self.Config.JSONRPC_PASSWORD
)
if self.Rpc.get_error.code != 0:
self.Logs.error(f"{self.Rpc.get_error.message} ({self.Rpc.get_error.code})")
self.Protocol.send_priv_msg(
nick_from=self.Config.SERVICE_NICKNAME,
msg=f"[{self.Config.COLORS.red}JSONRPC ERROR{self.Config.COLORS.nogc}] {self.Rpc.get_error.message}",
channel=self.Config.SERVICE_CHANLOG
)
raise Exception(f"[JSONRPC ERROR] {self.Rpc.get_error.message}")
if self.ModConfig.jsonrpc == 1: if self.ModConfig.jsonrpc == 1:
self.Base.create_thread(func=self.Threads.thread_subscribe, func_args=(self, ), run_once=True) self.Base.create_thread(func=self.Threads.thread_subscribe, func_args=(self, ), run_once=True)
return None return None
except Exception as err:
self.Protocol.send_priv_msg(
nick_from=self.Config.SERVICE_NICKNAME,
msg=f"[{self.Config.COLORS.red}JSONRPC ERROR{self.Config.COLORS.nogc}] {err.__str__()}",
channel=self.Config.SERVICE_CHANLOG
)
self.Logs.error(f"JSONRPC ERROR: {err.__str__()}")
def __create_tables(self) -> None: def __create_tables(self) -> None:
"""Methode qui va créer la base de donnée si elle n'existe pas. """Methode qui va créer la base de donnée si elle n'existe pas.
@@ -143,7 +124,7 @@ class Jsonrpc():
self.Base.db_execute_query(table_logs) self.Base.db_execute_query(table_logs)
return None return None
def callback_sent_to_irc(self, response: SimpleNamespace) -> None: def callback_sent_to_irc(self, response: LiveRPCResult) -> None:
dnickname = self.Config.SERVICE_NICKNAME dnickname = self.Config.SERVICE_NICKNAME
dchanlog = self.Config.SERVICE_CHANLOG dchanlog = self.Config.SERVICE_CHANLOG
@@ -152,22 +133,12 @@ class Jsonrpc():
bold = self.Config.COLORS.bold bold = self.Config.COLORS.bold
red = self.Config.COLORS.red red = self.Config.COLORS.red
if self.UnrealIrcdRpcLive.get_error.code != 0:
self.Protocol.send_priv_msg(nick_from=dnickname,
msg=f"[{bold}{red}JSONRPC ERROR{nogc}{bold}] {self.UnrealIrcdRpcLive.get_error.message}",
channel=dchanlog)
return None
if hasattr(response, 'error'):
if response.error.code != 0: if response.error.code != 0:
self.Protocol.send_priv_msg( self.Protocol.send_priv_msg(nick_from=dnickname,
nick_from=self.Config.SERVICE_NICKNAME, msg=f"[{bold}{red}JSONRPC ERROR{nogc}{bold}] {response.error.message} ({response.error.code})",
msg=f"[{bold}{red}JSONRPC{nogc}{bold}] JSONRPC Event activated on {self.Config.JSONRPC_URL}",
channel=dchanlog) channel=dchanlog)
return None return None
if hasattr(response, 'result'):
if isinstance(response.result, bool): if isinstance(response.result, bool):
if response.result: if response.result:
self.Protocol.send_priv_msg( self.Protocol.send_priv_msg(
@@ -278,18 +249,13 @@ class Jsonrpc():
match option: match option:
case 'get': case 'get':
nickname = str(cmd[2]) nickname = str(cmd[2])
uid_to_get = self.User.get_uid(nickname)
if uid_to_get is None:
return None
rpc = self.Rpc rpc = self.Rpc
UserInfo = rpc.User.get(uid_to_get) UserInfo = rpc.User.get(nickname)
if rpc.get_error.code != 0: if UserInfo.error.code != 0:
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'{rpc.get_error.message}') self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'{UserInfo.error.message}')
return None return None
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'UID : {UserInfo.id}') self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'UID : {UserInfo.id}')
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'NICKNAME : {UserInfo.name}') self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'NICKNAME : {UserInfo.name}')
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'USERNAME : {UserInfo.user.username}') self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f'USERNAME : {UserInfo.user.username}')
@@ -321,9 +287,8 @@ class Jsonrpc():
case 'jrinstances': case 'jrinstances':
try: try:
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"GC Collect: {self.MainUtils.run_python_garbage_collector()}") self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"GC Collect: {self.MainUtils.run_python_garbage_collector()}")
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"Nombre d'instance LiveWebsock: {self.MainUtils.get_number_gc_objects(LiveWebsocket)}") self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"Nombre d'instance LiveWebsock: {self.MainUtils.get_number_gc_objects(LiveConnectionFactory)}")
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"Nombre d'instance LiveUnixSocket: {self.MainUtils.get_number_gc_objects(LiveUnixSocket)}") self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"Nombre d'instance ConnectionFactory: {self.MainUtils.get_number_gc_objects(ConnectionFactory)}")
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"Nombre d'instance Loader: {self.MainUtils.get_number_gc_objects(Loader)}")
self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"Nombre de toute les instances: {self.MainUtils.get_number_gc_objects()}") self.Protocol.send_notice(nick_from=dnickname, nick_to=fromuser, msg=f"Nombre de toute les instances: {self.MainUtils.get_number_gc_objects()}")
except Exception as err: except Exception as err:
self.Logs.error(f"Unknown Error: {err}") self.Logs.error(f"Unknown Error: {err}")

View File

@@ -5,24 +5,20 @@ if TYPE_CHECKING:
from mods.jsonrpc.mod_jsonrpc import Jsonrpc from mods.jsonrpc.mod_jsonrpc import Jsonrpc
def thread_subscribe(uplink: 'Jsonrpc') -> None: def thread_subscribe(uplink: 'Jsonrpc') -> None:
response: dict[str, dict] = {}
snickname = uplink.Config.SERVICE_NICKNAME snickname = uplink.Config.SERVICE_NICKNAME
schannel = uplink.Config.SERVICE_CHANLOG schannel = uplink.Config.SERVICE_CHANLOG
if uplink.UnrealIrcdRpcLive.get_error.code == 0:
uplink.is_streaming = True uplink.is_streaming = True
response = asyncio.run(uplink.UnrealIrcdRpcLive.subscribe(["all"])) response = asyncio.run(uplink.LiveRpc.subscribe(["all"]))
else:
if response.error.code != 0:
uplink.Protocol.send_priv_msg(nick_from=snickname, uplink.Protocol.send_priv_msg(nick_from=snickname,
msg=f"[{uplink.Config.COLORS.red}JSONRPC ERROR{uplink.Config.COLORS.nogc}] {uplink.UnrealIrcdRpcLive.get_error.message}", msg=f"[{uplink.Config.COLORS.red}JSONRPC ERROR{uplink.Config.COLORS.nogc}] {response.error.message}",
channel=schannel channel=schannel
) )
if response is None: code = response.error.code
return message = response.error.message
code = response.get('error', {}).get('code', 0)
message = response.get('error', {}).get('message', None)
if code == 0: if code == 0:
uplink.Protocol.send_priv_msg( uplink.Protocol.send_priv_msg(
@@ -39,18 +35,15 @@ def thread_subscribe(uplink: 'Jsonrpc') -> None:
def thread_unsubscribe(uplink: 'Jsonrpc') -> None: def thread_unsubscribe(uplink: 'Jsonrpc') -> None:
response: dict[str, dict] = asyncio.run(uplink.UnrealIrcdRpcLive.unsubscribe()) response = asyncio.run(uplink.LiveRpc.unsubscribe())
uplink.Logs.debug("[JSONRPC UNLOAD] Unsubscribe from the stream!") uplink.Logs.debug("[JSONRPC UNLOAD] Unsubscribe from the stream!")
uplink.is_streaming = False uplink.is_streaming = False
uplink.update_configuration('jsonrpc', 0) uplink.update_configuration('jsonrpc', 0)
snickname = uplink.Config.SERVICE_NICKNAME snickname = uplink.Config.SERVICE_NICKNAME
schannel = uplink.Config.SERVICE_CHANLOG schannel = uplink.Config.SERVICE_CHANLOG
if response is None: code = response.error.code
return None message = response.error.message
code = response.get('error', {}).get('code', 0)
message = response.get('error', {}).get('message', None)
if code != 0: if code != 0:
uplink.Protocol.send_priv_msg( uplink.Protocol.send_priv_msg(