Automatic detecting mime type of images

This commit is contained in:
Dawid Rejowski 2022-09-11 23:12:24 +02:00
parent 80bea7e86f
commit c6fd3d999f
5 changed files with 8 additions and 7 deletions

View file

@ -3,5 +3,6 @@ pillow
matrix-nio
pyyaml
aiofiles
python-magic
lottie
cairosvg

View file

@ -1,6 +1,7 @@
import os
import aiofiles.os
import magic
import logging
from nio import AsyncClient, UploadResponse, ErrorResponse, RoomGetStateEventError
@ -52,7 +53,8 @@ async def upload_stickerpack(client: AsyncClient, room_id: str, stickerset: Matr
return await client.room_put_state(room_id, 'im.ponies.room_emotes', stickerset.json(), state_key=stickerset.name())
async def upload_image(client: AsyncClient, image: str, mime_type: str):
async def upload_image(client: AsyncClient, image: str):
mime_type = magic.from_file(image, mime=True)
file_stat = await aiofiles.os.stat(image)
async with aiofiles.open(image, "r+b") as f:
resp, maybe_keys = await client.upload(

View file

@ -46,9 +46,9 @@ class MatrixReuploader:
converted_stickerset = await self.exporter.get_stickerset(stickerset.name())
yield self.STATUS_UPLOADING
for sticker in converted_stickerset:
with tempfile.NamedTemporaryFile('w+b', suffix=sticker.mime_type.replace('image/', '')) as file:
with tempfile.NamedTemporaryFile('w+b') as file:
file.write(sticker.image_data)
sticker_mxc = await upload_image(self.client, file.name, sticker.mime_type)
sticker_mxc = await upload_image(self.client, file.name)
stickerset.add_sticker(sticker_mxc, sticker.alt_text)
if not stickerset.count():

View file

@ -1,9 +1,8 @@
class Sticker:
"""Custom type for easier transfering sticker data between functions and classes with simple lists and returns"""
def __init__(self, image_data, alt_text: str, mime_type: str):
def __init__(self, image_data, alt_text: str):
self.image_data = image_data
self.alt_text = alt_text
self.mime_type = mime_type
class MatrixStickerset:

View file

@ -71,9 +71,8 @@ class TelegramExporter:
raw_data = await self.client.download_media(sticker_document, file=bytes)
if sticker_document.mime_type == 'image/webp':
data, width, height = _convert_image(raw_data)
result.append(Sticker(data, alt, 'image/png'))
if sticker_document.mime_type == 'application/x-tgsticker':
data = _convert_animation(raw_data)
result.append(Sticker(data, alt, 'image/webp'))
result.append(Sticker(data, alt))
return result