Esempio n. 1
0
 async def logo(self, req):
     alias_id = req.rel_url.path.split('/')[1]
     chat = [i for i in chat_ids if i['alias_id'] == alias_id][0]
     chat_id = chat['chat_id']
     try:
         photo = await self.client.get_profile_photos(chat_id)
     except:
         log.debug(f"Error in getting profile picture in {chat_id}", exc_info=True)
         photo = None
     if not photo:
         return web.Response(status=404, text="404: Chat has no profile photo")
     photo = photo[0]
     size =  photo.sizes[0]
     media = types.InputPhotoFileLocation(
         id=photo.id,
         access_hash=photo.access_hash,
         file_reference=photo.file_reference,
         thumb_size=size.type
     )
     body = self.client.iter_download(media)
     r = web.Response(
         status=200,
         body=body,
     )
     r.enable_chunked_encoding()
     return r
Esempio n. 2
0
    async def logo(self, req: web.Request) -> web.Response:
        alias_id = req.match_info["chat"]
        chat = self.chat_ids[alias_id]
        chat_id = chat["chat_id"]
        chat_name = " ".join(
            map(lambda x: x[0].upper(), (chat["title"] or "_").split(" ")))
        logo_path = logo_folder.joinpath(f"{alias_id}.jpg")
        if not logo_path.exists():
            try:

                photo: types.Photo = (await self.client.get_profile_photos(
                    chat_id, limit=1))[0]
            except Exception:
                log.debug(f"Error in getting profile picture in {chat_id}",
                          exc_info=True)
                photo = None

            if not photo:
                W, H = (360, 360)
                color = tuple((random.randint(0, 255) for _ in range(3)))
                im = Image.new("RGB", (W, H), color)
                draw = ImageDraw.Draw(im)
                font = ImageFont.truetype("arial.ttf", 50)
                w, h = draw.textsize(chat_name, font=font)
                draw.text(((W - w) / 2, (H - h) / 2),
                          chat_name,
                          fill="white",
                          font=font)
                im.save(logo_path)
            else:
                pos = -1 if req.query.get("big", None) else int(
                    len(photo.sizes) / 2)
                size: types.PhotoSize = self.client._get_thumb(
                    photo.sizes, pos)
                if isinstance(
                        size,
                    (types.PhotoCachedSize, types.PhotoStrippedSize)):
                    await self.client._download_cached_photo_size(
                        size, logo_path)
                else:
                    media = types.InputPhotoFileLocation(
                        id=photo.id,
                        access_hash=photo.access_hash,
                        file_reference=photo.file_reference,
                        thumb_size=size.type,
                    )
                    await self.client.download_file(media, logo_path)

        with open(logo_path, "rb") as fp:
            body = fp.read()

        return web.Response(
            status=200,
            body=body,
            headers={
                "Content-Type": "image/jpeg",
                "Content-Disposition": 'inline; filename="logo.jpg"',
            },
        )
Esempio n. 3
0
    async def logo(self, req):
        alias_id = req.match_info['chat']
        chat = [i for i in chat_ids if i['alias_id'] == alias_id]
        if not chat:
            if not enable_otg:
                return web.Response(status=403, text="403: Forbiden")
            try:
                chat_id = int(alias_id)
            except:
                return web.Response(status=403, text="403: Forbiden")
        else:
            chat = chat[0]
            chat_id = chat['chat_id']
        chat_name = "Image not available"
        try:
            photo = await self.client.get_profile_photos(chat_id)
        except:
            log.debug(f"Error in getting profile picture in {chat_id}",
                      exc_info=True)
            photo = None
        if not photo:
            W, H = (160, 160)
            c = lambda: random.randint(0, 255)
            color = tuple([c() for i in range(3)])
            im = Image.new("RGB", (W, H), color)
            draw = ImageDraw.Draw(im)
            w, h = draw.textsize(chat_name)
            draw.text(((W - w) / 2, (H - h) / 2), chat_name, fill="white")
            temp = io.BytesIO()
            im.save(temp, "PNG")
            body = temp.getvalue()
        else:
            photo = photo[0]
            pos = -1 if req.query.get('big', None) else int(
                len(photo.sizes) / 2)
            size = self.client._get_thumb(photo.sizes, pos)
            if isinstance(size,
                          (types.PhotoCachedSize, types.PhotoStrippedSize)):
                body = self.client._download_cached_photo_size(size, bytes)
            else:
                media = types.InputPhotoFileLocation(
                    id=photo.id,
                    access_hash=photo.access_hash,
                    file_reference=photo.file_reference,
                    thumb_size=size.type)
                body = self.client.iter_download(media)

        r = web.Response(status=200,
                         body=body,
                         headers={
                             "Content-Type": "image/jpeg",
                             "Content-Disposition":
                             'inline; filename="logo.jpg"'
                         })
        #r.enable_chunked_encoding()
        return r
Esempio n. 4
0
    async def download_video_avatar(self, event: NewMessage.Event, target_user: str):
        user: User = await event.get_chat()
        photos = await self.bot.get_profile_photos(target_user)
        if len(photos) == 0:
            await event.message.respond("Не могу найти аватарку")
            return

        first_photo = photos[0]
        video_sizes = first_photo.video_sizes

        if video_sizes is None:
            avatar_buffer = io.BytesIO()
            await self.bot.download_profile_photo(target_user, file=avatar_buffer)

            if avatar_buffer.tell() > 0:
                async with self.bot.action(user, "photo", delay=10):
                    await self.reply_photo(event, avatar_buffer)
            else:
                logger.info(f"No avatar for @{user.username} ({user.id})")
            return

        video_size = video_sizes[0]

        progress_message: Message = await event.message.respond("Загружаю видео: 0%")

        async def progress_callback(current: int, total: int):
            new_progress = f"Загружаю видео: {round(current / total * 100)}%"
            if progress_message.text != new_progress:
                try:
                    await self.bot.edit_message(user, progress_message, new_progress)
                except MessageNotModifiedError:
                    pass

        video_bytes = await self.bot.download_file(
            types.InputPhotoFileLocation(
                id=first_photo.id,
                access_hash=first_photo.access_hash,
                file_reference=first_photo.file_reference,
                thumb_size=video_size.type,
            ),
            None,
            file_size=video_size.size,
            progress_callback=progress_callback,
        )

        if video_bytes:
            async with self.bot.action(user, "video", delay=60):
                message_text: str = event.message.message
                filter_type = 1 if message_text.rpartition(" ")[-1] == "1" else 0
                logger.error(repr(event.message.message))
                await self.process_video(event, video_bytes, progress_message, filter_type=filter_type)
        else:
            await event.message.respond("Не смог скачать видео")
Esempio n. 5
0
    async def logo(self, req):
        alias_id = req.match_info['chat']
        chat = [i for i in self.chat_ids if i['alias_id'] == alias_id][0]
        chat_id = chat['chat_id']
        chat_name = "Image not available"
        logo_path = logo_folder.joinpath(f"{alias_id}.jpg")
        if not logo_path.exists():
            try:
                photo = await self.client.get_profile_photos(chat_id)
            except:
                log.debug(f"Error in getting profile picture in {chat_id}",
                          exc_info=True)
                photo = None

            if not photo:
                W, H = (160, 160)
                color = tuple([random.randint(0, 255) for i in range(3)])
                im = Image.new("RGB", (W, H), color)
                draw = ImageDraw.Draw(im)
                w, h = draw.textsize(chat_name)
                draw.text(((W - w) / 2, (H - h) / 2), chat_name, fill="white")
                im.save(logo_path)
            else:
                photo = photo[0]
                pos = -1 if req.query.get('big', None) else int(
                    len(photo.sizes) / 2)
                size = self.client._get_thumb(photo.sizes, pos)
                if isinstance(
                        size,
                    (types.PhotoCachedSize, types.PhotoStrippedSize)):
                    await self.client._download_cached_photo_size(
                        size, logo_path)
                else:
                    media = types.InputPhotoFileLocation(
                        id=photo.id,
                        access_hash=photo.access_hash,
                        file_reference=photo.file_reference,
                        thumb_size=size.type)
                    await self.client.download_file(media, logo_path)

        with open(logo_path, 'rb') as fp:
            body = fp.read()

        return web.Response(status=200,
                            body=body,
                            headers={
                                "Content-Type":
                                "image/jpeg",
                                "Content-Disposition":
                                'inline; filename="logo.jpg"'
                            })
Esempio n. 6
0
 async def logo(self, req):
     alias_id = req.rel_url.path.split('/')[1]
     chat_id = chat_ids[alias_ids.index(alias_id)]
     photo = await self.client.get_profile_photos(chat_id)
     if not photo:
         return web.Response(status=404, text="404: Chat has no profile photo")
     photo = photo[0]
     size =  photo.sizes[0]
     media = types.InputPhotoFileLocation(
         id=photo.id,
         access_hash=photo.access_hash,
         file_reference=photo.file_reference,
         thumb_size=size.type
     )
     body = self.client.iter_download(media)
     r = web.Response(
         status=200,
         body=body,
     )
     r.enable_chunked_encoding()
     return r