Реструктуризация файлов в проекте
This commit is contained in:
14
.gitignore
vendored
14
.gitignore
vendored
@@ -1,13 +1,5 @@
|
|||||||
*.json
|
*.json
|
||||||
pyvenv.cfg
|
TBot/
|
||||||
bin/
|
logs/
|
||||||
include/
|
config/
|
||||||
lib/
|
|
||||||
lib64/
|
|
||||||
__pycache__/*
|
|
||||||
lib64
|
|
||||||
*.log.*
|
|
||||||
*.log
|
|
||||||
__pycache__/
|
__pycache__/
|
||||||
__pycache__/db.cpython-312.pyc
|
|
||||||
__pycache__/logger_config.cpython-312.pyc
|
|
||||||
|
|||||||
3
bot.py
3
bot.py
@@ -7,7 +7,6 @@ import json
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from logger_config import setup_logger
|
from logger_config import setup_logger
|
||||||
|
|
||||||
# Чтение конфигурации и настройка логгера
|
|
||||||
with open('config.json', 'r') as file:
|
with open('config.json', 'r') as file:
|
||||||
config = json.load(file)
|
config = json.load(file)
|
||||||
logger = setup_logger()
|
logger = setup_logger()
|
||||||
@@ -86,7 +85,6 @@ async def sup(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|||||||
else:
|
else:
|
||||||
await update.message.reply_text("Выберите команду или нажмите кнопку для продолжения.")
|
await update.message.reply_text("Выберите команду или нажмите кнопку для продолжения.")
|
||||||
|
|
||||||
# Обработчик кнопок
|
|
||||||
async def button_handler(update: Update, context):
|
async def button_handler(update: Update, context):
|
||||||
query = update.callback_query
|
query = update.callback_query
|
||||||
await query.answer()
|
await query.answer()
|
||||||
@@ -127,7 +125,6 @@ async def button_handler(update: Update, context):
|
|||||||
logger.error(f"Ошибка при обработке запроса пользователя {tgid}: {e}")
|
logger.error(f"Ошибка при обработке запроса пользователя {tgid}: {e}")
|
||||||
await query.message.reply_text("Произошла ошибка. Пожалуйста, попробуйте снова.")
|
await query.message.reply_text("Произошла ошибка. Пожалуйста, попробуйте снова.")
|
||||||
|
|
||||||
# Запуск приложения
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
init_db()
|
init_db()
|
||||||
application = Application.builder().token(config['token']).build()
|
application = Application.builder().token(config['token']).build()
|
||||||
|
|||||||
54
dal/db_Mong.py
Normal file
54
dal/db_Mong.py
Normal file
@@ -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 закрыто.")
|
||||||
@@ -42,7 +42,6 @@ class Subscription(Base):
|
|||||||
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
||||||
|
|
||||||
user = relationship("User", back_populates="subscriptions")
|
user = relationship("User", back_populates="subscriptions")
|
||||||
vpn_server = relationship("VPNServer", back_populates="subscriptions")
|
|
||||||
|
|
||||||
#Транзакции
|
#Транзакции
|
||||||
class Transaction(Base):
|
class Transaction(Base):
|
||||||
@@ -76,22 +75,6 @@ class Administrators(Base):
|
|||||||
user_id = Column(String,ForeignKey('users.id'))
|
user_id = Column(String,ForeignKey('users.id'))
|
||||||
admin = Column(Boolean,default=False)
|
admin = Column(Boolean,default=False)
|
||||||
user = relationship("User",back_populates="admins")
|
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"
|
DATABASE_URL = f"postgresql://{config['username']}:{config['password_DB']}@localhost/bot_db"
|
||||||
@@ -14,7 +14,6 @@ def generate_random_string(length=8):
|
|||||||
return ''.join(secrets.choice(characters) for _ in range(length))
|
return ''.join(secrets.choice(characters) for _ in range(length))
|
||||||
|
|
||||||
|
|
||||||
# Загрузка конфигурации один раз
|
|
||||||
with open('config.json', 'r') as file:
|
with open('config.json', 'r') as file:
|
||||||
config = json.load(file)
|
config = json.load(file)
|
||||||
|
|
||||||
@@ -182,7 +181,6 @@ class UserService:
|
|||||||
'password': server.password,
|
'password': server.password,
|
||||||
}
|
}
|
||||||
|
|
||||||
# Преобразование server.config из строки в словарь
|
|
||||||
try:
|
try:
|
||||||
server_config_dict = json.loads(server.config)
|
server_config_dict = json.loads(server.config)
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
@@ -232,13 +230,11 @@ class UserService:
|
|||||||
|
|
||||||
def generate_uri(self, vpn_config, CIF3):
|
def generate_uri(self, vpn_config, CIF3):
|
||||||
try:
|
try:
|
||||||
# Проверяем тип vpn_config и загружаем его, если это строка
|
|
||||||
config_data = json.loads(vpn_config) if isinstance(vpn_config, str) else vpn_config
|
config_data = json.loads(vpn_config) if isinstance(vpn_config, str) else vpn_config
|
||||||
|
|
||||||
obj = config_data["obj"]
|
obj = config_data["obj"]
|
||||||
port = obj["port"]
|
port = obj["port"]
|
||||||
|
|
||||||
# Обрабатываем настройки клиентов
|
|
||||||
clients = json.loads(obj["settings"])["clients"] if isinstance(obj["settings"], str) else obj["settings"]["clients"]
|
clients = json.loads(obj["settings"])["clients"] if isinstance(obj["settings"], str) else obj["settings"]["clients"]
|
||||||
|
|
||||||
for client in clients:
|
for client in clients:
|
||||||
@@ -246,7 +242,6 @@ class UserService:
|
|||||||
uuid = client["id"]
|
uuid = client["id"]
|
||||||
flow = client["flow"]
|
flow = client["flow"]
|
||||||
|
|
||||||
# Извлечение параметров из streamSettings
|
|
||||||
stream_settings = json.loads(obj["streamSettings"]) if isinstance(obj["streamSettings"], str) else obj["streamSettings"]
|
stream_settings = json.loads(obj["streamSettings"]) if isinstance(obj["streamSettings"], str) else obj["streamSettings"]
|
||||||
dest = stream_settings["realitySettings"]["dest"]
|
dest = stream_settings["realitySettings"]["dest"]
|
||||||
server_names = stream_settings["realitySettings"]["serverNames"]
|
server_names = stream_settings["realitySettings"]["serverNames"]
|
||||||
@@ -254,7 +249,6 @@ class UserService:
|
|||||||
fingerprint = stream_settings["realitySettings"]["settings"]["fingerprint"]
|
fingerprint = stream_settings["realitySettings"]["settings"]["fingerprint"]
|
||||||
short_id = stream_settings["realitySettings"]["shortIds"][0] # Первый короткий ID
|
short_id = stream_settings["realitySettings"]["shortIds"][0] # Первый короткий ID
|
||||||
|
|
||||||
# Сборка строки VLess
|
|
||||||
return (
|
return (
|
||||||
f"vless://{uuid}@{dest}:{port}?type=tcp&security=reality"
|
f"vless://{uuid}@{dest}:{port}?type=tcp&security=reality"
|
||||||
f"&pbk={public_key}&fp={fingerprint}&sni={server_names[0]}"
|
f"&pbk={public_key}&fp={fingerprint}&sni={server_names[0]}"
|
||||||
@@ -6,7 +6,7 @@ def setup_logger():
|
|||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
handler = TimedRotatingFileHandler(
|
handler = TimedRotatingFileHandler(
|
||||||
"app.log",
|
"/logs/app.log",
|
||||||
when="midnight",
|
when="midnight",
|
||||||
interval=1,
|
interval=1,
|
||||||
backupCount=7,
|
backupCount=7,
|
||||||
Reference in New Issue
Block a user