4
1
Fork 1

Rewrite CacheDB && Implements UserStates

This commit is contained in:
trueold89 2024-08-06 13:58:19 +03:00
parent dd27264fd5
commit 697dac6922
Signed by: trueold89
GPG Key ID: C122E85DD49E6B30
3 changed files with 37 additions and 104 deletions

View File

@ -7,7 +7,7 @@
# Imports # Imports
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from tubot.static.abc import IValidatable from tubot.static.abc import IValidatable
from tubot.db.types import CacheDBTypes, UserStates from tubot.db.types import CacheDBTypes, User
class CacheDB(IValidatable, ABC): class CacheDB(IValidatable, ABC):
@ -24,50 +24,22 @@ class CacheDB(IValidatable, ABC):
# Users # Users
@abstractmethod @abstractmethod
async def add_user(self, tg_id: int, name: str) -> None: async def write_user(self, tg_id: int, user: User) -> None:
""" """
Add user to cache db Writes user to cache db
:param tg_id: User telegram id :param tg_id: User telegram id
:param name: User telegram name :param user: User object
""" """
raise NotImplementedError raise NotImplementedError
@abstractmethod @abstractmethod
async def user_state(self, tg_id: int) -> UserStates: async def read_user(self, tg_id: int) -> User:
""" """
Get user state Writes user to cache db
:param tg_id: User telegram id
:return: Status of user
"""
raise NotImplementedError
@abstractmethod
async def change_user_state(self, tg_id: int, status: UserStates) -> None:
"""
Change user state
:param tg_id: User telegram id
:param status: New user status
"""
raise NotImplementedError
@abstractmethod
async def auth_user(self, tg_id: int) -> None:
"""
Auth user
:param tg_id: User telegram id
"""
raise NotImplementedError
@abstractmethod
async def is_user_auth(self, tg_id: int) -> bool:
"""
Check if user is already auth
:param tg_id: User telegram id :param tg_id: User telegram id
:return: User object
""" """
raise NotImplementedError raise NotImplementedError

View File

@ -60,38 +60,13 @@ class PythonCache(CacheDB):
# Users # Users
async def add_user(self, tg_id: int, name: str) -> None: async def write_user(self, tg_id: int, user: User) -> None:
if tg_id in tuple(self.users.keys()): self.users[tg_id] = user.to_dict
raise ValueError("User already exists")
user = User(tg_id, name)
self.users[tg_id] = user.dict
await self._save_pkl() await self._save_pkl()
async def user_state(self, tg_id: int) -> UserStates: async def read_user(self, tg_id: int) -> User:
if tg_id not in tuple(self.users.keys()): user_data = self.users[tg_id]
raise ValueError("User doesn't exists") return User.from_dict(user_data)
user = self.users[tg_id]
return user["state"]
async def change_user_state(self, tg_id: int, status: UserStates) -> None:
if tg_id not in tuple(self.users.keys()):
raise ValueError("User doesn't exists")
user = self.users[tg_id]
user["state"] = status
await self._save_pkl()
async def auth_user(self, tg_id: int) -> None:
if tg_id not in tuple(self.users.keys()):
raise ValueError("User doesn't exists")
user = self.users[tg_id]
user["auth"] = True
await self._save_pkl()
async def is_user_auth(self, tg_id: int) -> bool:
if tg_id not in tuple(self.users.keys()):
raise ValueError("User doesn't exists")
user = self.users[tg_id]
return user["auth"]
# Dirs # Dirs
@ -125,49 +100,21 @@ class RedisCache(CacheDB):
# Users # Users
async def add_user(self, tg_id: int, name: str) -> None: async def write_user(self, tg_id: int, user: User) -> None:
async with aioredis.from_url( async with aioredis.from_url(
f"redis://{self.host}", encoding="utf-8", decode_responses=True f"redis://{self.host}", encoding="utf-8", decode_responses=True
) as redis: ) as redis:
user = User(tg_id, name) json = json_dumps(user.to_dict)
json = json_dumps(user.dict)
await redis.set(str(tg_id), json) await redis.set(str(tg_id), json)
async def user_state(self, tg_id: int) -> UserStates: async def read_user(self, tg_id: int) -> User:
async with aioredis.from_url( async with aioredis.from_url(
f"redis://{self.host}", encoding="utf-8", decode_responses=True f"redis://{self.host}", encoding="utf-8", decode_responses=True
) as redis: ) as redis:
json = await redis.get(str(tg_id)) json = await redis.get(str(tg_id))
user = json_loads(json) user_data = json_loads(json)
return user["state"] user_data["state"] = UserStates(user_data["state"])
return User.from_dict(user_data)
async def change_user_state(self, tg_id: int, status: UserStates) -> None:
async with aioredis.from_url(
f"redis://{self.host}", encoding="utf-8", decode_responses=True
) as redis:
json = await redis.get(str(tg_id))
user = json_loads(json)
user["state"] = status
json = json_dumps(user)
await redis.set(str(tg_id), json)
async def auth_user(self, tg_id: int) -> None:
async with aioredis.from_url(
f"redis://{self.host}", encoding="utf-8", decode_responses=True
) as redis:
json = await redis.get(str(tg_id))
user = json_loads(json)
user["auth"] = True
json = json_dumps(user)
await redis.set(str(tg_id), json)
async def is_user_auth(self, tg_id: int) -> bool:
async with aioredis.from_url(
f"redis://{self.host}", encoding="utf-8", decode_responses=True
) as redis:
json = await redis.get(str(tg_id))
user = json_loads(json)
return bool(user["auth"])
# Dirs # Dirs

View File

@ -22,7 +22,9 @@ class UserStates(Enum):
Types of User status Types of User status
""" """
... IDLE = "IDLE"
DIRS = "DIRS"
WAIT_FOR_TORRENT = "WAIT_FOR_TORRENT"
class User(object): class User(object):
@ -32,11 +34,15 @@ class User(object):
tg_id: int tg_id: int
name: str name: str
state: UserStates | None = None state: UserStates = UserStates.IDLE
auth: bool = False auth: bool = False
def __init__( def __init__(
self, tg_id: int, name: str, state: UserStates | None = None, auth: bool = False self,
tg_id: int,
name: str,
state: UserStates = UserStates.IDLE,
auth: bool = False,
) -> None: ) -> None:
self.tg_id = tg_id self.tg_id = tg_id
self.name = name self.name = name
@ -44,10 +50,18 @@ class User(object):
self.auth = auth self.auth = auth
@property @property
def dict(self): def to_dict(self):
return { return {
"tg_id": self.tg_id, "tg_id": self.tg_id,
"name": self.name, "name": self.name,
"state": self.state, "state": self.state.value,
"auth": self.auth, "auth": self.auth,
} }
@classmethod
def from_dict(cls, usr: dict) -> "User":
tg = usr["tg_id"]
name = usr["name"]
state = UserStates(usr["state"])
auth = usr["auth"]
return cls(tg, name, state, auth)