initial commit
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
# utils/db/__init__.py
|
||||
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
# Создание асинхронного движка SQLAlchemy
|
||||
DATABASE_URL = 'sqlite+aiosqlite:///db/telezab.db'
|
||||
engine = create_async_engine(DATABASE_URL, echo=False)
|
||||
AsyncSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession)
|
||||
|
||||
# Базовый класс для всех моделей
|
||||
Base = declarative_base()
|
||||
|
||||
# Импорт моделей
|
||||
from .whitelist import Whitelist
|
||||
from .user_events import UserEvent
|
||||
from .subscriptions import Subscription
|
||||
from .regions import Region
|
||||
from .events import Event
|
||||
from .admins import Admin
|
||||
|
||||
# Создание всех таблиц
|
||||
async def init_db():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
print("INFO:SQLAlchemy:Database inited")
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# utils/db/admins.py
|
||||
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from utils.db import Base
|
||||
|
||||
class Admin(Base):
|
||||
__tablename__ = 'admins'
|
||||
|
||||
chat_id = Column(Integer, primary_key=True, unique=True, nullable=False)
|
||||
username = Column(String, nullable=False)
|
||||
@@ -0,0 +1,12 @@
|
||||
# utils/db/events.py
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Text, Boolean
|
||||
from utils.db import Base
|
||||
|
||||
class Event(Base):
|
||||
__tablename__ = 'events'
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
hash = Column(String, unique=True, nullable=False)
|
||||
data = Column(Text, nullable=False)
|
||||
delivered = Column(Boolean, default=False)
|
||||
@@ -0,0 +1,11 @@
|
||||
# utils/db/regions.py
|
||||
|
||||
from sqlalchemy import Column, String, Boolean
|
||||
from utils.db import Base
|
||||
|
||||
class Region(Base):
|
||||
__tablename__ = 'regions'
|
||||
|
||||
region_id = Column(String, primary_key=True, unique=True, nullable=False)
|
||||
region_name = Column(String, nullable=False)
|
||||
active = Column(Boolean, default=True)
|
||||
@@ -0,0 +1,22 @@
|
||||
# utils/db/subscriptions.py
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Boolean, UniqueConstraint
|
||||
from utils.db import Base
|
||||
|
||||
class Subscription(Base):
|
||||
__tablename__ = 'subscriptions'
|
||||
|
||||
chat_id = Column(Integer, nullable=False)
|
||||
region_id = Column(String, nullable=False)
|
||||
username = Column(String, nullable=False)
|
||||
active = Column(Boolean, default=True)
|
||||
skip = Column(Boolean, default=False)
|
||||
|
||||
# Определение составного первичного ключа
|
||||
__table_args__ = (
|
||||
UniqueConstraint('chat_id', 'region_id', name='unique_chat_region'),
|
||||
{'sqlite_autoincrement': True}
|
||||
)
|
||||
|
||||
# Определяем составной первичный ключ
|
||||
primary_key = Column(Integer, primary_key=True, autoincrement=True) # Добавление этого столбца необходимо для уникального первичного ключа
|
||||
@@ -0,0 +1,13 @@
|
||||
# utils/db/user_events.py
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Text
|
||||
from utils.db import Base
|
||||
|
||||
class UserEvent(Base):
|
||||
__tablename__ = 'user_events'
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
chat_id = Column(Integer, nullable=False)
|
||||
username = Column(String, nullable=False)
|
||||
action = Column(String, nullable=False)
|
||||
timestamp = Column(Text, nullable=False)
|
||||
@@ -0,0 +1,9 @@
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from utils.db import Base
|
||||
|
||||
class Whitelist(Base):
|
||||
__tablename__ = 'whitelist'
|
||||
|
||||
chat_id = Column(Integer, primary_key=True)
|
||||
username = Column(String)
|
||||
user_email = Column(String)
|
||||
@@ -0,0 +1,21 @@
|
||||
from sqlalchemy import cast, Integer
|
||||
from sqlalchemy.future import select
|
||||
from utils.db import AsyncSessionLocal
|
||||
from utils.db.regions import Region
|
||||
|
||||
async def get_sorted_regions():
|
||||
"""
|
||||
Получает отсортированный список активных регионов из базы данных.
|
||||
|
||||
:return: Список кортежей с идентификаторами и названиями регионов
|
||||
"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with session.begin():
|
||||
# Формируем запрос для получения активных регионов
|
||||
stmt = select(Region.region_id, Region.region_name).where(Region.active == True).order_by(cast(Region.region_id, Integer))
|
||||
|
||||
# Выполняем запрос и получаем результат
|
||||
result = await session.execute(stmt)
|
||||
regions = result.fetchall() # Получаем все записи как список кортежей
|
||||
regions = "\n".join(f"{region_id}: {region_name}" for region_id, region_name in regions)
|
||||
return regions
|
||||
@@ -0,0 +1,17 @@
|
||||
import logging
|
||||
|
||||
|
||||
from aiogram import types
|
||||
|
||||
from utils.db import AsyncSessionLocal, Whitelist
|
||||
from sqlalchemy.future import select
|
||||
|
||||
async def is_whitelisted(message: types.message):
|
||||
chat_id = message.chat.id
|
||||
async with AsyncSessionLocal() as session:
|
||||
stmt = select(Whitelist).filter_by(chat_id=chat_id)
|
||||
result = await session.execute(stmt)
|
||||
user = result.scalars().first()
|
||||
if not user:
|
||||
await message.answer("Вы не авторизованы для использования этого бота")
|
||||
logging.info(f"Unauthorized access attempt by {chat_id}")
|
||||
@@ -0,0 +1,14 @@
|
||||
from aiogram.types import KeyboardButton, ReplyKeyboardMarkup
|
||||
|
||||
|
||||
def show_settings_menu(chat_id):
|
||||
button_subscribe = KeyboardButton(text="Подписаться")
|
||||
button_unsubscribe = KeyboardButton(text="Отписаться")
|
||||
button_subscription = KeyboardButton(text="Мои подписки")
|
||||
button_active_regions = KeyboardButton(text="Активные регионы")
|
||||
button_cancel = KeyboardButton(text="Назад")
|
||||
button_row_1 = [button_subscribe,button_unsubscribe,button_subscription]
|
||||
button_row_2 = [button_active_regions]
|
||||
button_row_3 = [button_cancel]
|
||||
markup = ReplyKeyboardMarkup(keyboard=[button_row_1,button_row_2,button_row_3], resize_keyboard=True)
|
||||
return markup
|
||||
@@ -0,0 +1,33 @@
|
||||
# utils/subscribe.py
|
||||
from sqlalchemy import delete, select
|
||||
from utils.db.regions import Region
|
||||
from utils.db import AsyncSessionLocal, Subscription
|
||||
|
||||
|
||||
async def handle_subscribe(user_id, region_ids):
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with session.begin():
|
||||
# Пример: удаляем старые подписки и добавляем новые
|
||||
await session.execute(delete(Subscription).where(Subscription.user_id == user_id))
|
||||
new_subscriptions = [Subscription(user_id=user_id, region_id=region_id) for region_id in region_ids]
|
||||
session.add_all(new_subscriptions)
|
||||
await session.commit()
|
||||
|
||||
async def handle_unsubscribe(user_id):
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with session.begin():
|
||||
# Удаление всех подписок пользователя
|
||||
await session.execute(delete(Subscription).where(Subscription.user_id == user_id))
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def get_user_subscriptions(user_id):
|
||||
async with AsyncSessionLocal() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
select(Subscription.region_id, Region.region_name)
|
||||
.join(Region, Subscription.region_id == Region.region_id)
|
||||
.where(Subscription.user_id == user_id, Subscription.active == True)
|
||||
)
|
||||
subscriptions = result.fetchall()
|
||||
return subscriptions
|
||||
Reference in New Issue
Block a user