rumine-api-wrapper/db/database.py

94 lines
3.8 KiB
Python
Raw Normal View History

2024-03-07 14:06:53 +01:00
from sqlalchemy import select
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
from db import LuckpermsPlayer, LitebansBan, LuckpermsUserPermission, TabUser
from db.schemas import MySQLConfig, UserSchema, RequestSchema, TabSchema
from sqlalchemy.ext.asyncio import AsyncSession
from aiocache import cached, SimpleMemoryCache
from aiocache.serializers import PickleSerializer
class Database:
def __init__(self, uri: MySQLConfig):
self.engine = create_async_engine(str(uri))
self.AsyncSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine, class_=AsyncSession)
self.uri = uri
@cached(ttl=3600, cache=SimpleMemoryCache, serializer=PickleSerializer())
async def get_uuid_by_username(self, request: RequestSchema):
async with self.AsyncSessionLocal() as session:
async with session.begin():
player = await session.execute(select(LuckpermsPlayer).filter(LuckpermsPlayer.username == request.username))
player = player.scalar_one_or_none()
if player:
return player.uuid
else:
return None
async def unban_by_uuid(self, user: UserSchema):
async with self.AsyncSessionLocal() as session:
bans = await session.execute(
select(LitebansBan).filter(
LitebansBan.uuid == user.uuid,
LitebansBan.active == True
)
)
bans = bans.scalars().all()
for ban in bans:
ban.active = False
ban.removed_by_uuid = "fa87b50a-791b-4c61-a56f-d6cc03df1582"
ban.removed_by_name = "The_MrKroll"
ban.removed_by_reason = "Куплен разбан на сайте"
await session.commit()
async def grant_permissions_by_uuid(self, user: UserSchema):
async with self.AsyncSessionLocal() as session:
permission = LuckpermsUserPermission(
uuid=str(user.uuid),
permission="group.subscribe",
value="1",
server="global",
world="global",
expiry=str(user.expiry),
contexts="{}"
)
session.add(permission)
await session.commit()
async def grant_tab_by_username(self, user: UserSchema, tab: TabSchema):
async with self.AsyncSessionLocal() as session:
prefix = TabUser(
user=user.username,
property=tab.property,
value=tab.value,
expiry=user.expiry
)
session.add(prefix)
await session.commit()
async def check_subscription_by_uuid(self, user: UserSchema) -> bool:
async with self.AsyncSessionLocal() as session:
subscription = await session.execute(
select(LuckpermsUserPermission).filter(
LuckpermsUserPermission.uuid == user.uuid,
LuckpermsUserPermission.permission == "group.subscribe"
)
)
if subscription.scalar():
return True
else:
return False
@cached(ttl=2, cache=SimpleMemoryCache, serializer=PickleSerializer())
async def check_ban_status_by_uuid(self, user: UserSchema) -> bool:
async with self.AsyncSessionLocal() as session:
ban = await session.execute(
select(LitebansBan).filter(
LitebansBan.uuid == user.uuid,
LitebansBan.active == True
)
)
if not ban.scalar():
return True
else:
return False