API usage overhaul #27

Merged
profitroll merged 17 commits from overhaul into dev 2023-06-28 00:57:31 +03:00
Showing only changes of commit 66d9956026 - Show all commits

View File

@ -1,33 +1,33 @@
import logging import logging
from datetime import datetime from datetime import datetime
from os import makedirs, path from os import makedirs, path
from random import choice from random import choice, sample
from shutil import rmtree from shutil import rmtree
from traceback import format_exc, print_exc from traceback import format_exc, print_exc
from uuid import uuid4 from uuid import uuid4
import aiofiles import aiofiles
from aiohttp import ClientSession from aiohttp import ClientSession
from libbot.pyrogram.classes import PyroClient
from photosapi_client.errors import UnexpectedStatus from photosapi_client.errors import UnexpectedStatus
from PIL import Image from PIL import Image
from pyrogram.client import Client
from modules.api_client import ( from modules.api_client import (
authorize, authorize,
client, client,
photo_find,
photo_get, photo_get,
photo_patch, photo_patch,
video_find, photo_random,
video_get, video_get,
video_patch, video_patch,
video_random,
) )
from modules.database import col_sent, col_submitted from modules.database import col_sent, col_submitted
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
async def send_content(app: Client, http_session: ClientSession) -> None: async def send_content(app: PyroClient, http_session: ClientSession) -> None:
try: try:
try: try:
token = await authorize(http_session) token = await authorize(http_session)
@ -40,25 +40,67 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
try: try:
funcs = [] funcs = []
if app.config["posting"]["types"]["photo"]:
funcs.append(photo_find)
if (
app.config["posting"]["types"]["video"]
or app.config["posting"]["types"]["animation"]
):
funcs.append(video_find)
func = choice(funcs)
media = choice( print(funcs)
(
await func( if app.config["posting"]["types"]["photo"]:
funcs.append((photo_random, photo_get, app.send_photo, photo_patch))
if app.config["posting"]["types"]["video"]:
funcs.append((video_random, video_get, app.send_video, video_patch))
print(funcs)
if not funcs:
raise KeyError(
"No media source provided: all seem to be disabled in config"
)
if len(funcs) > 1:
found = False
for func_iter in sample(funcs, len(funcs)):
func = func_iter
media = (
await func_iter[0](
album=app.config["posting"]["api"]["album"],
caption="queue",
client=client,
limit=1,
)
).results[0]
try:
response = await func_iter[1](id=media.id, client=client)
except Exception as exp:
print_exc()
logger.error("Media is invalid: %s", exp)
if app.config["reports"]["error"]:
await app.send_message(
app.owner, f"Media is invalid: {exp}"
)
return
found = True
break
if not found:
raise KeyError("No media found")
else:
func = funcs[0]
media = (
await func[0](
album=app.config["posting"]["api"]["album"], album=app.config["posting"]["api"]["album"],
caption="queue", caption="queue",
page_size=app.config["posting"]["page_size"],
client=client, client=client,
limit=1,
) )
).results ).results[0]
) try:
response = await func[1](id=media.id, client=client)
except Exception as exp:
print_exc()
logger.error("Media is invalid: %s", exp)
if app.config["reports"]["error"]:
await app.send_message(app.owner, f"Media is invalid: {exp}")
return
except (KeyError, AttributeError, TypeError, IndexError): except (KeyError, AttributeError, TypeError, IndexError):
logger.info(app._("post_empty", "console")) logger.info(app._("post_empty", "console"))
if app.config["reports"]["error"]: if app.config["reports"]["error"]:
@ -67,6 +109,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
app._("api_queue_empty", "message"), app._("api_queue_empty", "message"),
) )
return return
except (ValueError, UnexpectedStatus): except (ValueError, UnexpectedStatus):
if app.config["reports"]["error"]: if app.config["reports"]["error"]:
await app.send_message( await app.send_message(
@ -75,30 +118,6 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
) )
return return
try:
if func is photo_find:
response = await photo_get(id=media.id, client=client)
else:
response = await video_get(id=media.id, client=client)
except Exception as exp:
print_exc()
logger.warning(
"Media is invalid: %s",
exp
# app._("post_invalid_pic", "console").format(
# response.status, str(await response.json())
# )
)
if app.config["reports"]["error"]:
await app.send_message(app.owner, f"Media is invalid: {exp}")
return
# await app.send_message(
# app.owner,
# app._("post_invalid_pic", "message").format(
# response.status, await response.json()
# ),
# )
tmp_dir = str(uuid4()) tmp_dir = str(uuid4())
makedirs(path.join(app.config["locations"]["tmp"], tmp_dir), exist_ok=True) makedirs(path.join(app.config["locations"]["tmp"], tmp_dir), exist_ok=True)
@ -116,7 +135,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
if ( if (
path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880 path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880
) and func is photo_find: ) and func[0] is photo_random:
image = Image.open(path.join(app.config["locations"]["tmp"], tmp_path)) image = Image.open(path.join(app.config["locations"]["tmp"], tmp_path))
width, height = image.size width, height = image.size
image = image.resize((int(width / 2), int(height / 2)), Image.ANTIALIAS) image = image.resize((int(width / 2), int(height / 2)), Image.ANTIALIAS)
@ -138,7 +157,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
if ( if (
path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880 path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880
) and func is photo_find: ) and func[0] is photo_random:
rmtree( rmtree(
path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True
) )
@ -178,20 +197,12 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
caption = caption caption = caption
try: try:
if func is photo_find: sent = await func[2](
sent = await app.send_photo( app.config["posting"]["channel"],
app.config["posting"]["channel"], path.join(app.config["locations"]["tmp"], tmp_path),
path.join(app.config["locations"]["tmp"], tmp_path), caption=caption,
caption=caption, disable_notification=app.config["posting"]["silent"],
disable_notification=app.config["posting"]["silent"], )
)
else:
sent = await app.send_video(
app.config["posting"]["channel"],
path.join(app.config["locations"]["tmp"], tmp_path),
caption=caption,
disable_notification=app.config["posting"]["silent"],
)
except Exception as exp: except Exception as exp:
logger.error( logger.error(
f"Could not send media {media.filename} ({media.id}) due to {exp}" f"Could not send media {media.filename} ({media.id}) due to {exp}"
@ -216,8 +227,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
} }
) )
func_patch = photo_patch if func is photo_find else video_patch await func[3](id=media.id, client=client, caption="sent")
await func_patch(id=media.id, client=client, caption="sent")
rmtree(path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True) rmtree(path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True)