mirror of
https://github.com/iio612/DEFENDER.git
synced 2026-02-13 19:24:23 +00:00
First Version 6
This commit is contained in:
127
core/classes/admin.py
Normal file
127
core/classes/admin.py
Normal file
@@ -0,0 +1,127 @@
|
||||
from typing import Union
|
||||
import core.definition as df
|
||||
from core.base import Base
|
||||
|
||||
|
||||
class Admin:
|
||||
|
||||
UID_ADMIN_DB: list[df.MAdmin] = []
|
||||
|
||||
def __init__(self, baseObj: Base) -> None:
|
||||
self.Logs = baseObj.logs
|
||||
pass
|
||||
|
||||
def insert(self, newAdmin: df.MAdmin) -> bool:
|
||||
|
||||
result = False
|
||||
exist = False
|
||||
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == newAdmin.uid:
|
||||
# If the admin exist then return False and do not go further
|
||||
exist = True
|
||||
self.Logs.debug(f'{record.uid} already exist')
|
||||
return result
|
||||
|
||||
if not exist:
|
||||
self.UID_ADMIN_DB.append(newAdmin)
|
||||
result = True
|
||||
self.Logs.debug(f'UID ({newAdmin.uid}) has been created')
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The User Object was not inserted {newAdmin}')
|
||||
|
||||
return result
|
||||
|
||||
def update_nickname(self, uid: str, newNickname: str) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == uid:
|
||||
# If the admin exist, update and do not go further
|
||||
record.nickname = newNickname
|
||||
result = True
|
||||
self.Logs.debug(f'UID ({record.uid}) has been updated with new nickname {newNickname}')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The new nickname {newNickname} was not updated, uid = {uid}')
|
||||
|
||||
return result
|
||||
|
||||
def update_level(self, nickname: str, newLevel: int) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.nickname == nickname:
|
||||
# If the admin exist, update and do not go further
|
||||
record.level = newLevel
|
||||
result = True
|
||||
self.Logs.debug(f'Admin ({record.nickname}) has been updated with new level {newLevel}')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The new level {newLevel} was not updated, nickname = {nickname}')
|
||||
|
||||
return result
|
||||
|
||||
def delete(self, uidornickname: str) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == uidornickname:
|
||||
# If the admin exist, delete and do not go further
|
||||
self.UID_ADMIN_DB.remove(record)
|
||||
result = True
|
||||
self.Logs.debug(f'UID ({record.uid}) has been deleted')
|
||||
return result
|
||||
if record.nickname == uidornickname:
|
||||
# If the admin exist, delete and do not go further
|
||||
self.UID_ADMIN_DB.remove(record)
|
||||
result = True
|
||||
self.Logs.debug(f'nickname ({record.nickname}) has been deleted')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The UID {uidornickname} was not deleted')
|
||||
|
||||
return result
|
||||
|
||||
def get_Admin(self, uidornickname: str) -> Union[df.MAdmin, None]:
|
||||
|
||||
Admin = None
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == uidornickname:
|
||||
Admin = record
|
||||
elif record.nickname == uidornickname:
|
||||
Admin = record
|
||||
|
||||
#self.Logs.debug(f'Search {uidornickname} -- result = {Admin}')
|
||||
|
||||
return Admin
|
||||
|
||||
def get_uid(self, uidornickname:str) -> Union[str, None]:
|
||||
|
||||
uid = None
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == uidornickname:
|
||||
uid = record.uid
|
||||
if record.nickname == uidornickname:
|
||||
uid = record.uid
|
||||
|
||||
self.Logs.debug(f'The UID that you are looking for {uidornickname} has been found {uid}')
|
||||
return uid
|
||||
|
||||
def get_nickname(self, uidornickname:str) -> Union[str, None]:
|
||||
|
||||
nickname = None
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.nickname == uidornickname:
|
||||
nickname = record.nickname
|
||||
if record.uid == uidornickname:
|
||||
nickname = record.nickname
|
||||
self.Logs.debug(f'The value {uidornickname} -- {nickname}')
|
||||
return nickname
|
||||
225
core/classes/channel.py
Normal file
225
core/classes/channel.py
Normal file
@@ -0,0 +1,225 @@
|
||||
from re import findall
|
||||
from typing import Union, Literal, TYPE_CHECKING
|
||||
from dataclasses import asdict
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.definition import MChannel
|
||||
from core.base import Base
|
||||
|
||||
class Channel:
|
||||
|
||||
UID_CHANNEL_DB: list['MChannel'] = []
|
||||
"""List that contains all the Channels objects (ChannelModel)
|
||||
"""
|
||||
|
||||
def __init__(self, baseObj: 'Base') -> None:
|
||||
|
||||
self.Logs = baseObj.logs
|
||||
self.Base = baseObj
|
||||
|
||||
return None
|
||||
|
||||
def insert(self, newChan: 'MChannel') -> bool:
|
||||
"""This method will insert a new channel and if the channel exist it will update the user list (uids)
|
||||
|
||||
Args:
|
||||
newChan (ChannelModel): The channel model object
|
||||
|
||||
Returns:
|
||||
bool: True if new channel, False if channel exist (However UID could be updated)
|
||||
"""
|
||||
result = False
|
||||
exist = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name.lower() == newChan.name.lower():
|
||||
# If the channel exist, update the user list and do not go further
|
||||
exist = True
|
||||
# self.Logs.debug(f'{record.name} already exist')
|
||||
|
||||
for user in newChan.uids:
|
||||
record.uids.append(user)
|
||||
|
||||
# Supprimer les doublons
|
||||
del_duplicates = list(set(record.uids))
|
||||
record.uids = del_duplicates
|
||||
# self.Logs.debug(f'Updating a new UID to the channel {record}')
|
||||
return result
|
||||
|
||||
if not exist:
|
||||
# If the channel don't exist, then create it
|
||||
newChan.name = newChan.name.lower()
|
||||
self.UID_CHANNEL_DB.append(newChan)
|
||||
result = True
|
||||
# self.Logs.debug(f'New Channel Created: ({newChan})')
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The Channel Object was not inserted {newChan}')
|
||||
|
||||
self.clean_channel()
|
||||
|
||||
return result
|
||||
|
||||
def delete(self, name: str) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name == name:
|
||||
# If the channel exist, then remove it and return True.
|
||||
# As soon as the channel found, return True and stop the loop
|
||||
self.UID_CHANNEL_DB.remove(record)
|
||||
result = True
|
||||
# self.Logs.debug(f'Channel ({record.name}) has been created')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The Channel {name} was not deleted')
|
||||
|
||||
return result
|
||||
|
||||
def delete_user_from_channel(self, chan_name: str, uid:str) -> bool:
|
||||
try:
|
||||
result = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name == chan_name:
|
||||
for user_id in record.uids:
|
||||
if self.Base.clean_uid(user_id) == uid:
|
||||
record.uids.remove(user_id)
|
||||
# self.Logs.debug(f'The UID {uid} has been removed, here is the new object: {record}')
|
||||
result = True
|
||||
|
||||
self.clean_channel()
|
||||
|
||||
return result
|
||||
except ValueError as ve:
|
||||
self.Logs.error(f'{ve}')
|
||||
|
||||
def delete_user_from_all_channel(self, uid:str) -> bool:
|
||||
try:
|
||||
result = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
for user_id in record.uids:
|
||||
if self.Base.clean_uid(user_id) == self.Base.clean_uid(uid):
|
||||
record.uids.remove(user_id)
|
||||
# self.Logs.debug(f'The UID {uid} has been removed, here is the new object: {record}')
|
||||
result = True
|
||||
|
||||
self.clean_channel()
|
||||
|
||||
return result
|
||||
except ValueError as ve:
|
||||
self.Logs.error(f'{ve}')
|
||||
|
||||
def clean_channel(self) -> None:
|
||||
"""Remove Channels if empty
|
||||
"""
|
||||
try:
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if not record.uids:
|
||||
self.UID_CHANNEL_DB.remove(record)
|
||||
# self.Logs.debug(f'The Channel {record.name} has been removed, here is the new object: {record}')
|
||||
return None
|
||||
except Exception as err:
|
||||
self.Logs.error(f'{err}')
|
||||
|
||||
def get_Channel(self, name: str) -> Union['MChannel', None]:
|
||||
|
||||
Channel = None
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name == name:
|
||||
Channel = record
|
||||
|
||||
# self.Logs.debug(f'Search {name} -- result = {Channel}')
|
||||
|
||||
return Channel
|
||||
|
||||
def get_Channel_AsDict(self, chan_name: str) -> Union[dict[str, any], None]:
|
||||
|
||||
chanObj = self.get_Channel(chan_name=chan_name)
|
||||
|
||||
if not chanObj is None:
|
||||
chan_as_dict = asdict(chanObj)
|
||||
return chan_as_dict
|
||||
else:
|
||||
return None
|
||||
|
||||
def Is_Channel(self, channelToCheck: str) -> bool:
|
||||
"""Check if the string has the # caractere and return True if this is a channel
|
||||
|
||||
Args:
|
||||
channelToCheck (str): The string to test if it is a channel or not
|
||||
|
||||
Returns:
|
||||
bool: True if the string is a channel / False if this is not a channel
|
||||
"""
|
||||
try:
|
||||
|
||||
if channelToCheck is None:
|
||||
return False
|
||||
|
||||
pattern = fr'^#'
|
||||
isChannel = findall(pattern, channelToCheck)
|
||||
|
||||
if not isChannel:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
except TypeError as te:
|
||||
self.logs.error(f'TypeError: [{channelToCheck}] - {te}')
|
||||
except Exception as err:
|
||||
self.logs.error(f'Error Not defined: {err}')
|
||||
|
||||
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.
|
||||
|
||||
Args:
|
||||
action (Literal['add','del']): Action on the database
|
||||
module_name (str): The module name (mod_test)
|
||||
channel_name (str): The channel name (With #)
|
||||
|
||||
Returns:
|
||||
bool: True if action done
|
||||
"""
|
||||
try:
|
||||
channel_name = channel_name.lower() if self.Is_Channel(channel_name) else None
|
||||
core_table = self.Base.Config.TABLE_CHANNEL
|
||||
|
||||
if not channel_name:
|
||||
self.Logs.warning(f'The channel [{channel_name}] is not correct')
|
||||
return False
|
||||
|
||||
match action:
|
||||
|
||||
case 'add':
|
||||
mes_donnees = {'module_name': module_name, 'channel_name': channel_name}
|
||||
response = self.Base.db_execute_query(f"SELECT id FROM {core_table} WHERE module_name = :module_name AND channel_name = :channel_name", mes_donnees)
|
||||
isChannelExist = response.fetchone()
|
||||
|
||||
if isChannelExist is None:
|
||||
mes_donnees = {'datetime': self.Base.get_datetime(), 'channel_name': channel_name, 'module_name': module_name}
|
||||
insert = self.Base.db_execute_query(f"INSERT INTO {core_table} (datetime, channel_name, module_name) VALUES (:datetime, :channel_name, :module_name)", mes_donnees)
|
||||
if insert.rowcount:
|
||||
self.Logs.debug(f'New channel added: channel={channel_name} / module_name={module_name}')
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
case 'del':
|
||||
mes_donnes = {'channel_name': channel_name, 'module_name': module_name}
|
||||
response = self.Base.db_execute_query(f"DELETE FROM {core_table} WHERE channel_name = :channel_name AND module_name = :module_name", mes_donnes)
|
||||
|
||||
if response.rowcount > 0:
|
||||
self.Logs.debug(f'Channel deleted: channel={channel_name} / module: {module_name}')
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
case _:
|
||||
return False
|
||||
|
||||
except Exception as err:
|
||||
self.Logs.error(err)
|
||||
|
||||
162
core/classes/clone.py
Normal file
162
core/classes/clone.py
Normal file
@@ -0,0 +1,162 @@
|
||||
from dataclasses import asdict
|
||||
from core.definition import MClone
|
||||
from typing import Union
|
||||
from core.base import Base
|
||||
|
||||
class Clone:
|
||||
|
||||
UID_CLONE_DB: list[MClone] = []
|
||||
|
||||
def __init__(self, baseObj: Base) -> None:
|
||||
|
||||
self.Logs = baseObj.logs
|
||||
|
||||
return None
|
||||
|
||||
def insert(self, newCloneObject: MClone) -> bool:
|
||||
"""Create new Clone object
|
||||
|
||||
Args:
|
||||
newCloneObject (CloneModel): New CloneModel object
|
||||
|
||||
Returns:
|
||||
bool: True if inserted
|
||||
"""
|
||||
result = False
|
||||
exist = False
|
||||
|
||||
for record in self.UID_CLONE_DB:
|
||||
if record.nickname == newCloneObject.nickname:
|
||||
# If the user exist then return False and do not go further
|
||||
exist = True
|
||||
self.Logs.warning(f'Nickname {record.nickname} already exist')
|
||||
return result
|
||||
if record.uid == newCloneObject.uid:
|
||||
exist = True
|
||||
self.Logs.warning(f'UID: {record.uid} already exist')
|
||||
return result
|
||||
|
||||
if not exist:
|
||||
self.UID_CLONE_DB.append(newCloneObject)
|
||||
result = True
|
||||
# self.Logs.debug(f'New Clone Object Created: ({newCloneObject})')
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The Clone Object was not inserted {newCloneObject}')
|
||||
|
||||
return result
|
||||
|
||||
def delete(self, uidornickname: str) -> bool:
|
||||
"""Delete the Clone Object starting from the nickname or the UID
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or nickname of the clone
|
||||
|
||||
Returns:
|
||||
bool: True if deleted
|
||||
"""
|
||||
result = False
|
||||
|
||||
for record in self.UID_CLONE_DB:
|
||||
if record.nickname == uidornickname or record.uid == uidornickname:
|
||||
# If the user exist then remove and return True and do not go further
|
||||
self.UID_CLONE_DB.remove(record)
|
||||
result = True
|
||||
# self.Logs.debug(f'The clone ({record.nickname}) has been deleted')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The UID or Nickname {uidornickname} was not deleted')
|
||||
|
||||
return result
|
||||
|
||||
def exists(self, nickname: str) -> bool:
|
||||
"""Check if the nickname exist
|
||||
|
||||
Args:
|
||||
nickname (str): Nickname of the clone
|
||||
|
||||
Returns:
|
||||
bool: True if the nickname exist
|
||||
"""
|
||||
response = False
|
||||
|
||||
for cloneObject in self.UID_CLONE_DB:
|
||||
if cloneObject.nickname == nickname:
|
||||
response = True
|
||||
|
||||
return response
|
||||
|
||||
def uid_exists(self, uid: str) -> bool:
|
||||
"""Check if the nickname exist
|
||||
|
||||
Args:
|
||||
uid (str): uid of the clone
|
||||
|
||||
Returns:
|
||||
bool: True if the nickname exist
|
||||
"""
|
||||
response = False
|
||||
|
||||
for cloneObject in self.UID_CLONE_DB:
|
||||
if cloneObject.uid == uid:
|
||||
response = True
|
||||
|
||||
return response
|
||||
|
||||
def get_Clone(self, uidornickname: str) -> Union[MClone, None]:
|
||||
"""Get MClone object or None
|
||||
|
||||
Args:
|
||||
uidornickname (str): The UID or the Nickname
|
||||
|
||||
Returns:
|
||||
Union[MClone, None]: Return MClone object or None
|
||||
"""
|
||||
for clone in self.UID_CLONE_DB:
|
||||
if clone.uid == uidornickname:
|
||||
return clone
|
||||
if clone.nickname == uidornickname:
|
||||
return clone
|
||||
|
||||
def get_uid(self, uidornickname: str) -> Union[str, None]:
|
||||
"""Get the UID of the clone starting from the UID or the Nickname
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or Nickname
|
||||
|
||||
Returns:
|
||||
str|None: Return the UID
|
||||
"""
|
||||
uid = None
|
||||
for record in self.UID_CLONE_DB:
|
||||
if record.uid == uidornickname:
|
||||
uid = record.uid
|
||||
if record.nickname == uidornickname:
|
||||
uid = record.uid
|
||||
|
||||
# if not uid is None:
|
||||
# self.Logs.debug(f'The UID that you are looking for {uidornickname} has been found {uid}')
|
||||
|
||||
return uid
|
||||
|
||||
def get_Clone_AsDict(self, uidornickname: str) -> Union[dict[str, any], None]:
|
||||
|
||||
cloneObj = self.get_Clone(uidornickname=uidornickname)
|
||||
|
||||
if not cloneObj is None:
|
||||
cloneObj_as_dict = asdict(cloneObj)
|
||||
return cloneObj_as_dict
|
||||
else:
|
||||
return None
|
||||
|
||||
def kill(self, nickname:str) -> bool:
|
||||
|
||||
response = False
|
||||
|
||||
for cloneObject in self.UID_CLONE_DB:
|
||||
if cloneObject.nickname == nickname:
|
||||
cloneObject.alive = False # Kill the clone
|
||||
response = True
|
||||
|
||||
return response
|
||||
57
core/classes/config.py
Normal file
57
core/classes/config.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from json import load
|
||||
from sys import exit
|
||||
from os import sep
|
||||
from typing import Union
|
||||
from core.definition import MConfig
|
||||
|
||||
|
||||
|
||||
class Configuration:
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
self.ConfigObject: MConfig = self.__load_service_configuration()
|
||||
return None
|
||||
|
||||
def __load_json_service_configuration(self):
|
||||
try:
|
||||
conf_filename = f'config{sep}configuration.json'
|
||||
with open(conf_filename, 'r') as configuration_data:
|
||||
configuration:dict[str, Union[str, int, list, dict]] = load(configuration_data)
|
||||
|
||||
return configuration
|
||||
|
||||
except FileNotFoundError as fe:
|
||||
print(f'FileNotFound: {fe}')
|
||||
print('Configuration file not found please create config/configuration.json')
|
||||
exit(0)
|
||||
except KeyError as ke:
|
||||
print(f'Key Error: {ke}')
|
||||
print('The key must be defined in core/configuration.json')
|
||||
|
||||
def __load_service_configuration(self) -> MConfig:
|
||||
try:
|
||||
import_config = self.__load_json_service_configuration()
|
||||
|
||||
Model_keys = MConfig().__dict__
|
||||
model_key_list: list = []
|
||||
json_config_key_list: list = []
|
||||
|
||||
for key in Model_keys:
|
||||
model_key_list.append(key)
|
||||
|
||||
for key in import_config:
|
||||
json_config_key_list.append(key)
|
||||
|
||||
for json_conf in json_config_key_list:
|
||||
if not json_conf in model_key_list:
|
||||
import_config.pop(json_conf, None)
|
||||
print(f"\!/ The key {json_conf} is not expected, it has been removed from the system ! please remove it from configuration.json file \!/")
|
||||
|
||||
ConfigObject: MConfig = MConfig(
|
||||
**import_config
|
||||
)
|
||||
|
||||
return ConfigObject
|
||||
except TypeError as te:
|
||||
print(te)
|
||||
15
core/classes/protocol.py
Normal file
15
core/classes/protocol.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from typing import Literal, TYPE_CHECKING
|
||||
from .protocols.unreal6 import Unrealircd6
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.irc import Irc
|
||||
|
||||
class Protocol:
|
||||
|
||||
def __init__(self, protocol: Literal['unreal6'], ircInstance: 'Irc'):
|
||||
|
||||
self.Protocol = None
|
||||
if protocol == 'unreal6':
|
||||
self.Protocol: Unrealircd6 = Unrealircd6(ircInstance)
|
||||
else:
|
||||
self.Protocol = None
|
||||
336
core/classes/protocols/unreal6.py
Normal file
336
core/classes/protocols/unreal6.py
Normal file
@@ -0,0 +1,336 @@
|
||||
from typing import TYPE_CHECKING
|
||||
from ssl import SSLEOFError, SSLError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.irc import Irc
|
||||
|
||||
class Unrealircd6:
|
||||
|
||||
def __init__(self, ircInstance: 'Irc'):
|
||||
self.__Irc = ircInstance
|
||||
self.__Config = ircInstance.Config
|
||||
self.__Base = ircInstance.Base
|
||||
|
||||
def send2socket(self, message: str, print_log: bool = True) -> None:
|
||||
"""Envoit les commandes à envoyer au serveur.
|
||||
|
||||
Args:
|
||||
string (Str): contient la commande à envoyer au serveur.
|
||||
"""
|
||||
try:
|
||||
with self.__Base.lock:
|
||||
self.__Irc.IrcSocket.send(f"{message}\r\n".encode(self.__Config.SERVEUR_CHARSET[0]))
|
||||
if print_log:
|
||||
self.__Base.logs.debug(f'<< {message}')
|
||||
|
||||
except UnicodeDecodeError:
|
||||
self.__Base.logs.error(f'Decode Error try iso-8859-1 - message: {message}')
|
||||
self.__Irc.IrcSocket.send(f"{message}\r\n".encode(self.__Config.SERVEUR_CHARSET[0],'replace'))
|
||||
except UnicodeEncodeError:
|
||||
self.__Base.logs.error(f'Encode Error try iso-8859-1 - message: {message}')
|
||||
self.__Irc.IrcSocket.send(f"{message}\r\n".encode(self.__Config.SERVEUR_CHARSET[0],'replace'))
|
||||
except AssertionError as ae:
|
||||
self.__Base.logs.warning(f'Assertion Error {ae} - message: {message}')
|
||||
except SSLEOFError as soe:
|
||||
self.__Base.logs.error(f"SSLEOFError: {soe} - {message}")
|
||||
except SSLError as se:
|
||||
self.__Base.logs.error(f"SSLError: {se} - {message}")
|
||||
except OSError as oe:
|
||||
self.__Base.logs.error(f"OSError: {oe} - {message}")
|
||||
except AttributeError as ae:
|
||||
self.__Base.logs.critical(f"Attribute Error: {ae}")
|
||||
|
||||
def sendPrivMsg(self, nick_from: str, msg: str, channel: str = None, nick_to: str = None):
|
||||
"""Sending PRIVMSG to a channel or to a nickname by batches
|
||||
could be either channel or nickname not both together
|
||||
Args:
|
||||
msg (str): The message to send
|
||||
nick_from (str): The sender nickname
|
||||
channel (str, optional): The receiver channel. Defaults to None.
|
||||
nick_to (str, optional): The reciever nickname. Defaults to None.
|
||||
"""
|
||||
try:
|
||||
batch_size = self.__Config.BATCH_SIZE
|
||||
User_from = self.__Irc.User.get_User(nick_from)
|
||||
User_to = self.__Irc.User.get_User(nick_to) if nick_to is None else None
|
||||
|
||||
if User_from is None:
|
||||
self.__Base.logs.error(f"The sender nickname [{nick_from}] do not exist")
|
||||
return None
|
||||
|
||||
if not channel is None:
|
||||
for i in range(0, len(str(msg)), batch_size):
|
||||
batch = str(msg)[i:i+batch_size]
|
||||
self.send2socket(f":{User_from.uid} PRIVMSG {channel} :{batch}")
|
||||
|
||||
if not nick_to is None:
|
||||
for i in range(0, len(str(msg)), batch_size):
|
||||
batch = str(msg)[i:i+batch_size]
|
||||
self.send2socket(f":{nick_from} PRIVMSG {User_to.uid} :{batch}")
|
||||
except Exception as err:
|
||||
self.__Base.logs.error(f"General Error: {err}")
|
||||
|
||||
def sendNotice(self, nick_from: str, nick_to: str, msg: str) -> None:
|
||||
"""Sending NOTICE by batches
|
||||
|
||||
Args:
|
||||
msg (str): The message to send to the server
|
||||
nick_from (str): The sender Nickname
|
||||
nick_to (str): The reciever nickname
|
||||
"""
|
||||
try:
|
||||
batch_size = self.__Config.BATCH_SIZE
|
||||
User_from = self.__Irc.User.get_User(nick_from)
|
||||
User_to = self.__Irc.User.get_User(nick_to)
|
||||
|
||||
if User_from is None or User_to is None:
|
||||
self.__Base.logs.error(f"The sender [{nick_from}] or the Reciever [{nick_to}] do not exist")
|
||||
return None
|
||||
|
||||
for i in range(0, len(str(msg)), batch_size):
|
||||
batch = str(msg)[i:i+batch_size]
|
||||
self.send2socket(f":{User_from.uid} NOTICE {User_to.uid} :{batch}")
|
||||
|
||||
except Exception as err:
|
||||
self.__Base.logs.error(f"General Error: {err}")
|
||||
|
||||
def link(self):
|
||||
"""Créer le link et envoyer les informations nécessaires pour la
|
||||
connexion au serveur.
|
||||
"""
|
||||
|
||||
nickname = self.__Config.SERVICE_NICKNAME
|
||||
username = self.__Config.SERVICE_USERNAME
|
||||
realname = self.__Config.SERVICE_REALNAME
|
||||
chan = self.__Config.SERVICE_CHANLOG
|
||||
info = self.__Config.SERVICE_INFO
|
||||
smodes = self.__Config.SERVICE_SMODES
|
||||
cmodes = self.__Config.SERVICE_CMODES
|
||||
umodes = self.__Config.SERVICE_UMODES
|
||||
host = self.__Config.SERVICE_HOST
|
||||
service_name = self.__Config.SERVICE_NAME
|
||||
|
||||
password = self.__Config.SERVEUR_PASSWORD
|
||||
link = self.__Config.SERVEUR_LINK
|
||||
server_id = self.__Config.SERVEUR_ID
|
||||
service_id = self.__Config.SERVICE_ID
|
||||
|
||||
version = self.__Config.CURRENT_VERSION
|
||||
unixtime = self.__Base.get_unixtime()
|
||||
|
||||
self.send2socket(f":{server_id} PASS :{password}")
|
||||
self.send2socket(f":{server_id} PROTOCTL SID NOQUIT NICKv2 SJOIN SJ3 NICKIP TKLEXT2 NEXTBANS CLK EXTSWHOIS MLOCK MTAGS")
|
||||
# self.__Irc.send2socket(f":{sid} PROTOCTL NICKv2 VHP UMODE2 NICKIP SJOIN SJOIN2 SJ3 NOQUIT TKLEXT MLOCK SID MTAGS")
|
||||
self.send2socket(f":{server_id} PROTOCTL EAUTH={link},,,{service_name}-v{version}")
|
||||
self.send2socket(f":{server_id} PROTOCTL SID={server_id}")
|
||||
self.send2socket(f":{server_id} SERVER {link} 1 :{info}")
|
||||
self.send2socket(f":{server_id} {nickname} :Reserved for services")
|
||||
#self.__Irc.send2socket(f":{sid} UID {nickname} 1 {unixtime} {username} {host} {service_id} * {smodes} * * * :{realname}")
|
||||
self.send2socket(f":{server_id} UID {nickname} 1 {unixtime} {username} {host} {service_id} * {smodes} * * fwAAAQ== :{realname}")
|
||||
# self.__Irc.send2socket(f":{server_id} SJOIN {unixtime} {chan} + :{service_id}")
|
||||
self.sjoin(chan)
|
||||
self.send2socket(f":{server_id} TKL + Q * {nickname} {host} 0 {unixtime} :Reserved for services")
|
||||
|
||||
self.send2socket(f":{service_id} MODE {chan} {cmodes}")
|
||||
self.send2socket(f":{service_id} MODE {chan} {umodes} {service_id}")
|
||||
|
||||
self.__Base.logs.debug(f'>> {__name__} Link information sent to the server')
|
||||
|
||||
def gline(self, nickname: str, hostname: str, set_by: str, expire_timestamp: int, set_at_timestamp: int, reason: str) -> None:
|
||||
# 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}")
|
||||
|
||||
return None
|
||||
|
||||
def set_nick(self, newnickname: str) -> None:
|
||||
|
||||
self.send2socket(f":{self.__Config.SERVICE_NICKNAME} NICK {newnickname}")
|
||||
return None
|
||||
|
||||
def squit(self, server_id: str, server_link: str, reason: str) -> None:
|
||||
|
||||
self.send2socket(f":{server_id} SQUIT {server_link} :{reason}")
|
||||
return None
|
||||
|
||||
def ungline(self, nickname:str, hostname: str) -> None:
|
||||
|
||||
self.send2socket(f":{self.__Config.SERVEUR_ID} TKL - G {nickname} {hostname} {self.__Config.SERVICE_NICKNAME}")
|
||||
|
||||
return None
|
||||
|
||||
def kline(self, nickname: str, hostname: str, set_by: str, expire_timestamp: int, set_at_timestamp: int, reason: str) -> None:
|
||||
# TKL + k user host set_by expire_timestamp set_at_timestamp :reason
|
||||
|
||||
self.send2socket(f":{self.__Config.SERVEUR_ID} TKL + k {nickname} {hostname} {set_by} {expire_timestamp} {set_at_timestamp} :{reason}")
|
||||
|
||||
return None
|
||||
|
||||
def sjoin(self, channel: str) -> None:
|
||||
|
||||
self.send2socket(f":{self.__Config.SERVEUR_ID} SJOIN {self.__Base.get_unixtime()} {channel} + :{self.__Config.SERVICE_ID}")
|
||||
|
||||
# Add defender to the channel uids list
|
||||
self.__Irc.Channel.insert(self.__Irc.Loader.Definition.MChannel(name=channel, uids=[self.__Config.SERVICE_ID]))
|
||||
return None
|
||||
|
||||
def join(self, uidornickname: str, channel: str, password: str = None, print_log: bool = True) -> None:
|
||||
"""Joining a channel
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or nickname that need to join
|
||||
channel (str): channel to join
|
||||
password (str, optional): The password of the channel to join. Default to None
|
||||
print_log (bool, optional): Write logs. Defaults to True.
|
||||
"""
|
||||
|
||||
userObj = self.__Irc.User.get_User(uidornickname)
|
||||
passwordChannel = password if not password is None else ''
|
||||
|
||||
if userObj is None:
|
||||
return None
|
||||
|
||||
if not self.__Irc.Channel.Is_Channel(channel):
|
||||
return None
|
||||
|
||||
self.send2socket(f":{userObj.uid} JOIN {channel} {passwordChannel}", print_log=print_log)
|
||||
|
||||
# Add defender to the channel uids list
|
||||
self.__Irc.Channel.insert(self.__Irc.Loader.Definition.MChannel(name=channel, uids=[userObj.uid]))
|
||||
return None
|
||||
|
||||
def part(self, uidornickname:str, channel: str, print_log: bool = True) -> None:
|
||||
"""Part from a channel
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or nickname that need to join
|
||||
channel (str): channel to join
|
||||
print_log (bool, optional): Write logs. Defaults to True.
|
||||
"""
|
||||
|
||||
userObj = self.__Irc.User.get_User(uidornickname)
|
||||
|
||||
if userObj is None:
|
||||
return None
|
||||
|
||||
if not self.__Irc.Channel.Is_Channel(channel):
|
||||
return None
|
||||
|
||||
self.send2socket(f":{userObj.uid} PART {channel}", print_log=print_log)
|
||||
|
||||
# Add defender to the channel uids list
|
||||
self.__Irc.Channel.delete_user_from_channel(channel, userObj.uid)
|
||||
return None
|
||||
|
||||
def unkline(self, nickname:str, hostname: str) -> None:
|
||||
|
||||
self.send2socket(f":{self.__Config.SERVEUR_ID} TKL - K {nickname} {hostname} {self.__Config.SERVICE_NICKNAME}")
|
||||
|
||||
return None
|
||||
|
||||
def on_server_ping(self, serverMsg: list[str]) -> None:
|
||||
"""Send a PONG message to the server
|
||||
|
||||
Args:
|
||||
serverMsg (list[str]): List of str coming from the server
|
||||
"""
|
||||
try:
|
||||
|
||||
pong = str(serverMsg[1]).replace(':','')
|
||||
self.send2socket(f"PONG :{pong}", print_log=False)
|
||||
|
||||
return None
|
||||
except Exception as err:
|
||||
self.__Base.logs.error(f"{__name__} - General Error: {err}")
|
||||
|
||||
def on_version(self, serverMsg: list[str]) -> None:
|
||||
"""Sending Server Version to the server
|
||||
|
||||
Args:
|
||||
serverMsg (list[str]): List of str coming from the server
|
||||
"""
|
||||
# ['@unrealircd.org/userhost=StatServ@stats.deb.biz.st;draft/bot;bot;msgid=ehfAq3m2yjMjhgWEfi1UCS;time=2024-10-26T13:49:06.299Z', ':00BAAAAAI', 'PRIVMSG', '12ZAAAAAB', ':\x01VERSION\x01']
|
||||
# Réponse a un CTCP VERSION
|
||||
try:
|
||||
|
||||
nickname = self.__Irc.User.get_nickname(self.__Base.clean_uid(serverMsg[1]))
|
||||
dnickname = self.__Config.SERVICE_NICKNAME
|
||||
arg = serverMsg[4].replace(':', '')
|
||||
|
||||
if nickname is None:
|
||||
return None
|
||||
|
||||
if arg == '\x01VERSION\x01':
|
||||
self.send2socket(f':{dnickname} NOTICE {nickname} :\x01VERSION Service {self.__Config.SERVICE_NICKNAME} V{self.__Config.CURRENT_VERSION}\x01')
|
||||
|
||||
return None
|
||||
except Exception as err:
|
||||
self.__Base.logs.error(f"{__name__} - General Error: {err}")
|
||||
|
||||
def on_time(self, serverMsg: list[str]) -> None:
|
||||
"""Sending TIME answer to a requestor
|
||||
|
||||
Args:
|
||||
serverMsg (list[str]): List of str coming from the server
|
||||
"""
|
||||
# ['@unrealircd.org/userhost=StatServ@stats.deb.biz.st;draft/bot;bot;msgid=ehfAq3m2yjMjhgWEfi1UCS;time=2024-10-26T13:49:06.299Z', ':00BAAAAAI', 'PRIVMSG', '12ZAAAAAB', ':\x01TIME\x01']
|
||||
# Réponse a un CTCP VERSION
|
||||
try:
|
||||
|
||||
nickname = self.__Irc.User.get_nickname(self.__Base.clean_uid(serverMsg[1]))
|
||||
dnickname = self.__Config.SERVICE_NICKNAME
|
||||
arg = serverMsg[4].replace(':', '')
|
||||
current_datetime = self.__Base.get_datetime()
|
||||
|
||||
if nickname is None:
|
||||
return None
|
||||
|
||||
if arg == '\x01TIME\x01':
|
||||
self.send2socket(f':{dnickname} NOTICE {nickname} :\x01TIME {current_datetime}\x01')
|
||||
|
||||
return None
|
||||
except Exception as err:
|
||||
self.__Base.logs.error(f"{__name__} - General Error: {err}")
|
||||
|
||||
def on_ping(self, serverMsg: list[str]) -> None:
|
||||
"""Sending a PING answer to requestor
|
||||
|
||||
Args:
|
||||
serverMsg (list[str]): List of str coming from the server
|
||||
"""
|
||||
# ['@unrealircd.org/userhost=StatServ@stats.deb.biz.st;draft/bot;bot;msgid=ehfAq3m2yjMjhgWEfi1UCS;time=2024-10-26T13:49:06.299Z', ':001INC60B', 'PRIVMSG', '12ZAAAAAB', ':\x01PING', '762382207\x01']
|
||||
# Réponse a un CTCP VERSION
|
||||
try:
|
||||
|
||||
nickname = self.__Irc.User.get_nickname(self.__Base.clean_uid(serverMsg[1]))
|
||||
dnickname = self.__Config.SERVICE_NICKNAME
|
||||
arg = serverMsg[4].replace(':', '')
|
||||
|
||||
if nickname is None:
|
||||
return None
|
||||
|
||||
if arg == '\x01PING':
|
||||
recieved_unixtime = int(serverMsg[5].replace('\x01',''))
|
||||
current_unixtime = self.__Base.get_unixtime()
|
||||
ping_response = current_unixtime - recieved_unixtime
|
||||
|
||||
# self.__Irc.send2socket(f':{dnickname} NOTICE {nickname} :\x01PING {ping_response} secs\x01')
|
||||
self.sendNotice(
|
||||
nick_from=dnickname,
|
||||
nick_to=nickname,
|
||||
msg=f"\x01PING {ping_response} secs\x01"
|
||||
)
|
||||
|
||||
return None
|
||||
except Exception as err:
|
||||
self.__Base.logs.error(f"{__name__} - General Error: {err}")
|
||||
|
||||
def on_version_msg(self, serverMsg: list[str]) -> None:
|
||||
|
||||
# ['@label=0073', ':0014E7P06', 'VERSION', 'PyDefender']
|
||||
getUser = self.__Irc.User.get_User(self.__Irc.User.clean_uid(serverMsg[1]))
|
||||
|
||||
if getUser is None:
|
||||
return None
|
||||
|
||||
self.send2socket(f'{self.__Config.SERVEUR_ID} 351 {getUser.nickname} {self.__Config.CURRENT_VERSION} {self.__Config.SERVICE_NAME} *:')
|
||||
175
core/classes/reputation.py
Normal file
175
core/classes/reputation.py
Normal file
@@ -0,0 +1,175 @@
|
||||
from typing import Union
|
||||
from core.definition import MReputation
|
||||
from core.base import Base
|
||||
|
||||
class Reputation:
|
||||
|
||||
UID_REPUTATION_DB: list[MReputation] = []
|
||||
|
||||
def __init__(self, baseObj: Base) -> None:
|
||||
|
||||
self.Logs = baseObj.logs
|
||||
self.MReputation: MReputation = MReputation
|
||||
|
||||
return None
|
||||
|
||||
def insert(self, newReputationUser: MReputation) -> bool:
|
||||
"""Insert a new Reputation User object
|
||||
|
||||
Args:
|
||||
newReputationUser (MReputation): New Reputation Model object
|
||||
|
||||
Returns:
|
||||
bool: True if inserted
|
||||
"""
|
||||
result = False
|
||||
exist = False
|
||||
|
||||
for record in self.UID_REPUTATION_DB:
|
||||
if record.uid == newReputationUser.uid:
|
||||
# If the user exist then return False and do not go further
|
||||
exist = True
|
||||
self.Logs.debug(f'{record.uid} already exist')
|
||||
return result
|
||||
|
||||
if not exist:
|
||||
self.UID_REPUTATION_DB.append(newReputationUser)
|
||||
result = True
|
||||
self.Logs.debug(f'New Reputation User Captured: ({newReputationUser})')
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The Reputation User Object was not inserted {newReputationUser}')
|
||||
|
||||
return result
|
||||
|
||||
def update(self, uid: str, newNickname: str) -> bool:
|
||||
"""Update the nickname starting from the UID
|
||||
|
||||
Args:
|
||||
uid (str): UID of the user
|
||||
newNickname (str): New nickname
|
||||
|
||||
Returns:
|
||||
bool: True if updated
|
||||
"""
|
||||
result = False
|
||||
|
||||
for record in self.UID_REPUTATION_DB:
|
||||
if record.uid == uid:
|
||||
# If the user exist then update and return True and do not go further
|
||||
record.nickname = newNickname
|
||||
result = True
|
||||
self.Logs.debug(f'Reputation UID ({record.uid}) has been updated with new nickname {newNickname}')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'Reputation new nickname {newNickname} was not updated, uid = {uid}')
|
||||
|
||||
return result
|
||||
|
||||
def delete(self, uid: str) -> bool:
|
||||
"""Delete the User starting from the UID
|
||||
|
||||
Args:
|
||||
uid (str): UID of the user
|
||||
|
||||
Returns:
|
||||
bool: True if deleted
|
||||
"""
|
||||
result = False
|
||||
|
||||
for record in self.UID_REPUTATION_DB:
|
||||
if record.uid == uid:
|
||||
# If the user exist then remove and return True and do not go further
|
||||
self.UID_REPUTATION_DB.remove(record)
|
||||
result = True
|
||||
self.Logs.debug(f'UID ({record.uid}) has been deleted')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The UID {uid} was not deleted')
|
||||
|
||||
return result
|
||||
|
||||
def get_Reputation(self, uidornickname: str) -> Union[MReputation, None]:
|
||||
"""Get The User Object model
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or Nickname
|
||||
|
||||
Returns:
|
||||
UserModel|None: The UserModel Object | None
|
||||
"""
|
||||
User = None
|
||||
for record in self.UID_REPUTATION_DB:
|
||||
if record.uid == uidornickname:
|
||||
User = record
|
||||
elif record.nickname == uidornickname:
|
||||
User = record
|
||||
|
||||
if not User is None:
|
||||
self.Logs.debug(f'Reputation found for {uidornickname} -> {User}')
|
||||
|
||||
return User
|
||||
|
||||
def get_uid(self, uidornickname:str) -> Union[str, None]:
|
||||
"""Get the UID of the user starting from the UID or the Nickname
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or Nickname
|
||||
|
||||
Returns:
|
||||
str|None: Return the UID
|
||||
"""
|
||||
uid = None
|
||||
for record in self.UID_REPUTATION_DB:
|
||||
if record.uid == uidornickname:
|
||||
uid = record.uid
|
||||
if record.nickname == uidornickname:
|
||||
uid = record.uid
|
||||
|
||||
if not uid is None:
|
||||
self.Logs.debug(f'Reputation UID found for {uidornickname} -> {uid}')
|
||||
|
||||
return uid
|
||||
|
||||
def get_nickname(self, uidornickname:str) -> Union[str, None]:
|
||||
"""Get the Nickname starting from UID or the nickname
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or Nickname of the user
|
||||
|
||||
Returns:
|
||||
str|None: the nickname
|
||||
"""
|
||||
nickname = None
|
||||
for record in self.UID_REPUTATION_DB:
|
||||
if record.nickname == uidornickname:
|
||||
nickname = record.nickname
|
||||
if record.uid == uidornickname:
|
||||
nickname = record.nickname
|
||||
|
||||
if not nickname is None:
|
||||
self.Logs.debug(f'Reputation nickname found for {uidornickname} -> {nickname}')
|
||||
|
||||
return nickname
|
||||
|
||||
def is_exist(self, uidornickname: str) -> bool:
|
||||
"""Check if the UID or the nickname exist in the reputation DB
|
||||
|
||||
Args:
|
||||
uidornickname (str): The UID or the NICKNAME
|
||||
|
||||
Returns:
|
||||
bool: True if exist
|
||||
"""
|
||||
|
||||
found = False
|
||||
|
||||
for record in self.UID_REPUTATION_DB:
|
||||
if record.uid == uidornickname:
|
||||
found = True
|
||||
if record.nickname == uidornickname:
|
||||
found = True
|
||||
|
||||
return found
|
||||
10
core/classes/settings.py
Normal file
10
core/classes/settings.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from threading import Timer, Thread, RLock
|
||||
from socket import socket
|
||||
|
||||
class Settings:
|
||||
|
||||
RUNNING_TIMERS: list[Timer] = []
|
||||
RUNNING_THREADS: list[Thread] = []
|
||||
RUNNING_SOCKETS: list[socket] = []
|
||||
PERIODIC_FUNC: dict[object] = {}
|
||||
LOCK: RLock = RLock()
|
||||
180
core/classes/user.py
Normal file
180
core/classes/user.py
Normal file
@@ -0,0 +1,180 @@
|
||||
import re
|
||||
from typing import Union, TYPE_CHECKING
|
||||
from dataclasses import asdict
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.base import Base
|
||||
from core.definition import MUser
|
||||
|
||||
class User:
|
||||
|
||||
UID_DB: list['MUser'] = []
|
||||
|
||||
def __init__(self, baseObj: 'Base') -> None:
|
||||
|
||||
self.Logs = baseObj.logs
|
||||
self.Base = baseObj
|
||||
|
||||
return None
|
||||
|
||||
def insert(self, newUser: 'MUser') -> bool:
|
||||
"""Insert a new User object
|
||||
|
||||
Args:
|
||||
newUser (UserModel): New userModel object
|
||||
|
||||
Returns:
|
||||
bool: True if inserted
|
||||
"""
|
||||
result = False
|
||||
exist = False
|
||||
|
||||
for record in self.UID_DB:
|
||||
if record.uid == newUser.uid:
|
||||
# If the user exist then return False and do not go further
|
||||
exist = True
|
||||
self.Logs.debug(f'{record.uid} already exist')
|
||||
return result
|
||||
|
||||
if not exist:
|
||||
self.UID_DB.append(newUser)
|
||||
result = True
|
||||
# self.Logs.debug(f'New User Created: ({newUser})')
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The User Object was not inserted {newUser}')
|
||||
|
||||
return result
|
||||
|
||||
def update(self, uid: str, newNickname: str) -> bool:
|
||||
"""Update the nickname starting from the UID
|
||||
|
||||
Args:
|
||||
uid (str): UID of the user
|
||||
newNickname (str): New nickname
|
||||
|
||||
Returns:
|
||||
bool: True if updated
|
||||
"""
|
||||
result = False
|
||||
|
||||
for record in self.UID_DB:
|
||||
if record.uid == uid:
|
||||
# If the user exist then update and return True and do not go further
|
||||
record.nickname = newNickname
|
||||
result = True
|
||||
# self.Logs.debug(f'UID ({record.uid}) has been updated with new nickname {newNickname}')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The new nickname {newNickname} was not updated, uid = {uid}')
|
||||
|
||||
return result
|
||||
|
||||
def delete(self, uid: str) -> bool:
|
||||
"""Delete the User starting from the UID
|
||||
|
||||
Args:
|
||||
uid (str): UID of the user
|
||||
|
||||
Returns:
|
||||
bool: True if deleted
|
||||
"""
|
||||
result = False
|
||||
|
||||
for record in self.UID_DB:
|
||||
if record.uid == uid:
|
||||
# If the user exist then remove and return True and do not go further
|
||||
self.UID_DB.remove(record)
|
||||
result = True
|
||||
# self.Logs.debug(f'UID ({record.uid}) has been deleted')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.Logs.critical(f'The UID {uid} was not deleted')
|
||||
|
||||
return result
|
||||
|
||||
def get_User(self, uidornickname: str) -> Union['MUser', None]:
|
||||
"""Get The User Object model
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or Nickname
|
||||
|
||||
Returns:
|
||||
UserModel|None: The UserModel Object | None
|
||||
"""
|
||||
User = None
|
||||
for record in self.UID_DB:
|
||||
if record.uid == uidornickname:
|
||||
User = record
|
||||
elif record.nickname == uidornickname:
|
||||
User = record
|
||||
|
||||
# self.Logs.debug(f'Search {uidornickname} -- result = {User}')
|
||||
|
||||
return User
|
||||
|
||||
def get_uid(self, uidornickname:str) -> Union[str, None]:
|
||||
"""Get the UID of the user starting from the UID or the Nickname
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or Nickname
|
||||
|
||||
Returns:
|
||||
str|None: Return the UID
|
||||
"""
|
||||
uid = None
|
||||
for record in self.UID_DB:
|
||||
if record.uid == uidornickname:
|
||||
uid = record.uid
|
||||
if record.nickname == uidornickname:
|
||||
uid = record.uid
|
||||
|
||||
# if not uid is None:
|
||||
# self.Logs.debug(f'The UID that you are looking for {uidornickname} has been found {uid}')
|
||||
|
||||
return uid
|
||||
|
||||
def get_nickname(self, uidornickname:str) -> Union[str, None]:
|
||||
"""Get the Nickname starting from UID or the nickname
|
||||
|
||||
Args:
|
||||
uidornickname (str): UID or Nickname of the user
|
||||
|
||||
Returns:
|
||||
str|None: the nickname
|
||||
"""
|
||||
nickname = None
|
||||
for record in self.UID_DB:
|
||||
if record.nickname == uidornickname:
|
||||
nickname = record.nickname
|
||||
if record.uid == uidornickname:
|
||||
nickname = record.nickname
|
||||
# self.Logs.debug(f'The value to check {uidornickname} -> {nickname}')
|
||||
return nickname
|
||||
|
||||
def get_User_AsDict(self, uidornickname: str) -> Union[dict[str, any], None]:
|
||||
|
||||
userObj = self.get_User(uidornickname=uidornickname)
|
||||
|
||||
if not userObj is None:
|
||||
user_as_dict = asdict(userObj)
|
||||
return user_as_dict
|
||||
else:
|
||||
return None
|
||||
|
||||
def clean_uid(self, uid: str) -> str:
|
||||
"""Clean UID by removing @ / % / + / ~ / * / :
|
||||
|
||||
Args:
|
||||
uid (str): The UID to clean
|
||||
|
||||
Returns:
|
||||
str: Clean UID without any sign
|
||||
"""
|
||||
|
||||
pattern = fr'[:|@|%|\+|~|\*]*'
|
||||
parsed_UID = re.sub(pattern, '', uid)
|
||||
|
||||
return parsed_UID
|
||||
Reference in New Issue
Block a user