Compare commits

..

3 Commits

Author SHA1 Message Date
Profitroll
056fc52353 This commit closes #4 and closes #6 2023-02-19 20:54:58 +01:00
Profitroll
8bafd0cb35 This commit closes #3 2023-02-19 20:44:00 +01:00
Profitroll
fd47217bad This commit closes #5 2023-02-19 20:31:08 +01:00
6 changed files with 25 additions and 11 deletions

View File

@@ -42,7 +42,7 @@ class PosterClient(Client):
except:
raise SubmissionUnavailableError()
response = await upload_pic(str(filepath))
response = await upload_pic(str(filepath), allow_duplicates=configGet("allow_duplicates", "submission"))
if len(response[1]) > 0:
raise SubmissionDuplicatesError(str(filepath), response[1])

View File

@@ -91,6 +91,7 @@
"timeout": 30,
"file_size": 15728640,
"tmp_size": 15728640,
"allow_duplicates": false,
"require_confirmation": {
"users": true,
"admins": true

View File

@@ -15,7 +15,9 @@
"shutdown": "Shutting down bot with pid `{0}`",
"startup": "Starting with pid `{0}`",
"sub_yes": "✅ Submission approved and accepted",
"sub_yes_auto": "✅ Submission automatically accepted",
"sub_no": "❌ Submission reviewed and declined",
"sub_dup": "⚠️ Submission automatically declined because database already contains this photo",
"sub_blocked": "You were blocked and you can't submit media anymore.",
"sub_unblocked": "You were unblocked and you can now submit media.",
"sub_by": "\n\nSubmitted by:",
@@ -33,7 +35,9 @@
"post_low": "Low amount of content: `There are only {0} files left in the queue.`",
"api_creds_invalid": "__TO_BE_ADDED__",
"sub_wip": "Post submission is now WIP. It will be available again in a few days. Thank you for your patience.",
"sub_duplicates_found": "__TO_BE_ADDED__"
"sub_duplicates_found": "__TO_BE_ADDED__",
"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```"
},
"button": {
"sub_yes": "✅ Accept",

View File

@@ -15,7 +15,9 @@
"shutdown": "Вимкнення бота з підом `{0}`",
"startup": "Запуск бота з підом `{0}`",
"sub_yes": "✅ Подання схвалено та прийнято",
"sub_yes_auto": "✅ Подання автоматично прийнято",
"sub_no": "❌ Подання розглянуто та відхилено",
"sub_dup": "⚠️ Подання автоматично відхилено через наявність цього фото в базі даних",
"sub_blocked": "Вас заблокували, ви більше не можете надсилати медіафайли.",
"sub_unblocked": "Вас розблокували, тепер ви можете надсилати медіафайли.",
"sub_by": "\n\nПредставлено:",
@@ -33,7 +35,9 @@
"post_low": "Мала кількість контенту: `Залишилось всього {0} файлів в черзі.`",
"api_creds_invalid": "__TO_BE_ADDED__",
"sub_wip": "Подання постів зараз знаходиться у розробці. Він буде знову доступний через кілька днів. Дякуємо за ваше терпіння.",
"sub_duplicates_found": "__TO_BE_ADDED__"
"sub_duplicates_found": "__TO_BE_ADDED__",
"sub_error": "⚠️ Не вдалось завантажити фото через помилку бота. Адміністрацію повідомлено.",
"sub_error_admin": "Користувач {0} не зміг надіслати фото без додаткової перевірки через помилку:\n```\n{1}\n```"
},
"button": {
"sub_yes": "✅ Прийняти",

View File

@@ -52,19 +52,22 @@ async def random_pic(token: Union[str, None] = None) -> Tuple[str, str]:
pic = choice(resp.json()["results"])
return pic["id"], pic["filename"]
async def upload_pic(filepath: str, token: Union[str, None] = None) -> Tuple[bool, list]:
async def upload_pic(filepath: str, allow_duplicates: bool = False, token: Union[str, None] = None) -> Tuple[bool, list]:
token = await authorize() if token is None else token
try:
pic_name = path.basename(filepath)
files = {'file': (pic_name, open(filepath, 'rb'), 'image/jpeg')}
response = post(f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos', params={"caption": "queue", "compress": False}, headers={"Authorization": f"Bearer {token}"}, files=files)
response = post(f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos', params={"caption": "queue", "compress": False, "ignore_duplicates": allow_duplicates}, headers={"Authorization": f"Bearer {token}"}, files=files)
if response.status_code != 200 and response.status_code != 409:
logWrite(f"Could not upload '{filepath}' to API: HTTP {response.status_code} with message '{response.content}'")
raise SubmissionUploadError(str(filepath), response.status_code, response.content)
duplicates = []
if "duplicates" in response.json():
for index, duplicate in enumerate(response.json()["duplicates"]):
duplicates.append(f'`{duplicate["id"]}`:\n{configGet("address_external", "posting", "api")}/token/photo/{response.json()["access_token"]}?id={index}')
if response.json()["access_token"] is None:
duplicates.append(f'`{duplicate["id"]}`:\n{configGet("address_external", "posting", "api")}/photos/{duplicate["id"]}')
else:
duplicates.append(f'`{duplicate["id"]}`:\n{configGet("address_external", "posting", "api")}/token/photo/{response.json()["access_token"]}?id={index}')
return True, duplicates
except:
return False, []

View File

@@ -149,25 +149,27 @@ async def get_submission(app: PosterClient, msg: Message):
if msg.from_user.id in app.admins and configGet("admins", "submission", "require_confirmation") is False:
try:
await app.submit_photo(str(inserted.inserted_id))
await msg.copy(app.owner, caption=caption)
await msg.reply_text(locale("sub_yes_auto", "message", locale=user_locale), quote=True)
await msg.copy(app.owner, caption=caption, disable_notification=True)
return
except SubmissionDuplicatesError as exp:
await msg.reply_text(locale("sub_media_duplicates_list", "message", locale=user_locale).format("\n".join(exp.duplicates)), quote=True)
return
except Exception as exp:
await msg.reply_text(format_exc())
await msg.reply_text(format_exc(), quote=True)
return
elif msg.from_user.id not in app.admins and configGet("users", "submission", "require_confirmation") is False:
try:
await app.submit_photo(str(inserted.inserted_id))
await msg.reply_text(locale("sub_yes_auto", "message", locale=user_locale), quote=True)
await msg.copy(app.owner, caption=caption)
return
except SubmissionDuplicatesError as exp:
await msg.reply_text(locale("sub_media_duplicates_list", "message", locale=user_locale).format("\n".join(exp.duplicates)), quote=True)
await msg.reply_text(locale("sub_dup", "message", locale=user_locale), quote=True)
return
except Exception as exp:
await app.send_message(app.owner, f"User {msg.from_user.id} could not submit photo without additional confirmation due to:\n```\n{format_exc()}\n```")
await msg.reply_text("Could not upload this image. Admins are advised.")
await app.send_message(app.owner, locale("sub_error_admin", "message").format(msg.from_user.id, format_exc()))
await msg.reply_text("sub_error", quote=True)
return
if msg.from_user.id not in app.admins: