Merge pull request #9 from adator85/dev

Dev
This commit is contained in:
adator
2024-08-03 19:22:30 +02:00
committed by GitHub
3 changed files with 86 additions and 49 deletions

View File

@@ -3,7 +3,6 @@ from datetime import datetime
from sqlalchemy import create_engine, Engine, Connection, CursorResult
from sqlalchemy.sql import text
from core.configuration import Config
from core.sys_configuration import SysConfig
class Base:
@@ -17,13 +16,16 @@ class Base:
'modules': 'sys_modules'
}
DEFENDER_VERSION = '' # MAJOR.MINOR.BATCH
LATEST_DEFENDER_VERSION = '' # Latest Version of Defender in git
DEFENDER_DB_PATH = 'db' + os.sep # Séparateur en fonction de l'OS
DEFENDER_DB_NAME = 'defender' # Le nom de la base de données principale
def __init__(self, Config: Config) -> None:
self.Config = Config # Assigner l'objet de configuration
self.SysConfig = SysConfig() # Importer les information pour le systeme
self.init_log_system() # Demarrer le systeme de log
self.get_latest_defender_version()
self.check_for_new_version() # Verifier si une nouvelle version est disponible
self.running_timers:list[threading.Timer] = [] # Liste des timers en cours
self.running_threads:list[threading.Thread] = [] # Liste des threads en cours
@@ -37,19 +39,36 @@ class Base:
self.db_create_first_admin() # Créer un nouvel admin si la base de données est vide
def get_latest_defender_version(self) -> None:
def __set_current_defender_version(self) -> None:
"""This will put the current version of Defender
located in version.json
"""
version_filename = f'.{os.sep}version.json'
with open(version_filename, 'r') as version_data:
current_version:dict[str, str] = json.load(version_data)
self.DEFENDER_VERSION = current_version["version"]
return None
def __get_latest_defender_version(self) -> None:
try:
#token = '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'
token = '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'
json_url = f'https://github.com/adator85/IRC_DEFENDER_MODULES/blob/e27a027ae99a6c11171635b2a120803e8682aac6/version.json'
token = ''
json_url = f'https://raw.githubusercontent.com/adator85/IRC_DEFENDER_MODULES/main/version.json'
headers = {
'Authorization': f'token {token}',
'Accept': 'application/vnd.github.v3.raw' # Indique à GitHub que nous voulons le contenu brut du fichier
}
if token == '':
response = requests.get(json_url)
else:
response = requests.get(json_url, headers=headers)
response.raise_for_status() # Vérifie si la requête a réussi
json_response:dict = response.json()
self.SysConfig.LATEST_DEFENDER_VERSION = json_response["version"]
self.LATEST_DEFENDER_VERSION = json_response["version"]
return None
except requests.HTTPError as err:
@@ -57,6 +76,34 @@ class Base:
except:
self.logs.warning(f'Github not available to fetch latest version')
def check_for_new_version(self) -> bool:
# Assigner la version actuelle de Defender
self.__set_current_defender_version()
# Récuperer la dernier version disponible dans github
self.__get_latest_defender_version()
isNewVersion = False
latest_version = self.LATEST_DEFENDER_VERSION
current_version = self.DEFENDER_VERSION
curr_major, curr_minor, curr_patch = current_version.split('.')
last_major, last_minor, last_patch = latest_version.split('.')
if last_major > curr_major:
self.logs.info(f'New version available: {current_version} >>> {latest_version}')
isNewVersion = True
elif last_major == curr_major and last_minor > curr_minor:
self.logs.info(f'New version available: {current_version} >>> {latest_version}')
isNewVersion = True
elif last_major == curr_major and last_minor == curr_minor and last_patch > curr_patch:
self.logs.info(f'New version available: {current_version} >>> {latest_version}')
isNewVersion = True
else:
isNewVersion = False
return isNewVersion
def get_unixtime(self) -> int:
"""
Cette fonction retourne un UNIXTIME de type 12365456
@@ -299,8 +346,8 @@ class Base:
def db_init(self) -> tuple[Engine, Connection]:
db_directory = self.SysConfig.DEFENDER_DB_PATH
full_path_db = self.SysConfig.DEFENDER_DB_PATH + self.SysConfig.DEFENDER_DB_NAME
db_directory = self.DEFENDER_DB_PATH
full_path_db = self.DEFENDER_DB_PATH + self.DEFENDER_DB_NAME
if not os.path.exists(db_directory):
os.makedirs(db_directory)

View File

@@ -3,7 +3,6 @@ from ssl import SSLSocket
from datetime import datetime, timedelta
from typing import Union
from core.configuration import Config
from core.sys_configuration import SysConfig
from core.base import Base
class Irc:
@@ -26,11 +25,10 @@ class Irc:
self.SSL_VERSION = None # Version SSL
self.Config = Config()
self.SysConfig = SysConfig()
# Liste des commandes internes du bot
self.commands_level = {
0: ['help', 'auth', 'copyright'],
0: ['help', 'auth', 'copyright','checkversion'],
1: ['load','reload','unload', 'deauth', 'uptime'],
2: ['show_modules', 'show_timers', 'show_threads', 'sentinel'],
3: ['quit', 'restart','addaccess','editaccess', 'delaccess']
@@ -183,7 +181,7 @@ class Irc:
sid = self.Config.SERVEUR_ID
service_id = self.Config.SERVICE_ID
version = self.SysConfig.DEFENDER_VERSION
version = self.Base.DEFENDER_VERSION
unixtime = self.Base.get_unixtime()
# Envoyer un message d'identification
@@ -631,11 +629,12 @@ class Irc:
def debug(self, debug_msg:str) -> None:
if self.Config.DEBUG == 1:
if type(debug_msg) == list:
if debug_msg[0] != 'PING':
print(f"[{self.Base.get_datetime()}] - {debug_msg}")
else:
# if self.Config.DEBUG == 1:
# if type(debug_msg) == list:
# if debug_msg[0] != 'PING':
# print(f"[{self.Base.get_datetime()}] - {debug_msg}")
# else:
#
print(f"[{self.Base.get_datetime()}] - {debug_msg}")
return None
@@ -731,6 +730,11 @@ class Irc:
hsid = str(cmd[0]).replace(':','')
if hsid == self.HSID:
if self.INIT == 1:
if self.Base.check_for_new_version():
version = f'{self.Base.DEFENDER_VERSION} >>> {self.Base.LATEST_DEFENDER_VERSION}'
else:
version = f'{self.Base.DEFENDER_VERSION}'
self.send2socket(f"MODE {self.Config.SERVICE_NICKNAME} +B")
self.send2socket(f"JOIN {self.Config.SERVICE_CHANLOG}")
print(f"################### DEFENDER ###################")
@@ -741,7 +745,7 @@ class Irc:
print(f"# SSL VER : {self.SSL_VERSION} ")
print(f"# NICKNAME : {self.Config.SERVICE_NICKNAME} ")
print(f"# CHANNEL : {self.Config.SERVICE_CHANLOG} ")
print(f"# VERSION : {self.SysConfig.DEFENDER_VERSION} ")
print(f"# VERSION : {version} ")
print(f"################################################")
self.Base.logs.info(f"################### DEFENDER ###################")
@@ -752,7 +756,7 @@ class Irc:
self.Base.logs.info(f"# SSL VER : {self.SSL_VERSION} ")
self.Base.logs.info(f"# NICKNAME : {self.Config.SERVICE_NICKNAME} ")
self.Base.logs.info(f"# CHANNEL : {self.Config.SERVICE_CHANLOG} ")
self.Base.logs.info(f"# VERSION : {self.SysConfig.DEFENDER_VERSION} ")
self.Base.logs.info(f"# VERSION : {version} ")
self.Base.logs.info(f"################################################")
# Initialisation terminé aprés le premier PING
@@ -842,7 +846,7 @@ class Irc:
arg = convert_to_string.split()
arg.remove(f':{self.Config.SERVICE_PREFIX}')
if not arg[0].lower() in self.commands:
self.debug(f"This command {arg[0]} is not available")
self.Base.logs.debug(f"This command {arg[0]} is not available")
return False
cmd_to_send = convert_to_string.replace(':','')
@@ -862,7 +866,7 @@ class Irc:
# Réponse a un CTCP VERSION
if arg[0] == '\x01VERSION\x01':
self.send2socket(f':{dnickname} NOTICE {user_trigger} :\x01VERSION Service {self.Config.SERVICE_NICKNAME} V{self.SysConfig.DEFENDER_VERSION}\x01')
self.send2socket(f':{dnickname} NOTICE {user_trigger} :\x01VERSION Service {self.Config.SERVICE_NICKNAME} V{self.Base.DEFENDER_VERSION}\x01')
return False
# Réponse a un TIME
@@ -1241,7 +1245,7 @@ class Irc:
self.send2socket(f':{dnickname} NOTICE {fromuser} : {uptime}')
case 'copyright':
self.send2socket(f':{dnickname} NOTICE {fromuser} : # Defender V.{self.SysConfig.DEFENDER_VERSION} Developped by adator® and dktmb® #')
self.send2socket(f':{dnickname} NOTICE {fromuser} : # Defender V.{self.Base.DEFENDER_VERSION} Developped by adator® and dktmb® #')
case 'sentinel':
# .sentinel on
@@ -1259,5 +1263,13 @@ class Irc:
if not chan in channel_to_dont_quit:
self.send2socket(f":{service_id} PART {chan}")
case 'checkversion':
if self.Base.check_for_new_version():
self.send2socket(f':{dnickname} NOTICE {fromuser} : New Version available : {self.Base.DEFENDER_VERSION} >>> {self.Base.LATEST_DEFENDER_VERSION}')
else:
self.send2socket(f':{dnickname} NOTICE {fromuser} : You have the latest version of defender')
pass
case _:
pass

View File

@@ -1,22 +0,0 @@
import os, json
####################################################################################################
# DO NOT TOUCH THIS FILE #
####################################################################################################
class SysConfig:
DEFENDER_VERSION = '4.0.0' # MAJOR.MINOR.BATCH
LATEST_DEFENDER_VERSION = '0.0.0' # Latest Version of Defender in git
DEFENDER_DB_PATH = 'db' + os.sep # Séparateur en fonction de l'OS
DEFENDER_DB_NAME = 'defender' # Le nom de la base de données principale
def __init__(self) -> None:
version_filename = f'.{os.sep}version.json'
with open(version_filename, 'r') as version_data:
self.global_configuration:dict[str, str] = json.load(version_data)
self.DEFENDER_VERSION = self.global_configuration["version"]
return None