dev (#19)
* Config file changes * Commands `/remove`, `/import` and `/export` Co-authored-by: profitroll <vozhd.kk@gmail.com> Co-authored-by: Profitroll <47523801+profitrollgame@users.noreply.github.com> Co-authored-by: Renovate <renovate@git.end-play.xyz> Reviewed-on: #19
This commit is contained in:
@@ -5,4 +5,4 @@ class SubmissionType(Enum):
|
||||
DOCUMENT = "document"
|
||||
VIDEO = "video"
|
||||
ANIMATION = "animation"
|
||||
PHOTO = "photo"
|
||||
PHOTO = "photo"
|
||||
|
58
classes/exceptions.py
Normal file
58
classes/exceptions.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from typing import Any
|
||||
|
||||
|
||||
class SubmissionUnavailableError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class SubmissionUploadError(Exception):
|
||||
def __init__(self, file_path: str, status_code: int, content: Any) -> None:
|
||||
self.status_code = status_code
|
||||
self.content = content
|
||||
super().__init__(
|
||||
f"Could not upload photo '{file_path}' due to HTTP {self.status_code}: {self.content}"
|
||||
)
|
||||
|
||||
|
||||
class SubmissionDuplicatesError(Exception):
|
||||
def __init__(self, file_path: str, duplicates: list) -> None:
|
||||
self.duplicates = duplicates
|
||||
super().__init__(
|
||||
f"Found duplicates of a photo '{file_path}': {self.duplicates}"
|
||||
)
|
||||
|
||||
|
||||
class UserCreationError(Exception):
|
||||
def __init__(self, code: int, data: str) -> None:
|
||||
self.code = code
|
||||
self.data = data
|
||||
super().__init__(
|
||||
f"Could not create a new user. API returned HTTP {self.code} with content: {self.data}"
|
||||
)
|
||||
|
||||
|
||||
class UserCreationDuplicateError(Exception):
|
||||
def __init__(self, username: str) -> None:
|
||||
self.username = username
|
||||
super().__init__(f"User '{self.username} already exists.'")
|
||||
|
||||
|
||||
class AlbumCreationError(Exception):
|
||||
def __init__(self, code: int, data: str) -> None:
|
||||
self.code = code
|
||||
self.data = data
|
||||
super().__init__(
|
||||
f"Could not create a new album. API returned HTTP {self.code} with content: {self.data}"
|
||||
)
|
||||
|
||||
|
||||
class AlbumCreationDuplicateError(Exception):
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
super().__init__(f"Album '{self.name} already exists.'")
|
||||
|
||||
|
||||
class AlbumCreationNameError(Exception):
|
||||
def __init__(self, data: dict) -> None:
|
||||
self.data = data
|
||||
super().__init__(data["detail"])
|
98
classes/poster_client.py
Normal file
98
classes/poster_client.py
Normal file
@@ -0,0 +1,98 @@
|
||||
from os import path, remove, sep
|
||||
from shutil import rmtree
|
||||
from typing import Tuple, Union
|
||||
from pyrogram.client import Client
|
||||
from pyrogram.types import Message
|
||||
from classes.exceptions import SubmissionDuplicatesError, SubmissionUnavailableError
|
||||
from modules.api_client import upload_pic
|
||||
from modules.database import col_submitted
|
||||
from bson import ObjectId
|
||||
from modules.logger import logWrite
|
||||
|
||||
from modules.utils import configGet
|
||||
|
||||
|
||||
class PosterClient(Client):
|
||||
def __init__(self, name: str, **kwargs): # type: ignore
|
||||
super().__init__(name, **kwargs)
|
||||
self.owner = configGet("owner")
|
||||
self.admins = configGet("admins") + [configGet("owner")]
|
||||
|
||||
async def submit_photo(
|
||||
self, id: str
|
||||
) -> Tuple[Union[Message, None], Union[str, None]]:
|
||||
db_entry = col_submitted.find_one({"_id": ObjectId(id)})
|
||||
submission = None
|
||||
|
||||
if db_entry is None:
|
||||
raise SubmissionUnavailableError()
|
||||
else:
|
||||
if db_entry["temp"]["uuid"] is not None:
|
||||
if not path.exists(
|
||||
path.join(
|
||||
configGet("data", "locations"),
|
||||
"submissions",
|
||||
db_entry["temp"]["uuid"],
|
||||
db_entry["temp"]["file"],
|
||||
)
|
||||
):
|
||||
raise SubmissionUnavailableError()
|
||||
else:
|
||||
filepath = path.join(
|
||||
configGet("data", "locations"),
|
||||
"submissions",
|
||||
db_entry["temp"]["uuid"],
|
||||
db_entry["temp"]["file"],
|
||||
)
|
||||
try:
|
||||
submission = await self.get_messages(
|
||||
db_entry["user"], db_entry["telegram"]["msg_id"]
|
||||
)
|
||||
except:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
submission = await self.get_messages(
|
||||
db_entry["user"], db_entry["telegram"]["msg_id"]
|
||||
)
|
||||
filepath = await self.download_media(
|
||||
submission, file_name=configGet("tmp", "locations") + sep
|
||||
)
|
||||
except:
|
||||
raise SubmissionUnavailableError()
|
||||
|
||||
response = await upload_pic(
|
||||
str(filepath), allow_duplicates=configGet("allow_duplicates", "submission")
|
||||
)
|
||||
|
||||
if len(response[1]) > 0:
|
||||
raise SubmissionDuplicatesError(str(filepath), response[1])
|
||||
|
||||
col_submitted.find_one_and_update(
|
||||
{"_id": ObjectId(id)}, {"$set": {"done": True}}
|
||||
)
|
||||
|
||||
try:
|
||||
if db_entry["temp"]["uuid"] is not None:
|
||||
rmtree(
|
||||
path.join(
|
||||
configGet("data", "locations"),
|
||||
"submissions",
|
||||
db_entry["temp"]["uuid"],
|
||||
),
|
||||
ignore_errors=True,
|
||||
)
|
||||
else:
|
||||
remove(str(filepath))
|
||||
except (FileNotFoundError, NotADirectoryError):
|
||||
logWrite(
|
||||
f"Could not delete '{filepath}' on submission accepted", debug=True
|
||||
)
|
||||
|
||||
return submission, response[2]
|
||||
|
||||
async def ban_user(self, id: int) -> None:
|
||||
pass
|
||||
|
||||
async def unban_user(self, id: int) -> None:
|
||||
pass
|
55
classes/user.py
Normal file
55
classes/user.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from modules.app import app
|
||||
from datetime import datetime
|
||||
from modules.database import col_banned, col_users
|
||||
from modules.utils import configGet
|
||||
|
||||
|
||||
class PosterUser:
|
||||
def __init__(self, id: int):
|
||||
self.id = id
|
||||
|
||||
def is_blocked(self) -> bool:
|
||||
"""Check if user is banned from submitting content.
|
||||
|
||||
### Returns:
|
||||
`bool`: Must be `True` if banned and `False` if not
|
||||
"""
|
||||
return False if col_banned.find_one({"user": self.id}) is None else True
|
||||
|
||||
def block(self) -> None:
|
||||
"""Ban user from using command and submitting content."""
|
||||
if col_banned.find_one({"user": self.id}) is None:
|
||||
col_banned.insert_one({"user": self.id, "date": datetime.now()})
|
||||
|
||||
def unblock(self) -> None:
|
||||
"""Allow user to use command and submit posts again."""
|
||||
col_banned.find_one_and_delete({"user": self.id})
|
||||
|
||||
def is_limited(self) -> bool:
|
||||
"""Check if user is on a cooldown after submitting something.
|
||||
|
||||
### Returns:
|
||||
`bool`: Must be `True` if on the cooldown and `False` if not
|
||||
"""
|
||||
if self.id in app.admins:
|
||||
return False
|
||||
else:
|
||||
db_record = col_users.find_one({"user": self.id})
|
||||
if db_record is None:
|
||||
return False
|
||||
return (
|
||||
True
|
||||
if (datetime.now() - db_record["cooldown"]).total_seconds()
|
||||
< configGet("timeout", "submission")
|
||||
else False
|
||||
)
|
||||
|
||||
def limit(self) -> None:
|
||||
"""Restart user's cooldown. Used after post has been submitted."""
|
||||
if (
|
||||
col_users.find_one_and_update(
|
||||
{"user": self.id}, {"$set": {"cooldown": datetime.now()}}
|
||||
)
|
||||
is None
|
||||
):
|
||||
col_users.insert_one({"user": self.id, "cooldown": datetime.now()})
|
Reference in New Issue
Block a user