From a06c893092171aca0308aced3e221e06b96dcbf7 Mon Sep 17 00:00:00 2001 From: Disledg Date: Wed, 13 Nov 2024 07:00:14 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B5=D1=81=D1=82=D1=80=D1=83=D0=BA?= =?UTF-8?q?=D1=82=D1=83=D1=80=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=D1=84?= =?UTF-8?q?=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2=20=D0=B2=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B5=D0=BA=D1=82=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 16 ++----- bot.py | 3 -- dal/db_Mong.py | 54 ++++++++++++++++++++++ db_Post.py => models/db_Post.py | 17 ------- service.py => service/service.py | 6 --- logger_config.py => utils/logger_config.py | 2 +- panel.py => utils/panel.py | 0 7 files changed, 59 insertions(+), 39 deletions(-) create mode 100644 dal/db_Mong.py rename db_Post.py => models/db_Post.py (84%) rename service.py => service/service.py (95%) rename logger_config.py => utils/logger_config.py (95%) rename panel.py => utils/panel.py (100%) diff --git a/.gitignore b/.gitignore index 063ba9c..7d01463 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,5 @@ *.json -pyvenv.cfg -bin/ -include/ -lib/ -lib64/ -__pycache__/* -lib64 -*.log.* -*.log -__pycache__/ -__pycache__/db.cpython-312.pyc -__pycache__/logger_config.cpython-312.pyc +TBot/ +logs/ +config/ +__pycache__/ \ No newline at end of file diff --git a/bot.py b/bot.py index db33f72..11b08ea 100644 --- a/bot.py +++ b/bot.py @@ -7,7 +7,6 @@ import json from datetime import datetime from logger_config import setup_logger -# Чтение конфигурации и настройка логгера with open('config.json', 'r') as file: config = json.load(file) logger = setup_logger() @@ -86,7 +85,6 @@ async def sup(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: else: await update.message.reply_text("Выберите команду или нажмите кнопку для продолжения.") -# Обработчик кнопок async def button_handler(update: Update, context): query = update.callback_query await query.answer() @@ -127,7 +125,6 @@ async def button_handler(update: Update, context): logger.error(f"Ошибка при обработке запроса пользователя {tgid}: {e}") await query.message.reply_text("Произошла ошибка. Пожалуйста, попробуйте снова.") -# Запуск приложения def main() -> None: init_db() application = Application.builder().token(config['token']).build() diff --git a/dal/db_Mong.py b/dal/db_Mong.py new file mode 100644 index 0000000..5fdf90b --- /dev/null +++ b/dal/db_Mong.py @@ -0,0 +1,54 @@ +from pymongo import MongoClient +import json + +class VPNServerRepository: + def __init__(self, config_path="config.json"): + with open(config_path, "r") as file: + config = json.load(file) + self.client = MongoClient(config["mongodb_uri"]) + self.db = self.client[config["database_name"]] + self.collection = self.db["vpn_servers"] + + def add_server(self, server_data): + """Добавляет новый VPN сервер в коллекцию.""" + result = self.collection.insert_one(server_data) + print(f"VPN сервер добавлен с ID: {result.inserted_id}") + return result.inserted_id + + def get_server(self, server_id): + """Получает сервер VPN по его ID.""" + server = self.collection.find_one({"_id": server_id}) + if server: + print(f"Найден VPN сервер: {server}") + else: + print(f"VPN сервер с ID {server_id} не найден.") + return server + + def update_server(self, server_id, update_data): + """Обновляет данные VPN сервера.""" + result = self.collection.update_one({"_id": server_id}, {"$set": update_data}) + if result.matched_count > 0: + print(f"VPN сервер с ID {server_id} обновлен.") + else: + print(f"VPN сервер с ID {server_id} не найден.") + return result.matched_count > 0 + + def delete_server(self, server_id): + """Удаляет VPN сервер по его ID.""" + result = self.collection.delete_one({"_id": server_id}) + if result.deleted_count > 0: + print(f"VPN сервер с ID {server_id} удален.") + else: + print(f"VPN сервер с ID {server_id} не найден.") + return result.deleted_count > 0 + + def list_servers(self): + """Возвращает список всех VPN серверов.""" + servers = list(self.collection.find()) + print(f"Найдено {len(servers)} VPN серверов.") + return servers + + def close_connection(self): + """Закрывает подключение к базе данных MongoDB.""" + self.client.close() + print("Подключение к MongoDB закрыто.") diff --git a/db_Post.py b/models/db_Post.py similarity index 84% rename from db_Post.py rename to models/db_Post.py index 36fc128..a792795 100644 --- a/db_Post.py +++ b/models/db_Post.py @@ -42,7 +42,6 @@ class Subscription(Base): updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now) user = relationship("User", back_populates="subscriptions") - vpn_server = relationship("VPNServer", back_populates="subscriptions") #Транзакции class Transaction(Base): @@ -76,22 +75,6 @@ class Administrators(Base): user_id = Column(String,ForeignKey('users.id')) admin = Column(Boolean,default=False) user = relationship("User",back_populates="admins") -# VPN-серверы -class VPNServer(Base): - __tablename__ = 'vpn_servers' - - id = Column(String, primary_key=True, default=generate_uuid) - server_name = Column(String) - ip_address = Column(String) - port = Column(Integer) - login = Column(String) - password = Column(String) - config = Column(String) - secret = Column(String) - current_users = Column(Integer, default=0) - max_users = Column(Integer, default=4) - - subscriptions = relationship("Subscription", back_populates="vpn_server") # Настройка подключения к базе данных DATABASE_URL = f"postgresql://{config['username']}:{config['password_DB']}@localhost/bot_db" diff --git a/service.py b/service/service.py similarity index 95% rename from service.py rename to service/service.py index dabd5b8..9f6f62e 100644 --- a/service.py +++ b/service/service.py @@ -14,7 +14,6 @@ def generate_random_string(length=8): return ''.join(secrets.choice(characters) for _ in range(length)) -# Загрузка конфигурации один раз with open('config.json', 'r') as file: config = json.load(file) @@ -182,7 +181,6 @@ class UserService: 'password': server.password, } - # Преобразование server.config из строки в словарь try: server_config_dict = json.loads(server.config) except json.JSONDecodeError as e: @@ -232,13 +230,11 @@ class UserService: def generate_uri(self, vpn_config, CIF3): try: - # Проверяем тип vpn_config и загружаем его, если это строка config_data = json.loads(vpn_config) if isinstance(vpn_config, str) else vpn_config obj = config_data["obj"] port = obj["port"] - # Обрабатываем настройки клиентов clients = json.loads(obj["settings"])["clients"] if isinstance(obj["settings"], str) else obj["settings"]["clients"] for client in clients: @@ -246,7 +242,6 @@ class UserService: uuid = client["id"] flow = client["flow"] - # Извлечение параметров из streamSettings stream_settings = json.loads(obj["streamSettings"]) if isinstance(obj["streamSettings"], str) else obj["streamSettings"] dest = stream_settings["realitySettings"]["dest"] server_names = stream_settings["realitySettings"]["serverNames"] @@ -254,7 +249,6 @@ class UserService: fingerprint = stream_settings["realitySettings"]["settings"]["fingerprint"] short_id = stream_settings["realitySettings"]["shortIds"][0] # Первый короткий ID - # Сборка строки VLess return ( f"vless://{uuid}@{dest}:{port}?type=tcp&security=reality" f"&pbk={public_key}&fp={fingerprint}&sni={server_names[0]}" diff --git a/logger_config.py b/utils/logger_config.py similarity index 95% rename from logger_config.py rename to utils/logger_config.py index d40f9b2..6088cdf 100644 --- a/logger_config.py +++ b/utils/logger_config.py @@ -6,7 +6,7 @@ def setup_logger(): logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler( - "app.log", + "/logs/app.log", when="midnight", interval=1, backupCount=7, diff --git a/panel.py b/utils/panel.py similarity index 100% rename from panel.py rename to utils/panel.py