From f82c7b309f9b7721befc21b87421fe999caf10a8 Mon Sep 17 00:00:00 2001 From: profitroll Date: Tue, 21 Mar 2023 14:34:25 +0100 Subject: [PATCH] Added media removal --- config_example.json | 1 + locale/en.json | 9 ++++++-- locale/uk.json | 9 ++++++-- modules/api_client.py | 20 +++++++++++++++++- plugins/commands/photos.py | 43 ++++++++++++++++++++++++++++++++++++-- 5 files changed, 75 insertions(+), 7 deletions(-) diff --git a/config_example.json b/config_example.json index 70d9612..bd335e4 100644 --- a/config_example.json +++ b/config_example.json @@ -116,6 +116,7 @@ "commands_admin": [ "import", "export", + "remove", "shutdown" ] } \ No newline at end of file diff --git a/locale/en.json b/locale/en.json index bb0762b..8bc568f 100644 --- a/locale/en.json +++ b/locale/en.json @@ -42,7 +42,7 @@ "sub_wip": "Post submission is now WIP. It will be available again in a few days. Thank you for your patience.", "sub_error": "⚠️ Could not upload this image due to bot error. Admins are advised.", "sub_error_admin": "User {0} could not submit photo without additional confirmation due to:\n```\n{1}\n```", - "import_request": "Alright, please send me a zip archive with your media to be imported. Use /cancel if you want to abort this operation.", + "import_request": "Please send me a zip archive with your media to be imported. Use /cancel if you want to abort this operation.", "import_ignored": "No response, aborting import.", "import_abort": "Import aborted.", "import_invalid_media": "File to import must be a zip archive. Aborting.", @@ -54,7 +54,12 @@ "import_uploading": "Uploading archive contents...", "import_upload_error_duplicate": "Could not upload `{0}` because there're duplicates on server.", "import_upload_error_other": "Could not upload `{0}`. Probably disallowed filetype.", - "import_finished": "Import finished." + "import_finished": "Import finished.", + "remove_request": "Please send me an ID to delete. You might have it from upload dialog. Use /cancel if you want to abort this operation.", + "remove_ignored": "No response, aborting removal.", + "remove_abort": "Removal aborted.", + "remove_success": "Removed media with ID `{0}`.", + "remove_failure": "Could not remove media with ID `{0}`. Check if provided ID is correct and if it is - you can also check bot's log for details." }, "button": { "sub_yes": "✅ Accept", diff --git a/locale/uk.json b/locale/uk.json index f41ba8e..31e36a9 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -42,7 +42,7 @@ "sub_wip": "Подання постів зараз знаходиться у розробці. Він буде знову доступний через кілька днів. Дякуємо за ваше терпіння.", "sub_error": "⚠️ Не вдалось завантажити фото через помилку бота. Адміністрацію повідомлено.", "sub_error_admin": "Користувач {0} не зміг надіслати фото без додаткової перевірки через помилку:\n```\n{1}\n```", - "import_request": "Гаразд, будь ласка, надішліть zip-архів з медіа для імпортування. Використовуйте /cancel, якщо ви хочете перервати цю операцію.", + "import_request": "Будь ласка, надішліть zip-архів з медіа для імпортування. Використовуйте /cancel, якщо ви хочете перервати цю операцію.", "import_ignored": "Немає відповіді, перериваємо імпорт.", "import_abort": "Імпорт перервано.", "import_invalid_media": "Файл для імпорту має бути zip-архівом. Перериваємо.", @@ -54,7 +54,12 @@ "import_uploading": "Завантажуємо вміст архіву...", "import_upload_error_duplicate": "Не вдалося завантажити `{0}`, оскільки на сервері є дублікати.", "import_upload_error_other": "Не вдалося завантажити `{0}`. Ймовірно, заборонений тип файлу.", - "import_finished": "Імпорт завершено." + "import_finished": "Імпорт завершено.", + "remove_request": "Будь ласка, надішліть мені ID для видалення. Ви могли отримати його з діалогу завантаження. Використовуйте /cancel, якщо ви хочете перервати цю операцію.", + "remove_ignored": "Немає відповіді, перериваємо видалення.", + "remove_abort": "Видалення перервано.", + "remove_success": "Видалено медіа з ID `{0}`.", + "remove_failure": "Не вдалося видалити медіа з ID `{0}`. Перевірте, чи вказано правильний ID, і якщо він правильний, ви також можете переглянути логи бота для отримання більш детальної інформації." }, "button": { "sub_yes": "✅ Прийняти", diff --git a/modules/api_client.py b/modules/api_client.py index 9cb6dc0..63ff0fd 100644 --- a/modules/api_client.py +++ b/modules/api_client.py @@ -208,10 +208,28 @@ async def find_pic( async def move_pic(id: str, token: Union[str, None] = None) -> bool: token = await authorize() if token is None else token try: - await http_session.patch( + response = await http_session.patch( f'{configGet("address", "posting", "api")}/photos/{id}?caption=sent', headers={"Authorization": f"Bearer {token}"}, ) + if response.status != 200: + logWrite(f"Media moving failed with HTTP {response.status}", debug=True) + return False + return True + except: + return False + + +async def remove_pic(id: str, token: Union[str, None] = None) -> bool: + token = await authorize() if token is None else token + try: + response = await http_session.delete( + f'{configGet("address", "posting", "api")}/photos/{id}', + headers={"Authorization": f"Bearer {token}"}, + ) + if response.status != 204: + logWrite(f"Media removal failed with HTTP {response.status}", debug=True) + return False return True except: return False diff --git a/plugins/commands/photos.py b/plugins/commands/photos.py index 0737093..e56a798 100644 --- a/plugins/commands/photos.py +++ b/plugins/commands/photos.py @@ -11,7 +11,7 @@ from pyrogram import filters from pyrogram.types import Message from classes.poster_client import PosterClient -from modules.api_client import upload_pic +from modules.api_client import remove_pic, upload_pic from modules.app import app, users_with_context from modules.logger import logWrite from modules.utils import configGet, extract_and_save, locale @@ -166,7 +166,46 @@ async def cmd_export(app: PosterClient, msg: Message): @app.on_message(~filters.scheduled & filters.command(["remove"], prefixes=["", "/"])) async def cmd_remove(app: PosterClient, msg: Message): if msg.from_user.id in app.admins: - pass + global users_with_context + if msg.from_user.id not in users_with_context: + users_with_context.append(msg.from_user.id) + else: + return + await msg.reply_text( + locale("remove_request", "message", locale=msg.from_user.language_code) + ) + answer = await listen_message(app, msg.chat.id, timeout=600) + users_with_context.remove(msg.from_user.id) + if answer is None: + await msg.reply_text( + locale("remove_ignored", "message", locale=msg.from_user.language_code), + quote=True, + ) + return + if answer.text == "/cancel": + await answer.reply_text( + locale("remove_abort", "message", locale=msg.from_user.language_code) + ) + return + response = await remove_pic(answer.text) + if response: + logWrite( + f"Removed '{answer.text}' by request of user {answer.from_user.id}" + ) + await answer.reply_text( + locale( + "remove_success", "message", locale=msg.from_user.language_code + ).format(answer.text) + ) + else: + logWrite( + f"Could not remove '{answer.text}' by request of user {answer.from_user.id}" + ) + await answer.reply_text( + locale( + "remove_failure", "message", locale=msg.from_user.language_code + ).format(answer.text) + ) @app.on_message(~filters.scheduled & filters.command(["purge"], prefixes=["", "/"]))