Добавлена начальная база данных

This commit is contained in:
Vlad
2024-09-13 03:39:21 +03:00
parent c9f3aa4a20
commit ae819e33dc
4 changed files with 61 additions and 48 deletions
+1
View File
@@ -2,3 +2,4 @@
/__pycache__
/vpn_users.db
/config.py
/database.db
+36 -13
View File
@@ -8,6 +8,9 @@ from auth import login_with_credentials, link
from client import add_client, generate_client_id
from datetime import datetime, timedelta
from config import API_TOKEN, ADMIN_PASSWORD, ADMIN_USERNAME
from database import add_connection, DATABASE_PATH
import uuid
import aiosqlite
@@ -41,23 +44,43 @@ async def handle_text(message: types.Message, state: FSMContext):
try:
session = login_with_credentials(ADMIN_USERNAME, ADMIN_PASSWORD)
# Параметры клиента
email = message.text
tg_id = message.from_user.id
email = message.text
client_id = generate_client_id()
email = message.text
limit_ip = 1
total_gb = 0
current_time = datetime.utcnow()
expiry_time = int((current_time + timedelta(days=30)).timestamp() * 1000)
enable = True
flow = "xtls-rprx-vision"
# Проверяем наличие активного ключа
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute('''
SELECT * FROM connections
WHERE tg_id = ? AND expiry_time > ?
''', (tg_id, int(datetime.utcnow().timestamp() * 1000))) as cursor:
existing_key = await cursor.fetchone()
if existing_key:
await message.reply("У вас уже есть активный ключ. Вы не можете создать больше одного ключа.")
else:
# Генерация нового ключа
client_id = str(uuid.uuid4())
limit_ip = 1
total_gb = 0
current_time = datetime.utcnow()
expiry_time = int((current_time + timedelta(days=30)).timestamp() * 1000)
enable = True
flow = "xtls-rprx-vision"
add_client(session, client_id, email, tg_id, limit_ip, total_gb, expiry_time, enable, flow)
connection_link = link(session, email)
# Добавление клиента (функция для создания клиента)
result = add_client(session, client_id, email, tg_id, limit_ip, total_gb, expiry_time, enable, flow)
await message.reply(f"Ключ создан:\n<pre>{connection_link}</pre>", parse_mode="HTML")
# Сохранение данных в базу данных
await add_connection(tg_id, client_id, email, expiry_time)
# Получение ссылки на подключение
connection_link = link(session, email)
# Отправка ключа в виде цитаты
await message.reply(f"Ключ создан:\n<pre>{connection_link}</pre>", parse_mode="HTML")
# Сброс состояния
await state.clear()
except Exception as e:
await message.reply(f"Произошла ошибка: {e}")
await message.reply(f"Произошла ошибка: {e}")
+1 -1
View File
@@ -3,7 +3,7 @@ from aiogram.filters import Command
from aiogram.types import Message
from aiogram.filters import Command
import requests
from database import add_user, get_user, update_subscription
# from database import add_user, get_user, update_subscription
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.fsm.context import FSMContext
+23 -34
View File
@@ -1,38 +1,27 @@
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime
import aiosqlite
from datetime import datetime
DATABASE_URL = 'sqlite:///vpn_users.db'
DATABASE_PATH = 'database.db'
engine = create_engine(DATABASE_URL)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
async def init_db():
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute('''
CREATE TABLE IF NOT EXISTS connections (
tg_id INTEGER NOT NULL,
client_id TEXT NOT NULL,
email TEXT NOT NULL,
expiry_time INTEGER NOT NULL,
PRIMARY KEY (tg_id, client_id)
)
''')
await db.commit()
class VPNUser(Base):
__tablename__ = 'vpn_users'
id = Column(Integer, primary_key=True)
telegram_id = Column(Integer, unique=True)
username = Column(String)
subscription_end = Column(DateTime)
access_key = Column(String)
async def add_connection(tg_id: int, client_id: str, email: str, expiry_time: int):
async with aiosqlite.connect(DATABASE_PATH) as db:
# Добавляем новый ключ
await db.execute('''
INSERT INTO connections (tg_id, client_id, email, expiry_time)
VALUES (?, ?, ?, ?)
''', (tg_id, client_id, email, expiry_time))
await db.commit()
Base.metadata.create_all(engine)
def add_user(telegram_id, username, access_key):
user = VPNUser(telegram_id=telegram_id, username=username,
subscription_end=datetime.datetime.now() + datetime.timedelta(days=30),
access_key=access_key)
session.add(user)
session.commit()
def get_user(telegram_id):
return session.query(VPNUser).filter(VPNUser.telegram_id == telegram_id).first()
def update_subscription(telegram_id, days):
user = get_user(telegram_id)
if user:
user.subscription_end += datetime.timedelta(days=days)
session.commit()