text
stringlengths
1
93.6k
import logging
import random
import string
from collections.abc import Iterable
from typing import Optional, Sequence, Union
from redis import asyncio as aioredis
import asyncpg
from pyrogram.types import Photo
from libpy3.aiopgsqldb import PgSQLdb
logger = logging.getLogger("forwarder.pgsql")
logger.setLevel(logging.DEBUG)
class CheckFile(PgSQLdb):
min_resolution = 120
async def check(self, sql: str, exec_sql: str, *args) -> bool:
try:
if await self.query1(sql, *args) is None:
await self.execute(exec_sql, *args)
return True
else:
return False
except asyncpg.PostgresError:
logger.exception("Got postgresql exception error")
return False
async def check_file(self, file_id: str) -> bool:
return await self.check(
"""SELECT "id" FROM "file_id" WHERE "id" = $1""",
"""INSERT INTO "file_id" VALUES ($1, CURRENT_TIMESTAMP)""",
file_id,
)
async def check_file_dirty(self, file_id: str) -> bool:
return (
await self.query1("""SELECT "id" FROM "file_id" WHERE "id" = $1""", file_id)
is None
)
async def insert_log(self, *args) -> None:
await self.execute(
"""INSERT INTO "msg_detail"
("to_chat", "to_msg", "from_chat", "from_id", "from_user", "forward_from")
VALUES ($1, $2, $3, $4, $5, $6)""",
*args,
)
@staticmethod
def check_photo(photo: Photo) -> bool:
return not (
photo.file_size / (photo.width * photo.height) * 1000
< CheckFile.min_resolution
or photo.file_size < 40960
)
async def update_forward_target(self, chat_id: int, target: str) -> None:
if await self.query1(
"""SELECT * FROM "special_forward" WHERE "chat_id" = $1""", chat_id
):
await self.execute(
"""UPDATE "special_forward" SET "target" = $1 WHERE "chat_id" = $2""",
target,
chat_id,
)
else:
await self.execute(
"""INSERT INTO "special_forward" ("chat_id", "target") VALUES ($1, $2)""",
chat_id,
target,
)
async def insert_blacklist(self, user_ids: Union[int, Sequence[int]]) -> None:
await self.execute(
"""INSERT INTO "blacklist" ("id") VALUES ($1)""",
user_ids,
isinstance(user_ids, Iterable),
)
async def remove_blacklist(self, user_id: int) -> None:
await self.execute("""DELETE FROM "blacklist" WHERE "id" = $1""", user_id)
async def query_user(self, user_id: int) -> Optional[asyncpg.Record]:
return await self.query1(
"""SELECT * FROM "user_list" WHERE "id" = $1""", user_id
)
async def insert_bypass(self, user_id: int) -> None:
if await self.query_user(user_id):
await self.execute(
"""UPDATE "user_list" SET "bypass" = true WHERE "id" = $1""", user_id
)
else:
await self.execute(
"""INSERT INTO "user_list" ("id", "bypass") VALUES ($1, true)""",
user_id,
)