~nicoco/sleamdge

f7b026c25bf7f972385f11cb04ea0a98397c9e31 — nicoco 4 months ago 571dbdf
feat: Sync XMPP avatar
1 files changed, 30 insertions(+), 2 deletions(-)

M sleamdge/session.py
M sleamdge/session.py => sleamdge/session.py +30 -2
@@ 1,7 1,10 @@
import asyncio
import tempfile
from io import BytesIO
from typing import Optional, Union

import steam
from PIL import Image
from slidge import BaseSession, FormField, SearchResult
from slixmpp.exceptions import XMPPError



@@ 36,7 39,7 @@ class Session(BaseSession[int, Recipient]):
    async def logout(self) -> None:
        await self.steam.close()

    async def on_composing(self, c: Recipient, *_, **__) -> None:
    async def on_composing(self, c: Recipient, thread=None) -> None:
        if c.is_group:
            return
        assert isinstance(c, Contact)


@@ 84,7 87,7 @@ class Session(BaseSession[int, Recipient]):
            self.log.debug("rm emoticon: %r", emoticon)
            await self.steam.remove_emoticon(msg, emoticon)

    async def on_correct(self, **kwargs) -> None:
    async def on_correct(self, *args, **kwargs) -> None:
        raise XMPPError("feature-not-implemented", "No correction in steam")

    async def on_retract(


@@ 109,3 112,28 @@ class Session(BaseSession[int, Recipient]):
                }
            ],
        )

    async def on_avatar(
        self, bytes_: Optional[bytes], hash_, type_, width, height
    ) -> None:
        if bytes_ is None:
            # Steam forces you to have an avatar, so we cannot remove it AFAIK
            return
        if len(bytes_) > 10e6:
            # steam does not want avatars larger than 1024 KB
            bytes_ = await self.xmpp.loop.run_in_executor(None, resize_image, bytes_)
        # workaround for bug in steam.py preventing use of BytesIO
        # https://github.com/Gobot1234/steam.py/issues/566
        with tempfile.NamedTemporaryFile() as tmp_file:
            tmp_file.write(bytes_)
            await self.steam.user.edit(avatar=steam.Media(tmp_file.name))


def resize_image(bytes_: bytes) -> bytes:
    with BytesIO() as f:
        img = Image.open(BytesIO(bytes_))
        img.thumbnail((500, 500))  # should be < 1024 KB hopefully
        img.save(f, format="JPEG")
        f.flush()
        f.seek(0)
        return f.read()