Exemple #1
0
async def ffmpegsave(message: Message):
    if not os.path.exists(FF_MPEG_DOWN_LOAD_MEDIA_PATH):
        if not os.path.isdir(Config.DOWN_PATH):
            os.makedirs(Config.DOWN_PATH)
        if message.reply_to_message.media:
            start = datetime.now()
            reply_message = message.reply_to_message
            try:
                downloaded_file_name = await message.client.download_media(
                    message=reply_message,
                    file_name=FF_MPEG_DOWN_LOAD_MEDIA_PATH,
                    progress=progress,
                    progress_args=(message, "trying to download"),
                )
                downloaded_file_name = safe_filename(downloaded_file_name)
            except Exception as e:  # pylint:disable=C0103,W0703
                await message.edit(str(e))
            else:
                end = datetime.now()
                ms = (end - start).seconds
                await message.edit("Downloaded to `{}` in {} seconds.".format(
                    downloaded_file_name, ms))
        else:
            await message.edit("Reply to a Telegram media file")
    else:
        await message.edit(
            "a media file already exists in path. "
            f"Please remove the media and try again!\n`.term rm {FF_MPEG_DOWN_LOAD_MEDIA_PATH}`"
        )
async def mediainfo(message: Message):
    """Get Media Info"""
    reply = message.reply_to_message
    if not reply:
        await message.err("reply to media first", del_in=5)
        return
    process = await message.edit("`Processing ...`")
    x_media = None
    available_media = (
        "audio",
        "document",
        "photo",
        "sticker",
        "animation",
        "video",
        "voice",
        "video_note",
        "new_chat_photo",
    )
    for kind in available_media:
        x_media = getattr(reply, kind, None)
        if x_media is not None:
            break
    if x_media is None:
        await message.err("Reply To a Vaild Media Format", del_in=3)
        return
    media_type = str(type(x_media)).split("'")[1]
    file_path = safe_filename(await reply.download())
    output_ = await runcmd(f'mediainfo "{file_path}"')
    out = None
    if len(output_) != 0:
        out = output_[0]
    body_text = f"""
<h2>JSON</h2>
<pre>{x_media}</pre>
<br>

<h2>DETAILS</h2>
<pre>{out or 'Not Supported'}</pre>
"""
    text_ = media_type.split(".")[-1].upper()
    link = post_to_telegraph(media_type, body_text)
    if message.client.is_bot:
        markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=text_, url=link)]])
        await process.edit_text("ℹ️  <b>MEDIA INFO</b>", reply_markup=markup)
    else:
        await message.edit(f"ℹ️  <b>MEDIA INFO:  [{text_}]({link})</b>")
    os.remove(file_path)
Exemple #3
0
async def video_note(message: Message):
    """ Covert to video note """
    _cache_path = "userge/xcache/circle"
    _vid_path = _cache_path + "/temp_vid.mp4"
    reply = message.reply_to_message
    if not reply:
        await message.err("Reply to supported media", del_in=10)
        return
    if not (reply.video or reply.animation or reply.audio):
        await message.err("Only videos, gifs and audio are Supported",
                          del_in=10)
        return
    if os.path.exists(_cache_path):
        rmtree(_cache_path, ignore_errors=True)
    os.mkdir(_cache_path)
    await message.edit("`Processing ...`")
    if reply.video or reply.animation:
        note = safe_filename(await reply.download())
        await crop_vid(note, _vid_path)
    else:
        thumb_loc = _cache_path + "/thumb.jpg"
        audio_loc = _cache_path + "/music.mp3"
        if reply.audio.thumbs:
            audio_thumb = reply.audio.thumbs[0].file_id
            thumb = await userge.download_media(audio_thumb)
        else:
            thumb = None
        music = await reply.download()
        os.rename(music, audio_loc)
        if thumb:
            os.rename(thumb, thumb_loc)
        else:
            await thumb_from_audio(audio_loc, thumb_loc)
        await runcmd(
            f"""ffmpeg -loop 1 -i {thumb_loc} -i {audio_loc} -c:v libx264 -tune stillimage -c:a aac -b:a 192k -vf \"scale=\'iw-mod (iw,2)\':\'ih-mod(ih,2)\',format=yuv420p\" -shortest -movflags +faststart {_vid_path}"""
        )
    if os.path.exists(_vid_path):
        await message.client.send_video_note(message.chat.id, _vid_path)
    await message.delete()
    rmtree(_cache_path, ignore_errors=True)

async def get_rawaudio_thumb(data: Dict) -> Optional[tuple]:
    key = data["id"]
    msg = data["msg"]
    client = userge.bot if data["has_bot"] else userge
    thumb_loc = keypath(key, thumb=True)[1]
    if data["yt_url"]:
        song_path = await download_yt_song(key)
        if thumb := await check_thumb(
            await pool.run_in_thread(download)(data["thumb"] or await get_ytthumb(key))
        ):
            os.rename(thumb, thumb_loc)
            thumb = thumb_loc
    else:
        song_path = safe_filename(await client.download_media(msg.audio))
        thumb = await extract_thumb(song_path, key)
    if song_path and (outf := await convert_raw(song_path, key)):
        return outf, thumb


async def yt_x_bleck_megik(link: str) -> Optional[str]:
    if not (yt_id := get_yt_video_id(link)):
        if not (
            (output := await get_song_link(link))
            and (pf_ := output.get("linksByPlatform"))
            and (yt_ := pf_.get("youtube"))
        ):
            return
        yt_id = get_yt_video_id(yt_.get("url"))
    return yt_id
async def spinn(message: Message):
    """Spin any media"""
    reply = message.reply_to_message
    if not reply:
        return await message.err("Reply To Media First !", del_in=5)
    if (message.chat.type in ["group", "supergroup"]
            and not message.chat.permissions.can_send_animations):
        return await message.err(
            "can't send gif in this chat, Permission Denied !", del_in=5)
    # to choose no. of frames i.e step_dict[6] or 60 => 360 / 60 = 6 frames
    step_dict = {"1": 1, "2": 3, "3": 6, "4": 12, "5": 24, "6": 60}
    if "-s" in message.flags:
        step = step_dict.get(message.flags["-s"])
        if not step:
            return await message.err("Not valid value for flag '-s'", del_in=5)
    else:
        step = 1
    # Haha USERGE-X custom function
    pic_loc = safe_filename(await media_to_image(message))
    if not pic_loc:
        return await message.err("Reply to a valid media first", del_in=5)
    await message.edit(
        "🌀 `Tighten your seatbelts, sh*t is about to get wild ...`")
    # direction of rotation
    spin_dir = -1 if "-c" in message.flags else 1
    path = "userge/xcache/rotate-disc/"
    if os.path.exists(path):
        rmtree(path, ignore_errors=True)
    os.mkdir(path)
    # Converting RGBA to RGB
    im = Image.open(pic_loc)
    if im.mode != "RGB":
        im = im.convert("RGB")
    # Rotating pic by given angle and saving
    for k, nums in enumerate(range(1, 360, step), start=0):
        y = im.rotate(nums * spin_dir)
        y.save(os.path.join(path, "spinx%s.jpg" % k))

    output_vid = os.path.join(path, "out.mp4")
    # ;__; Maths lol, y = mx + c
    frate = int(((90 / 59) * step) + (1680 / 59))
    # https://stackoverflow.com/questions/20847674/ffmpeg-libx264-height-not-divisible-by-2
    await runcmd(
        f'ffmpeg -framerate {frate} -i {path}spinx%d.jpg -c:v libx264 -preset ultrafast -vf "crop=trunc(iw/2)*2:trunc(ih/2)*2" -pix_fmt yuv420p {output_vid}'
    )
    if os.path.exists(output_vid):
        reply_id = reply.message_id if reply else None
        if "-r" in message.flags:
            round_vid = os.path.join(path, "out_round.mp4")
            # aspect ratio = 1:1
            await crop_vid(output_vid, round_vid)
            await message.client.send_video_note(message.chat.id,
                                                 round_vid,
                                                 reply_to_message_id=reply_id)
        else:
            await message.client.send_animation(
                message.chat.id,
                output_vid,
                unsave=(not message.client.is_bot),
                reply_to_message_id=reply_id,
            )
        await message.delete()
    # Clean up
    os.remove(pic_loc)
    rmtree(path, ignore_errors=True)