Exemplo n.º 1
0
async def open_posts(_, callback):
    username = callback.data.split(' ')[1]

    language = get_language(callback.from_user.id,
                            callback.from_user.language_code)

    key = f"{callback.message.chat.id}_{callback.message.message_id}"

    profile: Profile = cached_profiles.get(key)
    right_user_id = cached_ids.get(key)

    if profile is None or right_user_id is None:
        await callback.answer(get_message(language, "errors/not_cached_post"),
                              show_alert=True)
        await callback.edit_message_text("", reply_markup="")
        return

    if callback.from_user.id != right_user_id:
        await callback.answer(get_message(language, "errors/wrong_id"),
                              show_alert=True)
        return

    iterator: PostsIterator = cached_posts.get(key)

    if iterator is None:
        posts = get_user_posts(username)

        if posts == "Fail":
            await callback.answer(get_message(language, "errors/fail"),
                                  show_alert=True)
            return

        next_max_id = posts.get("next_max_id")

        iterator = PostsIterator(posts["post_list"], username, next_max_id)

        cached_posts[key] = iterator

    await callback.answer()

    post: Post = iterator.next(
    ) if iterator.index != -1 else iterator.collection[iterator.index]

    caption = create_caption_posts(post.caption, post.taken_at, post.views,
                                   post.is_video)

    keyboard = create_keyboard_posts(post.likes,
                                     post.comment_number,
                                     iterator.username,
                                     len(iterator.collection),
                                     language,
                                     callback.from_user.id,
                                     from_profile=True)

    media = InputMediaVideo(post.source) if post.is_video else InputMediaPhoto(
        post.source)
    media.caption = caption

    await callback.edit_message_media(media)
    await callback.edit_message_reply_markup(keyboard)
async def next_post(_, callback):
    message_id = callback.message.message_id
    chat_id = callback.message.chat.id

    key = f"{chat_id}_{message_id}"

    iterator: PostsIterator = cached_posts.get(key)

    language = get_language(callback.from_user.id,
                            callback.from_user.language_code)

    if iterator is None:
        await callback.answer(get_message(language, "errors/not_cached_post"),
                              show_alert=True)
        await callback.edit_message_text("", reply_markup="")
        return

    if iterator.right_user_id is None:
        iterator.right_user_id = cached_ids.get(key)

        if iterator.right_user_id is None:
            await callback.answer(get_message(language,
                                              "errors/not_cached_stories"),
                                  show_alert=True)
            await callback.edit_message_text("", reply_markup="")
            return

    if callback.from_user.id != iterator.right_user_id:
        await callback.answer(get_message(language, "errors/wrong_id"),
                              show_alert=True)
        return

    post = iterator.next()

    if post == "Fail":
        await callback.answer(get_message(language, "errors/fail"),
                              show_alert=True)
        return

    await callback.answer()

    caption = create_caption_posts(post.caption, post.taken_at, post.views,
                                   post.is_video)

    from_profile = len(callback.data.split(' ')) > 1

    keyboard = create_keyboard_posts(post.likes,
                                     post.comment_number,
                                     iterator.username,
                                     len(iterator.collection),
                                     callback.from_user.language_code,
                                     callback.from_user.id,
                                     from_profile=from_profile)

    media = InputMediaVideo(post.source) if post.is_video else InputMediaPhoto(
        post.source)
    media.caption = caption

    await callback.edit_message_media(media, reply_markup=keyboard)
Exemplo n.º 3
0
async def edit_message(m: Message):
    """
    edit any type of pyrogram message using the messages dict.
    :param m: pyrogram.Message to edit.
    """
    if m.text:
        messages[m.date] = await messages[m.date].edit(m.text)
    elif m.caption and m.caption != messages[m.date].caption:
        messages[m.date] = await messages[m.date].edit_caption(m.caption)
    elif m.media:
        caption = {'caption': m.caption + '\n'} if m.caption else {}
        if m.photo and m.photo != messages[m.date].photo:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaPhoto(m.photo.file_id, m.photo.file_unique_id,
                                **caption))
        elif m.video and m.video != messages[m.date].video:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaVideo(m.video.file_id, m.video.file_unique_id,
                                **caption))
        elif m.document and m.document != messages[m.date].document:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaDocument(m.document.file_id,
                                   m.document.file_unique_id, **caption))
        elif m.animation and m.animation != messages[m.date].animation:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaAnimation(m.animation.file_id,
                                    m.animation.file_unique_id, **caption))
        elif m.audio and m.audio != messages[m.date].audio:
            messages[m.date] = await messages[m.date].edit_media(
                InputMediaAudio(m.audio.file_id, m.audio.file_unique_id,
                                **caption))
Exemplo n.º 4
0
 def generate_video(self):
     log.info("[AP] Извлечение видео...")
     video_link = None
     video_file = None
     for _, v in self.story["video"]["files"].items():
         video_link = v
     if video_link is not None:
         video_file = download(video_link)
     if video_file is not None:
         self.media.append(InputMediaVideo(video_file))
Exemplo n.º 5
0
async def callback_query_forward_rice(_, callback_query):
    app.set_parse_mode("markdown")
    u_approver = callback_query.from_user
    c_group = callback_query.message.chat
    approver_status = (await c_group.get_member(u_approver.id)).status
    if not (approver_status in ("creator", "administrator")):
        await callback_query.answer("Only admin can approve this!")
        return
    await callback_query.answer("Successfully approved")
    m_op = callback_query.message.reply_to_message
    u_op = m_op.from_user
    arg_caption = f"{m_op.caption}\nOP: [{u_op.first_name}]({m_op.link})"
    if m_op.media_group_id:
        message_id = m_op.message_id
        media_group = await app.get_media_group(RICE_GROUP, message_id)
        arg_media = []
        for m in media_group:
            if m.photo and m.caption:
                arg_media.append(
                    InputMediaPhoto(m.photo.file_id, caption=arg_caption)
                )
            elif m.photo:
                arg_media.append(InputMediaPhoto(m.photo.file_id))
            elif m.video and m.caption:
                arg_media.append(
                    InputMediaVideo(m.video.file_id, caption=arg_caption)
                )
            elif m.video:
                arg_media.append(InputMediaVideo(m.video.file_id))
        m_cp = await app.send_media_group(RICE_CHANNEL, arg_media)
        link = m_cp[0].link
    else:
        m_cp = await m_op.copy(RICE_CHANNEL, caption=arg_caption)
        link = m_cp.link
    await callback_query.message.delete()
    reply_text = (
        f"**OP**: {u_op.mention()}\n"
        f"**Approver**: {u_approver.mention()}\n"
        f"**Forwarded**: [Rice Gallery]({link})"
    )
    await m_op.reply_text(reply_text, disable_web_page_preview=True)
Exemplo n.º 6
0
 async def ytdl_callback(_, c_q: CallbackQuery):
     startTime = time()
     u_id = c_q.from_user.id
     if u_id != Config.OWNER_ID and u_id not in Config.SUDO_USERS:
         return await c_q.answer("𝘿𝙚𝙥𝙡𝙤𝙮 𝙮𝙤𝙪𝙧 𝙤𝙬𝙣 𝙐𝙎𝙀𝙍𝙂𝙀-𝙓", show_alert=True)
     choice_id = c_q.matches[0].group(2)
     callback_continue = "Downloading Video Please Wait..."
     callback_continue += f"\n\nFormat Code : {choice_id}"
     await c_q.answer(callback_continue, show_alert=True)
     upload_msg = await userge.send_message(Config.LOG_CHANNEL_ID, "Uploading...")
     yt_code = c_q.matches[0].group(1)
     yt_url = f"https://www.youtube.com/watch?v={yt_code}"
     await c_q.edit_message_caption(
         caption=f"Video is now Downloading, for progress see [LOG CHANNEL]({upload_msg.link})\n\n🔗  [<b>Link</b>]({yt_url})\n🆔  <b>Format Code</b> : {choice_id}",
         reply_markup=None,
     )
     retcode = await _tubeDl(yt_url, startTime, choice_id)
     if retcode == 0:
         _fpath = ""
         for _path in glob.glob(os.path.join(Config.DOWN_PATH, str(startTime), "*")):
             if not _path.lower().endswith((".jpg", ".png", ".webp")):
                 _fpath = _path
         if not _fpath:
             await upload_msg.err("nothing found !")
             return
         uploaded_vid = await upload(upload_msg, Path(_fpath))
     else:
         return await upload_msg.edit(str(retcode))
     refresh_vid = await userge.bot.get_messages(
         Config.LOG_CHANNEL_ID, uploaded_vid.message_id
     )
     f_id, f_ref = get_file_id_and_ref(refresh_vid)
     if hasattr(refresh_vid.video, "thumbs"):
         try:
             video_thumb = await userge.bot.download_media(
                 refresh_vid.video.thumbs[0].file_id
             )
         except TypeError:
             video_thumb = None
     else:
         video_thumb = None
     await c_q.edit_message_media(
         media=InputMediaVideo(
             media=f_id,
             file_ref=f_ref,
             thumb=video_thumb,
             caption=f"📹  <b>[{uploaded_vid.caption}]({yt_url})</b>",
             supports_streaming=True,
         ),
         reply_markup=None,
     )
     await uploaded_vid.delete()
Exemplo n.º 7
0
async def ytdl_download_callback(client: Client, c_q: CallbackQuery):
    yt_code = c_q.matches[0].group(1)
    choice_id = c_q.matches[0].group(2)
    downtype = c_q.matches[0].group(3)
    if str(choice_id).isdigit():
        choice_id = int(choice_id)
        if choice_id == 0:
            await c_q.answer("🔄  Processing...", show_alert=False)
            await c_q.edit_message_reply_markup(
                reply_markup=(await download_button(yt_code)))
            return
    startTime = time()
    choice_str, disp_str = get_choice_by_id(choice_id, downtype)
    media_type = "Video" if downtype == "v" else "Audio"
    callback_continue = f"Downloading {media_type} Please Wait..."
    callback_continue += f"\n\nFormat Code : {disp_str}"
    await c_q.answer(callback_continue, show_alert=True)
    yt_url = BASE_YT_URL + yt_code
    await c_q.edit_message_text(text=(
        f"**⬇️ Downloading {media_type} ...**"
        f"\n\n🔗  <b><a href='{yt_url}'>Link</a></b>\n🆔  <b>Format Code</b> : {disp_str}"
    ), )
    if downtype == "v":
        k = await _tubeDl(url=yt_url, starttime=startTime, uid=choice_str)
    else:
        k = await _mp3Dl(url=yt_url, starttime=startTime, uid=choice_str)
    if type(k) == list:
        await c_q.answer(k[1], show_alert=True)
        return
    _fpath = ""
    thumb_pic = None
    for _path in glob.glob(os.path.join(DOWN_PATH, str(startTime), "*")):
        if _path.lower().endswith((".jpg", ".png", ".webp")):
            thumb_pic = _path
        else:
            _fpath = _path
    if not thumb_pic and downtype == "v":
        thumb_pic = str(await run_in_thread(download)(await
                                                      get_ytthumb(yt_code)))
    if downtype == "v":
        await c_q.edit_message_media(media=(InputMediaVideo(
            media=str(Path(_fpath)),
            caption=f"📹  <b><a href = '{yt_url}'>{Path(_fpath).name}</a></b>",
            thumb=thumb_pic)), )
    else:  # Audio
        await c_q.edit_message_media(media=(InputMediaAudio(
            media=str(Path(_fpath)),
            caption=f"🎵  <b><a href = '{yt_url}'>{Path(_fpath).name}</a></b>",
            thumb=thumb_pic)), )
Exemplo n.º 8
0
 def generate_video(self, attachment):
     log.info("[AP] Извлечение видео...")
     video_link = "https://m.vk.com/video{owner_id}_{id}".format(
         **attachment["video"])
     if not attachment["video"].get("platform"):
         soup = BeautifulSoup(
             self.session.http.get(video_link).text, "html.parser")
         if len(soup.find_all("source")) >= 2:
             video_link = soup.find_all("source")[1].get("src")
             file = download_video(self.session.http, video_link)
             if getsize(file) >= 2097152000:
                 log.info(
                     "[AP] Видео весит более 2 ГБ. Добавляем ссылку на видео в текст."
                 )
                 self.text += '\n🎥 <a href="{0}">{1[title]}</a>\n👁 {1[views]} раз(а) ⏳ {1[duration]} сек'.format(
                     video_link.replace("m.", ""), attachment["video"])
                 del file
                 return None
             self.media.append(InputMediaVideo(file))
     else:
         self.text += '\n🎥 <a href="{0}">{1[title]}</a>\n👁 {1[views]} раз(а) ⏳ {1[duration]} сек'.format(
             video_link.replace("m.", ""), attachment["video"])
Exemplo n.º 9
0
async def yt_dl_video(client, cb):
    url = cb.matches[0].group(1)
    audio_or_video = cb.matches[0].group(2)
    if audio_or_video == "video":
        file_name, downloaded_thumb, name, dur, u_date, uploader, views = await download_yt(
            url, as_video=True)
    else:
        file_name, downloaded_thumb, name, dur, u_date, uploader, views = await download_yt(
            url, as_video=False)
    if not os.path.exists(file_name):
        await cb.edit_message_text(file_name)
        return
    await cb.edit_message_text(f"`Downloaded : {name} | Now Uploading....`")
    import datetime
    f_size = humanbytes(os.stat(file_name).st_size)
    caption = f"""
**Title :** `{name}`
**Uploader :** `{uploader}`
**Views :** `{views}`
**Link :** `{url}`
**Duration :** `{datetime.timedelta(seconds=dur)}`
**File Size :** `{f_size}`
"""
    if audio_or_video == "video":
        file_ = InputMediaVideo(file_name,
                                thumb=downloaded_thumb,
                                supports_streaming=True,
                                duration=dur,
                                caption=caption)
    else:
        file_ = InputMediaAudio(file_name,
                                performer=uploader,
                                title=name,
                                thumb=downloaded_thumb,
                                duration=dur,
                                caption=caption)
    await cb.edit_message_media(file_)
    if os.path.exists(file_name):
        os.remove(file_name)
Exemplo n.º 10
0
async def note_send(client: Client, message: Message):
    await message.edit("<code>Loading...</code>")
    if len(message.text.split()) >= 2:
        find_note = await db.find_one(
            {"NAME": f"{message.text.split(' ', maxsplit=1)[1]}"})
        if find_note:
            if "MEDIA_GROUP_ID" in find_note:
                messages_grouped = await client.get_media_group(
                    int(find_note["CHAT_ID"]), int(find_note["MESSAGE_ID"]))
                media_grouped_list = []
                for _ in messages_grouped:
                    if _.photo:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaPhoto(_.photo.file_id,
                                                _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaPhoto(_.photo.file_id))
                    elif _.video:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaVideo(_.video.file_id,
                                                _.video.thumbs[0].file_id,
                                                _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaVideo(_.video.file_id,
                                                _.video.thumbs[0].file_id))
                    elif _.audio:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaAudio(_.audio.file_id,
                                                _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaAudio(_.audio.file_id))
                    elif _.document:
                        if _.caption:
                            media_grouped_list.append(
                                InputMediaDocument(
                                    _.document.file_id,
                                    _.document.thumbs[0].file_id,
                                    _.caption.markdown))
                        else:
                            media_grouped_list.append(
                                InputMediaDocument(
                                    _.document.file_id,
                                    _.document.thumbs[0].file_id))
                if message.reply_to_message:
                    await client.send_media_group(
                        message.chat.id,
                        media_grouped_list,
                        reply_to_message_id=message.reply_to_message.message_id
                    )
                else:
                    await client.send_media_group(message.chat.id,
                                                  media_grouped_list)
                await message.delete()
            else:
                if message.reply_to_message:
                    await client.copy_message(
                        message.chat.id,
                        int(find_note["CHAT_ID"]),
                        int(find_note["MESSAGE_ID"]),
                        reply_to_message_id=message.reply_to_message.message_id
                    )
                else:
                    await client.copy_message(message.chat.id,
                                              int(find_note["CHAT_ID"]),
                                              int(find_note["MESSAGE_ID"]))
                await message.delete()
        else:
            await message.edit("There is no such note")
    else:
        await message.edit("Example: <code>.note name note</code>")
Exemplo n.º 11
0
async def upload_single_file(
    message, local_file_name, caption_str, from_user, client, edit_media, yt_thumb
):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    local_file_name = str(Path(local_file_name).resolve())
    sent_message = None
    start_time = time.time()
    #
    thumbnail_location = os.path.join(
        DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg"
    )
    # LOGGER.info(thumbnail_location)
    if UPLOAD_AS_DOC.upper() == "TRUE":  # todo: this code will be removed in future
        thumb = None
        thumb_image_path = None
        if os.path.exists(thumbnail_location):
            thumb_image_path = await copy_file(
                thumbnail_location, os.path.dirname(
                    os.path.abspath(local_file_name))
            )
            thumb = thumb_image_path
        message_for_progress_display = message
        if not edit_media:
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(
                    os.path.basename(local_file_name))
            )
        prog = Progress(from_user, client, message_for_progress_display)
        sent_message = await message.reply_document(
            document=local_file_name,
            thumb=thumb,
            caption=caption_str,
            parse_mode="html",
            disable_notification=True,
            progress=prog.progress_for_pyrogram,
            progress_args=(
                f"{os.path.basename(local_file_name)}",
                start_time,
            ),
        )
        if edit_media:
            await message_for_progress_display.delete()
        if message.message_id != message_for_progress_display.message_id:
            try:
                await message_for_progress_display.delete()
            except FloodWait as gf:
                time.sleep(gf.x)
            except Exception as rr:
                LOGGER.warning(str(rr))
        os.remove(local_file_name)
        if thumb is not None:
            os.remove(thumb)
    else:
        try:
            message_for_progress_display = message
            if not edit_media:
                message_for_progress_display = await message.reply_text(
                    "starting upload of {}".format(
                        os.path.basename(local_file_name))
                )
                prog = Progress(from_user, client,
                                message_for_progress_display)
            if local_file_name.upper().endswith(("MKV", "MP4", "WEBM", "M4V", "3GP")):
                duration = 0
                try:
                    metadata = extractMetadata(createParser(local_file_name))
                    if metadata.has("duration"):
                        duration = metadata.get("duration").seconds
                except Exception as g_e:
                    LOGGER.info(g_e)
                width = 0
                height = 0
                thumb_image_path = None
                if os.path.exists(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)),
                    )
                else:
                    if not yt_thumb:
                        thumb_image_path = await take_screen_shot(
                            local_file_name,
                            os.path.dirname(os.path.abspath(local_file_name)),
                            (duration / 2),
                        )
                    else:
                        req = requests.get(yt_thumb)
                        thumb_image_path = os.path.join(
                            os.path.dirname(os.path.abspath(local_file_name)),
                            str(time.time()) + ".jpg",
                        )
                        with open(thumb_image_path, "wb") as thum:
                            thum.write(req.content)
                        img = Image.open(thumb_image_path).convert("RGB")
                        img.save(thumb_image_path, format="jpeg")
                    # get the correct width, height, and duration for videos greater than 10MB
                    if os.path.exists(thumb_image_path):
                        metadata = extractMetadata(
                            createParser(thumb_image_path))
                        if metadata.has("width"):
                            width = metadata.get("width")
                        if metadata.has("height"):
                            height = metadata.get("height")
                        # ref: https://t.me/PyrogramChat/44663
                        # https://stackoverflow.com/a/21669827/4723940
                        Image.open(thumb_image_path).convert("RGB").save(
                            thumb_image_path
                        )
                        img = Image.open(thumb_image_path)
                        # https://stackoverflow.com/a/37631799/4723940
                        img.resize((320, height))
                        img.save(thumb_image_path, "JPEG")
                        # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
                #
                thumb = None
                if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                    thumb = thumb_image_path
                # send video
                if edit_media and message.photo:
                    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                    sent_message = await message.edit_media(
                        media=InputMediaVideo(
                            media=local_file_name,
                            thumb=thumb,
                            caption=caption_str,
                            parse_mode="html",
                            width=width,
                            height=height,
                            duration=duration,
                            supports_streaming=True,
                        )
                        # quote=True,
                    )
                else:
                    sent_message = await message.reply_video(
                        video=local_file_name,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        width=width,
                        height=height,
                        thumb=thumb,
                        supports_streaming=True,
                        disable_notification=True,
                        progress=prog.progress_for_pyrogram,
                        progress_args=(
                            f"{os.path.basename(local_file_name)}",
                            start_time,
                        ),
                    )
                if thumb is not None:
                    os.remove(thumb)
            elif local_file_name.upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")):
                metadata = extractMetadata(createParser(local_file_name))
                duration = 0
                title = ""
                artist = ""
                if metadata.has("duration"):
                    duration = metadata.get("duration").seconds
                if metadata.has("title"):
                    title = metadata.get("title")
                if metadata.has("artist"):
                    artist = metadata.get("artist")
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)),
                    )
                thumb = None
                if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                    thumb = thumb_image_path
                # send audio
                if edit_media and message.photo:
                    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                    sent_message = await message.edit_media(
                        media=InputMediaAudio(
                            media=local_file_name,
                            thumb=thumb,
                            caption=caption_str,
                            parse_mode="html",
                            duration=duration,
                            performer=artist,
                            title=title,
                        )
                    )
                else:
                    sent_message = await message.reply_audio(
                        audio=local_file_name,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title,
                        thumb=thumb,
                        disable_notification=True,
                        progress=prog.progress_for_pyrogram,
                        progress_args=(
                            f"{os.path.basename(local_file_name)}",
                            start_time,
                        ),
                    )
                if thumb is not None:
                    os.remove(thumb)
            else:
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)),
                    )
                # if a file, don't upload "thumb"
                # this "diff" is a major derp -_- 😔😭😭
                thumb = None
                if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                    thumb = thumb_image_path
                #
                # send document
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaDocument(
                            media=local_file_name,
                            thumb=thumb,
                            caption=caption_str,
                            parse_mode="html",
                        )
                    )
                else:
                    sent_message = await message.reply_document(
                        document=local_file_name,
                        thumb=thumb,
                        caption=caption_str,
                        parse_mode="html",
                        disable_notification=True,
                        progress=prog.progress_for_pyrogram,
                        progress_args=(
                            f"{os.path.basename(local_file_name)}",
                            start_time,
                        ),
                    )
                if thumb is not None:
                    os.remove(thumb)

        except MessageNotModified as oY:
            LOGGER.info(oY)
        except FloodWait as g:
            LOGGER.info(g)
            time.sleep(g.x)
        except Exception as e:
            LOGGER.info(e)
            await message_for_progress_display.edit_text("**FAILED**\n" + str(e))
        else:
            if message.message_id != message_for_progress_display.message_id:
                try:
                    if sent_message is not None:
                        await message_for_progress_display.delete()
                except FloodWait as gf:
                    time.sleep(gf.x)
                except Exception as rr:
                    LOGGER.warning(str(rr))
                    await asyncio.sleep(5)
        os.remove(local_file_name)
    return sent_message
Exemplo n.º 12
0
async def upload_to_tg(message: Message, dirname: str, post: Post) -> None:  # pylint: disable=R0912
    """ uploads downloaded post from local to telegram servers """
    pto = (".jpg", ".jpeg", ".png", ".bmp")
    vdo = (".mkv", ".mp4", ".webm")
    paths = []
    if post.typename == 'GraphSidecar':
        # upload media group
        captioned = False
        media = []
        for path in natsorted(os.listdir(dirname)):
            ab_path = dirname + '/' + path
            paths.append(ab_path)
            if str(path).endswith(pto):
                if captioned:
                    media.append(InputMediaPhoto(media=ab_path))
                else:
                    media.append(InputMediaPhoto(media=ab_path, caption=get_caption(post)[:1023]))
                    captioned = True
            elif str(path).endswith(vdo):
                if captioned:
                    media.append(InputMediaVideo(media=ab_path))
                else:
                    media.append(InputMediaVideo(media=ab_path, caption=get_caption(post)[:1023]))
                    captioned = True
        if media:
            await message.client.send_media_group(message.chat.id, media)
            await message.client.send_media_group(Config.LOG_CHANNEL_ID, media)

    if post.typename == 'GraphImage':
        # upload a photo
        for path in natsorted(os.listdir(dirname)):
            if str(path).endswith(pto):
                ab_path = dirname + '/' + path
                paths.append(ab_path)
                await message.client.send_photo(
                    message.chat.id,
                    ab_path,
                    caption=get_caption(post)[:1023])
                await message.client.send_photo(
                    Config.LOG_CHANNEL_ID,
                    ab_path,
                    caption=get_caption(post)[:1023])

    if post.typename == 'GraphVideo':
        # upload a video
        for path in natsorted(os.listdir(dirname)):
            if str(path).endswith(vdo):
                ab_path = dirname + '/' + path
                paths.append(ab_path)
                thumb = await get_thumb(ab_path)
                duration = 0
                metadata = extractMetadata(createParser(ab_path))
                if metadata and metadata.has("duration"):
                    duration = metadata.get("duration").seconds

                await message.client.send_video(
                    chat_id=message.chat.id,
                    video=ab_path,
                    duration=duration,
                    thumb=thumb,
                    caption=get_caption(post)[:1023])
                await message.client.send_video(
                    chat_id=Config.LOG_CHANNEL_ID,
                    video=ab_path,
                    duration=duration,
                    thumb=thumb,
                    caption=get_caption(post)[:1023])
                await remove_thumb(thumb)
    for del_p in paths:
        if os.path.lexists(del_p):
            os.remove(del_p)
Exemplo n.º 13
0
async def upload_single_file(path, message, force_edit,database=None,thumb_image_path=None,user_msg=None):
    if database is not None:
        if database.get_cancel_status(message.chat_id,message.id):
            # add os remove here
            return None
    if not os.path.exists(path):
        return None
    
    force_docs = get_val("FORCE_DOCUMENTS")
    if user_msg is not None:
        force_docs = user_db.get_var("FORCE_DOCUMENTS",user_msg.sender_id)

    thonmsg = message
    message = await message.client.pyro.get_messages(message.chat_id, message.id)
    tout = get_val("EDIT_SLEEP_SECS")
    sent_message = None
    start_time = time.time()
    #
    if user_msg is not None:
        dis_thumb = user_db.get_var("DISABLE_THUMBNAIL", user_msg.sender_id)
        if dis_thumb is False or dis_thumb is None:
            thumb_image_path = user_db.get_thumbnail(user_msg.sender_id)
            if not thumb_image_path:
                thumb_image_path = None
    #
    try:
        message_for_progress_display = message
        if not force_edit:
            data = "upcancel {} {} {}".format(message.chat.id,message.message_id,user_msg.sender_id)
            markup = InlineKeyboardMarkup([[InlineKeyboardButton("Cancel Upload", callback_data=data.encode("UTF-8"))]])
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(os.path.basename(path)),
                reply_markup=markup
            )
        if str(path).upper().endswith(("MKV", "MP4", "WEBM")) and not force_docs:
            metadata = extractMetadata(createParser(path))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            if thumb_image_path is None:
                thumb_image_path = await thumb_manage.get_thumbnail(path)
                # get the correct width, height, and duration for videos greater than 10MB

            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            
            # send video
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        width=width,
                        height=height,
                        duration=duration,
                        supports_streaming=True
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        "trying to upload",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        elif str(path).upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")) and not force_docs:
            metadata = extractMetadata(createParser(path))
            duration = 0
            title = ""
            artist = ""
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            if metadata.has("title"):
                title = metadata.get("title")
            if metadata.has("artist"):
                artist = metadata.get("artist")
            
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        "trying to upload",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        else:
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(
                        media=path,
                        thumb=thumb,
                        parse_mode="html"
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=path,
                    # quote=True,
                    thumb=thumb,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        "trying to upload",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        if str(e).find("cancel") != -1:
            torlog.info("cancled an upload lol")
            await message_for_progress_display.delete()
        else:
            torlog.info(traceback.format_exc())
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    #os.remove(path)
    if sent_message is None:
        return None
    sent_message = await thonmsg.client.get_messages(sent_message.chat.id, ids=sent_message.message_id)
    return sent_message
Exemplo n.º 14
0
async def catch_youtube_dldata(bot, update):
    thumb_image_path = os.getcwd() + "/" + "thumbnails" + "/" + str(
        update.from_user.id) + ".jpg"
    yt_thumb_image_path = os.getcwd() + "/" + "YouTubeThumb" + "/" + str(
        update.from_user.id) + ".jpg"
    if os.path.exists(thumb_image_path):
        thumb_image = thumb_image_path
    else:
        thumb_image = yt_thumb_image_path
    file_name = str(Config.PRE_FILE_TXT)
    cb_data = update.data
    # Callback Data Check (for Youtube formats)
    if cb_data.startswith(("video", "audio", "docaudio", "docvideo")):
        yturl = cb_data.split("||")[-1]
        format_id = cb_data.split("||")[-2]
        if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")):
            print("no data found")
            raise ContinuePropagation

        new_filext = "%(title)s.%(ext)s"
        filext = file_name + new_filext
        saved_file_path = os.getcwd() + "/" + "downloads" + "/" + str(
            update.from_user.id) + "/"
        if not os.path.isdir(saved_file_path):
            os.makedirs(saved_file_path)
        dl_folder = [f for f in os.listdir(saved_file_path)]
        for f in dl_folder:
            try:
                os.remove(os.path.join(saved_file_path, f))
            except IndexError:
                pass
        await update.edit_message_text(text=Translation.DOWNLOAD_START)
        filepath = os.path.join(saved_file_path, filext)

        audio_command = [
            "youtube-dl",
            "-c",
            "--prefer-ffmpeg",
            "--extract-audio",
            "--audio-format",
            "mp3",
            "--audio-quality",
            format_id,
            "-o",
            filepath,
            yturl,
        ]

        video_command = [
            "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio",
            "-o", filepath, "--hls-prefer-ffmpeg", yturl
        ]

        loop = asyncio.get_event_loop()
        med = None
        if cb_data.startswith("audio"):
            filename = await downloadaudiocli(audio_command)
            med = InputMediaAudio(media=filename,
                                  caption=os.path.basename(filename),
                                  title=os.path.basename(filename),
                                  thumb=thumb_image)

        if cb_data.startswith("video"):
            description = Translation.CUSTOM_CAPTION_VIDEO
            filename = await downloadvideocli(video_command)
            dur = round(duration(filename))
            med = InputMediaVideo(media=filename,
                                  duration=dur,
                                  caption=description,
                                  thumb=thumb_image,
                                  supports_streaming=True)

        if cb_data.startswith("docaudio"):
            filename = await downloadaudiocli(audio_command)
            med = InputMediaDocument(media=filename,
                                     caption=os.path.basename(filename),
                                     thumb=thumb_image)

        if cb_data.startswith("docvideo"):
            description = Translation.CUSTOM_CAPTION_DOC
            filename = await downloadvideocli(video_command)
            dur = round(duration(filename))
            med = InputMediaDocument(media=filename,
                                     caption=description,
                                     thumb=thumb_image)

        if med:
            loop.create_task(send_file(bot, update, med))

        else:
            print("med not found")

######################################### CB Data query for Bot Settings ###############################################
    else:
        # Callback Data Check (for bot settings)
        if cb_data.startswith(
            ("close", "view_thumb", "del_thumb", "conf_thumb", "start_help",
             "settings", "rename_doc", "convert_video", "d_copy", "v_copy",
             "clear_med")):
            if "close" in cb_data:
                await close_button(bot, update)
            elif "view_thumb" in cb_data:
                await view_thumbnail(bot, update)
            elif "del_thumb" in cb_data:
                await delete_thumbnail(bot, update)
            elif "conf_thumb" in cb_data:
                await del_thumb_confirm(bot, update)
            elif "start_help" in cb_data:
                await start_bot(bot, update)
            elif "settings" in cb_data:
                await bot_settings(bot, update)
            elif "rename_doc" in cb_data:
                await rename_file(bot, update)
            elif "convert_video" in cb_data:
                await convert_to_video(bot, update)
            elif "d_copy" in cb_data:
                await convert_to_doc_copy(bot, update)
            elif "v_copy" in cb_data:
                await convert_to_video_copy(bot, update)
            elif "clear_med" in cb_data:
                await clear_media(bot, update)
Exemplo n.º 15
0
async def open_stories(_, callback):
    username = callback.data.split(' ')[1]

    language = get_language(callback.from_user.id,
                            callback.from_user.language_code)

    key = f"{callback.message.chat.id}_{callback.message.message_id}"

    profile: Profile = cached_profiles.get(key)
    right_user_id = cached_ids.get(key)

    if profile is None or right_user_id is None:
        await callback.answer(get_message(language, "errors/no_cached_post"),
                              show_alert=True)
        await callback.edit_message_text("", reply_markup="")
        return

    if callback.from_user.id != right_user_id:
        await callback.answer(get_message(language, 'errors/wrong_id'),
                              show_alert=True)
        return

    iterator: StoriesIterator = cached_stories.get(key)

    if iterator is None:
        user = get_user_id(username)

        if "username" not in user:
            await callback.answer(get_message(language, "errors/fail"))
            return

        stories = _request_story(user["user_id"])

        if stories == "private_account":
            await callback.answer(
                get_message(language, "errors/private_account"))
            return

        if stories == "no_stories":
            await callback.answer(get_message(language, "errors/no_stories"))
            return

        iterator = StoriesIterator(stories, username)

        cached_stories[key] = iterator

    await callback.answer()

    story: Story = iterator.next(
    ) if iterator.index != -1 else iterator.collection[iterator.index]

    caption = format_date(story.taken_at)

    keyboard = create_keyboard_stories(iterator.username,
                                       len(iterator.collection),
                                       language,
                                       from_profile=True)

    media = InputMediaVideo(
        story.url
    ) if story.type_story == "mp4/video/boomerang" else InputMediaPhoto(
        story.url)
    media.caption = caption

    await callback.edit_message_media(media, reply_markup=keyboard)
Exemplo n.º 16
0
async def anime_episode(bot: Amime, callback: CallbackQuery):
    message = callback.message
    chat = message.chat
    user = callback.from_user
    lang = callback._lang

    anime_id = int(callback.matches[0].group(1))
    season = int(callback.matches[0].group(2))
    number = int(callback.matches[0].group(3))
    subtitled = bool(int(callback.matches[0].group(4)))
    language = callback.matches[0].group(5)
    page = int(callback.matches[0].group(6))

    if str(user.id) not in EPISODES.keys():
        EPISODES[str(user.id)] = {}
    if str(anime_id) not in EPISODES[str(user.id)].keys():
        EPISODES[str(user.id)][str(anime_id)] = {}

    chat.cancel_listener()

    episode = EPISODES[str(user.id)][str(anime_id)]

    episode_db = await Episodes.get_or_none(
        anime=anime_id,
        season=season,
        number=number,
        language=language,
        subtitled=subtitled,
    )
    if episode_db is not None:
        if not ("id" in episode.keys() and episode["id"] == episode_db.id):
            episode["id"] = episode_db.id
            episode["video"] = episode_db.file_id
            episode["name"] = episode_db.name
            episode["notes"] = episode_db.notes
            episode["duration"] = episode_db.duration
            episode["unified_until"] = episode_db.unified_until

            EPISODES[str(user.id)][str(anime_id)] = episode
    elif number == -1:
        EPISODES[str(user.id)][str(anime_id)] = {}
        episode = EPISODES[str(user.id)][str(anime_id)]

        episodes = await Episodes.filter(
            anime=anime_id,
            season=season,
            language=language,
            subtitled=subtitled,
        )
        episodes = sorted(episodes, key=lambda episode: episode.number)
        if len(episodes) > 0:
            number = episodes[-1].number + 1
        else:
            number = 1

    episode["subtitled"] = subtitled

    async with anilist.AsyncClient() as client:
        anime = await client.get(anime_id, "anime")

        if anime is None:
            return

        logger.debug(
            "%s is editing/adding episode %s of the anime %s (%s)",
            user.first_name,
            number,
            anime_id,
            language,
        )

        text = lang.manage_episode_text
        text += f"\n<b>{anime.title.romaji}</b> (<code>{anime.title.native}</code>)\n"

        buttons = []

        if "name" in episode.keys() and len(episode["name"]) > 0:
            text += f"\n<b>{lang.name}</b>: <code>{episode['name']}</code>"
            buttons.append((
                f"✏️ {lang.name}",
                f"manage episode edit name {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))
        else:
            buttons.append((
                f"➕ {lang.name}",
                f"manage episode edit name {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))

        if season > 0:
            text += f"\n<b>{lang.season}</b>: <code>{season}</code>"

        if number != -1:
            episode_number = str(number)
            if "unified_until" in episode.keys() and int(
                    episode["unified_until"]) > 0:
                episode_number += f"-{episode['unified_until']}"
            text += f"\n<b>{lang.episode}</b>: <code>{episode_number}</code>"
            buttons.append((
                f"✏️ {lang.episode}",
                f"manage episode edit number {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))
        else:
            buttons.append((
                f"➕ {lang.episode}",
                f"manage episode edit number {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))

        if "video" in episode.keys():
            buttons.append((
                f"✏️ {lang.video}",
                f"manage episode edit video {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))
        else:
            buttons.append((
                f"➕ {lang.video}",
                f"manage episode edit video {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))

        if "duration" in episode.keys():
            text += f"\n<b>{lang.duration}</b>: <code>{episode['duration']}m</code>"
            buttons.append((
                f"✏️ {lang.duration}",
                f"manage episode edit duration {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))
        else:
            buttons.append((
                f"➕ {lang.duration}",
                f"manage episode edit duration {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))

        text += f"\n<b>{lang.language}</b>: <code>{lang.strings[language]['LANGUAGE_NAME']}</code>"

        if "notes" in episode.keys() and len(episode["notes"]) > 0:
            text += f"\n<b>{lang.notes}</b>: <i>{episode['notes']}</i>"
            buttons.append((
                f"✏️ {lang.notes}",
                f"manage episode edit notes {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))
        else:
            buttons.append((
                f"➕ {lang.notes}",
                f"manage episode edit notes {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))

        keyboard = array_chunk(buttons, 2)

        buttons = []
        if number != -1 and "video" in episode.keys():
            episode["number"] = number
            buttons.append((
                lang.confirm_button,
                f"manage episode save {anime_id} {season} {int(subtitled)} {language} {page}",
            ))

        if "id" in episode.keys():
            buttons.append((
                lang.del_button,
                f"manage episode delete {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ))

        buttons.append((
            lang.back_button,
            f"manage anime {anime_id} {season} {int(subtitled)} {language} {page}",
        ))

        keyboard += array_chunk(buttons, 2)

        if "video" in episode.keys():
            file_id = False
            if isinstance(episode["video"], str) and len(episode["video"]) > 0:
                file_id = episode["video"]
            elif isinstance(episode["video"], Video):
                file_id = episode["video"].file_id

            if file_id is not False:
                try:
                    await callback.edit_message_media(
                        InputMediaVideo(
                            file_id,
                            caption=text,
                        ),
                        reply_markup=ikb(keyboard),
                    )
                    return
                except BaseException:
                    pass
        await callback.edit_message_media(
            InputMediaPhoto(
                f"https://img.anili.st/media/{anime_id}",
                caption=text,
            ),
            reply_markup=ikb(keyboard),
        )
Exemplo n.º 17
0
    async def ytdl_callback(_, c_q: CallbackQuery):
        startTime = time()
        inline_mode = True
        u_id = c_q.from_user.id
        if u_id not in Config.OWNER_ID and u_id not in Config.SUDO_USERS:
            return await c_q.answer("𝘿𝙚𝙥𝙡𝙤𝙮 𝙮𝙤𝙪𝙧 𝙤𝙬𝙣 𝙐𝙎𝙀𝙍𝙂𝙀-𝙓",
                                    show_alert=True)
        choice_id = c_q.matches[0].group(2)
        i_q_id = c_q.matches[0].group(3)
        callback_continue = "Downloading Video Please Wait..."
        callback_continue += f"\n\nFormat Code : {choice_id}"
        await c_q.answer(callback_continue, show_alert=True)
        upload_msg = await userge.send_message(Config.LOG_CHANNEL_ID,
                                               "Uploading...")
        yt_code = c_q.matches[0].group(1)
        yt_url = f"https://www.youtube.com/watch?v={yt_code}"
        try:
            await c_q.edit_message_caption(
                caption=
                (f"Video is now being ⬇️ Downloaded, for progress see:\nLog Channel:  [<b>click here</b>]({upload_msg.link})"
                 f"\n\n🔗  [<b>Link</b>]({yt_url})\n🆔  <b>Format Code</b> : {choice_id}"
                 ),
                reply_markup=None,
            )
        except MessageIdInvalid:
            inline_mode = False
            todelete = STORE_DATA.get(i_q_id)
            if todelete:
                bad_msg = await userge.get_messages(todelete["chat_id"],
                                                    todelete["msg_id"])
                await bad_msg.delete()
                upload_msg = await userge.send_message(todelete["chat_id"],
                                                       "Uploading ...")

        retcode = await _tubeDl(yt_url, startTime, choice_id)
        if retcode != 0:
            return await upload_msg.edit(str(retcode))
        _fpath = ""
        for _path in glob.glob(
                os.path.join(Config.DOWN_PATH, str(startTime), "*")):
            if not _path.lower().endswith((".jpg", ".png", ".webp")):
                _fpath = _path
        if not _fpath:
            await upload_msg.err("nothing found !")
            return
        uploaded_vid = await upload(upload_msg, Path(_fpath))
        if not inline_mode:
            return
        refresh_vid = await userge.bot.get_messages(Config.LOG_CHANNEL_ID,
                                                    uploaded_vid.message_id)
        f_id, f_ref = get_file_id_and_ref(refresh_vid)
        video_thumb = None
        if refresh_vid.video.thumbs:
            video_thumb = await userge.bot.download_media(
                refresh_vid.video.thumbs[0].file_id)
        else:
            video_thumb = download(get_ytthumb(yt_code))

        await c_q.edit_message_media(
            media=InputMediaVideo(
                media=f_id,
                file_ref=f_ref,
                thumb=video_thumb,
                caption=f"📹  <b>[{uploaded_vid.caption}]({yt_url})</b>",
                supports_streaming=True,
            ),
            reply_markup=None,
        )
        await uploaded_vid.delete()
async def youtube_dl_call_back(bot, update, cb_data):
    LOGGER.info(update)
    # youtube_dl extractors
    tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|")
    #
    current_user_id = update.message.reply_to_message.from_user.id
    current_touched_user_id = update.from_user.id
    if current_user_id != current_touched_user_id:
        return False, None
    user_working_dir = os.path.join(TMP_DOWNLOAD_DIRECTORY,
                                    str(current_user_id))
    # create download directory, if not exist
    if not os.path.isdir(user_working_dir):
        await bot.delete_messages(
            chat_id=update.message.chat.id,
            message_ids=[
                update.message.message_id,
                update.message.reply_to_message.message_id,
            ],
            revoke=True)
        return
    save_ytdl_json_path = user_working_dir + \
        "/" + str("ytdleech") + ".json"
    try:
        with open(save_ytdl_json_path, "r", encoding="utf8") as f_d:
            response_json = json.load(f_d)
        os.remove(save_ytdl_json_path)
    except FileNotFoundError:
        await bot.delete_messages(
            chat_id=update.message.chat.id,
            message_ids=[
                update.message.message_id,
                update.message.reply_to_message.message_id,
            ],
            revoke=True)
        return False
    #
    response_json = response_json[0]
    # TODO: temporary limitations
    LOGGER.info(response_json)
    #
    youtube_dl_url = response_json.get("webpage_url")
    LOGGER.info(youtube_dl_url)
    #
    custom_file_name = "%(title)s.%(ext)s"
    # https://superuser.com/a/994060
    LOGGER.info(custom_file_name)
    #
    await update.message.edit_caption(caption="trying to download")
    description = "@PyroGramBot"
    if "fulltitle" in response_json:
        description = response_json["fulltitle"][0:1021]
        # escape Markdown and special characters
    #
    tmp_directory_for_each_user = os.path.join(TMP_DOWNLOAD_DIRECTORY,
                                               str(update.from_user.id))
    if not os.path.isdir(tmp_directory_for_each_user):
        os.makedirs(tmp_directory_for_each_user)
    download_directory = tmp_directory_for_each_user
    download_directory = os.path.join(tmp_directory_for_each_user,
                                      custom_file_name)
    command_to_exec = []
    if tg_send_type == "audio":
        command_to_exec = [
            "youtube-dl",
            "-c",
            "--prefer-ffmpeg",
            "--extract-audio",
            "--add-metadata",
            "--embed-thumbnail",
            "--audio-format",
            youtube_dl_ext,
            "--audio-quality",
            youtube_dl_format,
            youtube_dl_url,
            "-o",
            download_directory,
            # "--external-downloader", "aria2c"
        ]
    else:
        # command_to_exec = ["youtube-dl", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", "--recode-video", "mp4", "-k", youtube_dl_url, "-o", download_directory]
        minus_f_format = youtube_dl_format
        if "youtu" in youtube_dl_url:
            for for_mat in response_json["formats"]:
                format_id = for_mat.get("format_id")
                if format_id == youtube_dl_format:
                    acodec = for_mat.get("acodec")
                    vcodec = for_mat.get("vcodec")
                    if acodec == "none" or vcodec == "none":
                        minus_f_format = youtube_dl_format + "+bestaudio"
                    break
        command_to_exec = [
            "youtube-dl",
            "-c",
            # "--embed-subs",
            "-f",
            minus_f_format,
            "--hls-prefer-ffmpeg",
            youtube_dl_url,
            "-o",
            download_directory,
            # "--external-downloader", "aria2c"
        ]
    #
    command_to_exec.append("--no-warnings")
    # command_to_exec.append("--quiet")
    command_to_exec.append("--restrict-filenames")
    #
    if "hotstar" in youtube_dl_url:
        command_to_exec.append("--geo-bypass-country")
        command_to_exec.append("IN")
    LOGGER.info(command_to_exec)
    start = datetime.now()
    t_response, e_response = await run_command(command_to_exec)
    # LOGGER.info(e_response)
    # LOGGER.info(t_response)
    ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output."
    if e_response and ad_string_to_replace in e_response:
        error_message = e_response.replace(ad_string_to_replace, "")
        await update.message.edit_caption(caption=error_message)
        return False, None
    if t_response:
        # LOGGER.info(t_response)
        # os.remove(save_ytdl_json_path)
        end_one = datetime.now()
        time_taken_for_download = (end_one - start).seconds
        dir_contents = os.listdir(tmp_directory_for_each_user)
        # dir_contents.sort()
        await update.message.edit_caption(
            f"found {len(dir_contents)} files"
            f"\n Download took {time_taken_for_download} seconds"
            "\n Trying to Upload, now ...")
        LOGGER.info(dir_contents)
        #
        for single_file in dir_contents:
            local_file_name = os.path.join(tmp_directory_for_each_user,
                                           single_file)
            thumb = await is_thumb_image_exists(local_file_name)
            # caption_str = os.path.basename(local_file_name)
            metadata = extractMetadata(createParser(local_file_name))
            duration = 0
            artist = ""
            title = ""
            if metadata.has("duration"):
                duration = metadata.get("duration").seconds
            if metadata.has("title"):
                title = metadata.get("title")
            if metadata.has("artist"):
                artist = metadata.get("artist")
            width, height = 0, 0
            if thumb is not None:
                metadata = extractMetadata(createParser(thumb))
                if metadata.has("height"):
                    height = metadata.get("height")
                if metadata.has("width"):
                    height = metadata.get("width")
            if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")):
                await update.message.edit_media(
                    media=InputMediaVideo(media=local_file_name,
                                          thumb=thumb,
                                          caption=description,
                                          parse_mode="html",
                                          width=width,
                                          height=height,
                                          duration=duration,
                                          supports_streaming=True))
            elif local_file_name.upper().endswith(
                ("MP3", "M4A", "M4B", "FLAC", "WAV")):
                await update.message.edit_media(media=InputMediaAudio(
                    media=local_file_name,
                    thumb=thumb,
                    caption=description,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title)
                                                # quote=True,
                                                )
            else:
                await update.message.edit_media(media=InputMediaDocument(
                    media=local_file_name,
                    thumb=thumb,
                    caption=description,
                    parse_mode="html")
                                                # quote=True,
                                                )
        #
        try:
            shutil.rmtree(tmp_directory_for_each_user)
        except:
            pass
Exemplo n.º 19
0
async def upload_single_file(message, local_file_name, caption_str, from_user,
                             edit_media):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    sent_message = None
    start_time = time.time()
    #
    thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails",
                                      str(from_user) + ".jpg")
    LOGGER.info(thumbnail_location)
    #
    try:
        message_for_progress_display = message
        if not edit_media:
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(
                    os.path.basename(local_file_name)))
        if local_file_name.upper().endswith(
            ("WEBM", "MP4")) and not local_file_name.upper().startswith(
                ("KDG")):
            metadata = extractMetadata(createParser(local_file_name))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            thumb_image_path = None
            if os.path.exists(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            else:
                thumb_image_path = None
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send video
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          width=width,
                                          height=height,
                                          duration=duration,
                                          supports_streaming=True)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        elif local_file_name.upper().endswith(
            ("MP3", "M4A", "M4B", "FLAC", "WAV")):
            metadata = extractMetadata(createParser(local_file_name))
            duration = 0
            title = ""
            artist = ""
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            if metadata.has("title"):
                title = metadata.get("title")
            if metadata.has("artist"):
                artist = metadata.get("artist")
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          duration=duration,
                                          performer=artist,
                                          title=title)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        else:
            base_file_name = os.path.basename(local_file_name)
            base_new_name = os.path.splitext(base_file_name)[0]
            extension_new_name = os.path.splitext(base_file_name)[1]
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(media=local_file_name,
                                             thumb=thumb,
                                             caption=caption_str,
                                             parse_mode="html")
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=local_file_name,
                    # quote=True,
                    thumb=thumb,
                    caption=caption_str,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))

            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        await message_for_progress_display.edit_text("**FAILED**\n" + str(e))
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    os.remove(local_file_name)
    return sent_message
Exemplo n.º 20
0
async def upload_single_file(path, message, force_edit,database=None,thumb_image_path=None,user_msg=None):
    if database is not None:
        if database.get_cancel_status(message.chat_id,message.id):
            # add os remove here
            return None
    if not os.path.exists(path):
        return None
    
    file_name = os.path.basename(path)
    caption_str = ""
    caption_str += "<code>"
    caption_str += file_name
    caption_str += "</code>"

    if user_msg is None:
        user_msg = await message.get_reply_message()

    force_docs = get_val("FORCE_DOCUMENTS")
    if user_msg is not None:
        force_docs = user_db.get_var("FORCE_DOCUMENTS",user_msg.sender_id)
    
    # Avoid Flood in Express
    await asyncio.sleep(int(get_val("EDIT_SLEEP_SECS"))+5)

    metadata = extractMetadata(createParser(path))
    
    if metadata is not None:
        # handle none for unknown
        metadata = metadata.exportDictionary()
        try:
            mime = metadata.get("Common").get("MIME type")
        except:
            mime = metadata.get("Metadata").get("MIME type")

        ftype = mime.split("/")[0]
        ftype = ftype.lower().strip()
    else:
        ftype = "unknown"

    thonmsg = message
    message = await message.client.pyro.get_messages(message.chat_id, message.id)
    tout = get_val("EDIT_SLEEP_SECS")
    sent_message = None
    start_time = time.time()
    #
    if user_msg is not None:
        dis_thumb = user_db.get_var("DISABLE_THUMBNAIL", user_msg.sender_id)
        if dis_thumb is False or dis_thumb is None:
            thumb_image_path = user_db.get_thumbnail(user_msg.sender_id)
            if not thumb_image_path:
                thumb_image_path = None
    #
    try:
        message_for_progress_display = message
        if not force_edit:
            data = "upcancel {} {} {}".format(message.chat.id,message.message_id,user_msg.sender_id)
            markup = InlineKeyboardMarkup([[InlineKeyboardButton("Cancel Upload", callback_data=data.encode("UTF-8"))]])
            message_for_progress_display = await message.reply_text(
                "📤 **Starting upload of** `{}`".format(os.path.basename(path)),
                reply_markup=markup
            )
        
        if ftype == "video" and not force_docs:
            metadata = extractMetadata(createParser(path))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            if thumb_image_path is None:
                thumb_image_path = await thumb_manage.get_thumbnail(path)
                # get the correct width, height, and duration for videos greater than 10MB

            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            
            # send video
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        width=width,
                        height=height,
                        duration=duration,
                        supports_streaming=True,
                        caption=caption_str
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    caption=caption_str,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        f"💠 Uploading {os.path.basename(path)}",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        elif ftype == "audio" and not force_docs:
            metadata = extractMetadata(createParser(path))
            duration = 0
            title = ""
            artist = ""
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            if metadata.has("title"):
                title = metadata.get("title")
            if metadata.has("artist"):
                artist = metadata.get("artist")
            
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(
                        media=path,
                        thumb=thumb,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title,
                        caption=caption_str
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=path,
                    # quote=True,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    caption=caption_str,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=(
                        f"💠 Uploading {os.path.basename(path)}",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
        else:
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if force_edit and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(
                        media=path,
                        caption=caption_str,
                        thumb=thumb,
                        parse_mode="html"
                    )
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=path,
                    # quote=True,
                    thumb=thumb,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    caption=caption_str,
                    progress_args=(
                        f"💠 Uploading {os.path.basename(path)}",
                        message_for_progress_display,
                        start_time,
                        tout,
                        thonmsg.client.pyro,
                        message,
                        database,
                        markup
                    )
                )
            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        if str(e).find("cancel") != -1:
            torlog.info("Canceled an upload lol")
            try:
                await message_for_progress_display.edit(f"Failed to upload {e}")
            except:pass
        else:
            try:
                await message_for_progress_display.edit(f"Failed to upload {e}")
            except:pass
            torlog.exception("IN Pyro upload")
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    #os.remove(path)
    if sent_message is None:
        return None
    sent_message = await thonmsg.client.get_messages(sent_message.chat.id, ids=sent_message.message_id)
    return sent_message
Exemplo n.º 21
0
async def anime_episode(bot: Amime, callback: CallbackQuery):
    user = callback.from_user
    lang = callback._lang

    anime_id = int(callback.matches[0].group(1))
    season = int(callback.matches[0].group(2))
    number = int(callback.matches[0].group(3))

    async with anilist.AsyncClient() as client:
        anime = await client.get(anime_id, "anime")

        if anime is None:
            return

        text = f"<b>{anime.title.romaji}</b> (<code>{anime.title.native}</code>)\n"

        user_db = await Users.get(id=user.id)
        language = user_db.language_anime
        subtitled = user_db.subtitled_anime

        episodes = await Episodes.filter(anime=anime_id,
                                         season=season,
                                         language=language,
                                         subtitled=subtitled)
        episodes = sorted(episodes, key=lambda episode: episode.number)
        all_episodes = await Episodes.filter(anime=anime_id,
                                             language=language,
                                             subtitled=subtitled)
        all_episodes = sorted(all_episodes, key=lambda episode: episode.number)

        episode = await Episodes.get_or_none(
            anime=anime_id,
            season=season,
            number=number,
            language=language,
            subtitled=subtitled,
        )
        if episode is not None:
            await Viewed.get_or_create(user=user.id,
                                       item=episode.id,
                                       type="anime")

            keyboard = [[await get_watched_button(lang, user, episode.id)]]

            if len(episode.name) > 0:
                text += f"\n<b>{lang.name}</b>: <code>{episode.name}</code>"

            if episode.season > 0:
                text += f"\n<b>{lang.season}</b>: <code>{episode.season}</code>"

            episode_number = f"{episode.number}"
            if episode.unified_until > 0:
                episode_number += f"-{episode.unified_until}"
            text += f"\n<b>{lang.episode}</b>: <code>{episode_number}</code>"
            text += f"\n<b>{lang.duration}</b>: <code>{episode.duration}m</code>"
            text += f"\n<b>{lang.language}</b>: <code>{lang.strings[episode.language]['LANGUAGE_NAME']}</code>"

            if len(episode.added_by) > 0:
                if not episode.added_by.isdecimal():
                    text += f"\n<b>{lang.added_by}</b>: <b>{episode.added_by}</b>"

            if len(episode.notes) > 0:
                text += f"\n<b>{lang.notes}</b>: <i>{episode.notes}</i>"

            viewed = await Viewed.filter(item=episode.id, type="anime")
            text += f"\n\n<b>{len(viewed)} {lang.views.lower()}</b>"

            previous_button = await get_previous_episode_button(
                lang, episodes, all_episodes, anime_id, season, number,
                language)
            next_button = await get_next_episode_button(
                lang, episodes, all_episodes, anime_id, season, number)
            if not (previous_button[0] == lang.dot_button
                    and next_button[0] == lang.dot_button):
                keyboard.append([previous_button, next_button])

            keyboard.append([(
                lang.report_button,
                f"report episode {anime_id} {season} {number} -1",
            )])

            if anime.format.lower() == "movie":
                keyboard.append([(
                    lang.back_button,
                    f"anime {anime_id} {user.id}",
                )])
            else:
                keyboard.append([(
                    lang.back_button,
                    f"episodes {anime_id} {season} {math.ceil(number / (5 * 3))}",
                )])

            await callback.edit_message_media(
                InputMediaVideo(
                    episode.file_id,
                    caption=text,
                ),
                reply_markup=ikb(keyboard),
            )
async def catch_youtube_dldata(c, q):
    cb_data = q.data
    # caption = q.message.caption
    user_id = q.from_user.id
    # Callback Data Assigning
    media_type, send_as, format_id, av_codec, video_id = cb_data.split("|")
    LOGGER.info(cb_data)

    filext = "%(title)s.%(ext)s"
    userdir = os.path.join(os.getcwd(), Config.DOWNLOAD_DIR, str(user_id),
                           video_id)

    if not os.path.isdir(userdir):
        os.makedirs(userdir)
    await q.edit_message_reply_markup(
        InlineKeyboardMarkup(
            [[InlineKeyboardButton("Downloading...", callback_data="down")]]))
    filepath = os.path.join(userdir, filext)
    # await q.edit_message_reply_markup([[InlineKeyboardButton("Processing..")]])

    fetch_media, caption = await yt_download(video_id, media_type, av_codec,
                                             format_id, filepath)
    if not fetch_media:
        await q.message.reply_text(caption)
        shutil.rmtree(userdir, ignore_errors=True)
        await q.message.delete()
        return
    else:
        LOGGER.info(os.listdir(userdir))
        for content in os.listdir(userdir):
            if ".jpg" not in content:
                file_name = os.path.join(userdir, content)

    thumb = os.path.join(userdir, video_id + ".jpg")
    width = height = 0
    if os.path.isfile(thumb):
        width, height = width_and_height(thumb)
    else:
        thumb = None

    duration = media_duration(file_name)
    if send_as == "Audio":
        med = InputMediaAudio(
            media=file_name,
            thumb=thumb,
            duration=duration,
            caption=caption,
            title=caption,
        )

    elif send_as == "Video":
        med = InputMediaVideo(
            media=file_name,
            thumb=thumb,
            width=width,
            height=height,
            duration=duration,
            caption=caption,
            supports_streaming=True,
        )

    else:
        med = InputMediaDocument(
            media=file_name,
            thumb=thumb,
            caption=caption,
        )

    if med:
        loop = asyncio.get_event_loop()
        loop.create_task(send_file(c, q, med, video_id, userdir))
    else:
        LOGGER.info("Media not found")
Exemplo n.º 23
0
 async def ytdl_download_callback(c_q: CallbackQuery):
     yt_code = c_q.matches[0].group(1)
     choice_id = c_q.matches[0].group(2)
     downtype = c_q.matches[0].group(3)
     if str(choice_id).isdigit():
         choice_id = int(choice_id)
         if choice_id == 0:
             await c_q.answer("🔄  Processing...", show_alert=False)
             await c_q.edit_message_reply_markup(
                 reply_markup=(await download_button(yt_code)))
             return
     startTime = time()
     choice_str, disp_str = get_choice_by_id(choice_id, downtype)
     media_type = "Video" if downtype == "v" else "Audio"
     callback_continue = f"Downloading {media_type} Please Wait..."
     callback_continue += f"\n\nFormat Code : {disp_str}"
     await c_q.answer(callback_continue, show_alert=True)
     upload_msg = await userge.send_message(Config.LOG_CHANNEL_ID,
                                            "Uploading...")
     yt_url = BASE_YT_URL + yt_code
     await c_q.edit_message_text(text=(
         f"**⬇️ Downloading {media_type} ...**"
         f"\n\n🔗  [<b>Link</b>]({yt_url})\n🆔  <b>Format Code</b> : {disp_str}"
     ), )
     if downtype == "v":
         retcode = await _tubeDl(url=yt_url,
                                 starttime=startTime,
                                 uid=choice_str)
     else:
         retcode = await _mp3Dl(url=yt_url,
                                starttime=startTime,
                                uid=choice_str)
     if retcode != 0:
         return await upload_msg.edit(str(retcode))
     _fpath = ""
     thumb_pic = None
     for _path in glob.glob(
             os.path.join(Config.DOWN_PATH, str(startTime), "*")):
         if _path.lower().endswith((".jpg", ".png", ".webp")):
             thumb_pic = _path
         else:
             _fpath = _path
     if not _fpath:
         await upload_msg.err("nothing found !")
         return
     if not thumb_pic and downtype == "v":
         thumb_pic = str(download(await get_ytthumb(yt_code)))
     uploaded_media = await upload(
         upload_msg,
         path=Path(_fpath),
         callback=c_q,
         custom_thumb=thumb_pic,
         log=False,
     )
     refresh_vid = await userge.bot.get_messages(Config.LOG_CHANNEL_ID,
                                                 uploaded_media.message_id)
     f_id = get_file_id(refresh_vid)
     if downtype == "v":
         await c_q.edit_message_media(media=(InputMediaVideo(
             media=f_id,
             caption=f"📹  <b>[{uploaded_media.caption}]({yt_url})</b>",
         )), )
     else:  # Audio
         await c_q.edit_message_media(media=(InputMediaAudio(
             media=f_id,
             caption=f"🎵  <b>[{uploaded_media.caption}]({yt_url})</b>",
         )), )
Exemplo n.º 24
0
async def upload_single_file(message, local_file_name, caption_str, from_user,
                             edit_media):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    sent_message = None
    start_time = time.time()
    #
    thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails",
                                      str(from_user) + ".jpg")
    LOGGER.info(thumbnail_location)
    #
    try:
        message_for_progress_display = message
        if not edit_media:
            message_for_progress_display = await message.reply_text(
                "starting upload of {}".format(
                    os.path.basename(local_file_name)))
        if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")):
            metadata = extractMetadata(createParser(local_file_name))
            duration = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            #
            width = 0
            height = 0
            thumb_image_path = None
            if os.path.exists(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            else:
                thumb_image_path = await take_screen_shot(
                    local_file_name,
                    os.path.dirname(os.path.abspath(local_file_name)),
                    (duration / 2))
                # get the correct width, height, and duration for videos greater than 10MB
                if os.path.exists(thumb_image_path):
                    metadata = extractMetadata(createParser(thumb_image_path))
                    if metadata.has("width"):
                        width = metadata.get("width")
                    if metadata.has("height"):
                        height = metadata.get("height")
                    # resize image
                    # ref: https://t.me/PyrogramChat/44663
                    # https://stackoverflow.com/a/21669827/4723940
                    Image.open(thumb_image_path).convert("RGB").save(
                        thumb_image_path)
                    img = Image.open(thumb_image_path)
                    # https://stackoverflow.com/a/37631799/4723940
                    img.resize((320, height))
                    img.save(thumb_image_path, "JPEG")
                    # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
            #
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send video
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaVideo(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          width=width,
                                          height=height,
                                          duration=duration,
                                          supports_streaming=True)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_video(
                    video=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    width=width,
                    height=height,
                    thumb=thumb,
                    supports_streaming=True,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        elif local_file_name.upper().endswith(
            ("MP3", "M4A", "M4B", "FLAC", "WAV")):
            metadata = extractMetadata(createParser(local_file_name))
            duration = 0
            title = ""
            artist = ""
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            if metadata.has("title"):
                title = metadata.get("title")
            if metadata.has("artist"):
                artist = metadata.get("artist")
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            # send audio
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaAudio(media=local_file_name,
                                          thumb=thumb,
                                          caption=caption_str,
                                          parse_mode="html",
                                          duration=duration,
                                          performer=artist,
                                          title=title)
                    # quote=True,
                )
            else:
                sent_message = await message.reply_audio(
                    audio=local_file_name,
                    # quote=True,
                    caption=caption_str,
                    parse_mode="html",
                    duration=duration,
                    performer=artist,
                    title=title,
                    thumb=thumb,
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
        else:
            thumb_image_path = None
            if os.path.isfile(thumbnail_location):
                thumb_image_path = await copy_file(
                    thumbnail_location,
                    os.path.dirname(os.path.abspath(local_file_name)))
            # if a file, don't upload "thumb"
            # this "diff" is a major derp -_- 😔😭😭
            thumb = None
            if thumb_image_path is not None and os.path.isfile(
                    thumb_image_path):
                thumb = thumb_image_path
            #
            # send document
            if edit_media and message.photo:
                sent_message = await message.edit_media(
                    media=InputMediaDocument(media=local_file_name,
                                             thumb=thumb,
                                             caption=caption_str,
                                             parse_mode="html")
                    # quote=True,
                )
            else:
                sent_message = await message.reply_document(
                    document=local_file_name,
                    # quote=True,
                    thumb=thumb,
                    caption=caption_str,
                    parse_mode="html",
                    disable_notification=True,
                    # reply_to_message_id=message.reply_to_message.message_id,
                    progress=progress_for_pyrogram,
                    progress_args=("trying to upload",
                                   message_for_progress_display, start_time))
            if thumb is not None:
                os.remove(thumb)
    except Exception as e:
        await message_for_progress_display.edit_text("**FAILED**\n" + str(e))
    else:
        if message.message_id != message_for_progress_display.message_id:
            await message_for_progress_display.delete()
    # os.remove(local_file_name)
    return sent_message
Exemplo n.º 25
0
async def upload_single_file(message, local_file_name, caption_str, from_user,
                             edit_media):

    base_file_name = os.path.basename(local_file_name)
    if len(base_file_name) > 64 and base_file_name.lower().startswith(
        ("@dramaost", "[d&o]")):
        status_message = await message.reply_text("Renaming start")
        h = base_file_name
        c_h = local_file_name
        out_dir = os.path.dirname(os.path.abspath(local_file_name))
        g = f"opus opus2.0 aac aac2.0 ddp5.1 ddp2.0 ddp2 h264 h.264 x264 10bit 2017 2018 2019 2020 2021 nf webdl web-dl webrip webhd web-hd web-rip".split(
            " ")
        c = 0
        f = h.lower()
        f = re.sub("_", '.', f)
        f = re.sub("web.dl", 'webdl', f)
        if f[:3] == "d&o":
            f = re.sub("d&o", '[d&o]', f)
        for i in g:
            if len(f) <= 64:
                break
            if re.search(i, f):
                f = re.sub("." + i, '', f)
        if len(f) > 64:
            f = re.sub("@dramaost.", '', f)
        p = f.split('.')
        s = '.'.join(i.capitalize() for i in p)
        s = re.sub("Nf", 'NF', s)
        s = re.sub("Web-dl", 'WEB-DL', s)
        s = re.sub("Webdl", 'WEB-DL', s)
        s = re.sub("Webrip", 'WEBRip', s)
        s = re.sub("Sh3lby", 'SH3LBY', s)
        s = re.sub("sh3lby", 'SH3LBY', s)
        s = re.sub("ost", 'OST', s)
        s = re.sub("Mkv", 'mkv', s)
        s = re.sub("d&o", 'D&O', s)
        s = re.sub("D&o", 'D&O', s)
        s = re.sub("S01e", 'S01E', s)
        s = re.sub("S02e", 'S02E', s)
        s = re.sub("S03e", 'S03E', s)
        s = re.sub("S04e", 'S04E', s)
        s = re.sub("X265", 'x265', s)
        s = re.sub("X264", 'x264', s)
        out_file_name = os.path.join(out_dir, s)
        os.rename(local_file_name, out_file_name)
        local_file_name = out_file_name
        await status_message.edit(
            f"Old Name - <code>{c_h}</code>\n\nNew Name - <code>{local_file_name}</code>"
        )
    elif not base_file_name.lower().startswith(
        ("kdg")) and re.search('_', base_file_name.lower()):
        await message.reply_text(
            f"<code>{local_file_name}</code>\n\nfile name contain underscore please rename it"
        )
    else:
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        sent_message = None
        start_time = time.time()
        #
        thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails",
                                          str(from_user) + ".jpg")
        LOGGER.info(thumbnail_location)
        #
        try:
            message_for_progress_display = message
            if not edit_media:
                message_for_progress_display = await message.reply_text(
                    "starting upload of {}".format(
                        os.path.basename(local_file_name)))
            if local_file_name.upper().endswith(
                ("WEBM", "MP4")) and not local_file_name.upper().startswith(
                    ("KDG")):
                metadata = extractMetadata(createParser(local_file_name))
                duration = 0
                if metadata.has("duration"):
                    duration = metadata.get('duration').seconds
                #
                width = 0
                height = 0
                thumb_image_path = None
                if os.path.exists(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)))
                else:
                    thumb_image_path = await take_screen_shot(
                        local_file_name,
                        os.path.dirname(os.path.abspath(local_file_name)),
                        (duration / 2))
                    # get the correct width, height, and duration for videos greater than 10MB
                    if os.path.exists(thumb_image_path):
                        metadata = extractMetadata(
                            createParser(thumb_image_path))
                        if metadata.has("width"):
                            width = metadata.get("width")
                        if metadata.has("height"):
                            height = metadata.get("height")
                        # resize image
                        # ref: https://t.me/PyrogramChat/44663
                        # https://stackoverflow.com/a/21669827/4723940
                        Image.open(thumb_image_path).convert("RGB").save(
                            thumb_image_path)
                        img = Image.open(thumb_image_path)
                        # https://stackoverflow.com/a/37631799/4723940
                        img.resize((320, height))
                        img.save(thumb_image_path, "JPEG")
                        # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
                #
                thumb = None
                if thumb_image_path is not None and os.path.isfile(
                        thumb_image_path):
                    thumb = thumb_image_path
                # send video
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaVideo(media=local_file_name,
                                              thumb=thumb,
                                              caption=caption_str,
                                              parse_mode="html",
                                              width=width,
                                              height=height,
                                              duration=duration,
                                              supports_streaming=True)
                        # quote=True,
                    )
                else:
                    sent_message = await message.reply_video(
                        video=local_file_name,
                        # quote=True,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        width=width,
                        height=height,
                        thumb=thumb,
                        supports_streaming=True,
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))
                if thumb is not None:
                    os.remove(thumb)
            elif local_file_name.upper().endswith(
                ("MP3", "M4A", "M4B", "FLAC", "WAV")):
                metadata = extractMetadata(createParser(local_file_name))
                duration = 0
                title = ""
                artist = ""
                if metadata.has("duration"):
                    duration = metadata.get('duration').seconds
                if metadata.has("title"):
                    title = metadata.get("title")
                if metadata.has("artist"):
                    artist = metadata.get("artist")
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)))
                thumb = None
                if thumb_image_path is not None and os.path.isfile(
                        thumb_image_path):
                    thumb = thumb_image_path
                # send audio
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaAudio(media=local_file_name,
                                              thumb=thumb,
                                              caption=caption_str,
                                              parse_mode="html",
                                              duration=duration,
                                              performer=artist,
                                              title=title)
                        # quote=True,
                    )
                else:
                    sent_message = await message.reply_audio(
                        audio=local_file_name,
                        # quote=True,
                        caption=caption_str,
                        parse_mode="html",
                        duration=duration,
                        performer=artist,
                        title=title,
                        thumb=thumb,
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))
                if thumb is not None:
                    os.remove(thumb)
            else:
                base_file_name = os.path.basename(local_file_name)
                base_new_name = os.path.splitext(base_file_name)[0]
                extension_new_name = os.path.splitext(base_file_name)[1]
                thumb_image_path = None
                if os.path.isfile(thumbnail_location):
                    thumb_image_path = await copy_file(
                        thumbnail_location,
                        os.path.dirname(os.path.abspath(local_file_name)))
                # if a file, don't upload "thumb"
                # this "diff" is a major derp -_- 😔😭😭
                thumb = None
                if thumb_image_path is not None and os.path.isfile(
                        thumb_image_path):
                    thumb = thumb_image_path
                #
                # send document
                if edit_media and message.photo:
                    sent_message = await message.edit_media(
                        media=InputMediaDocument(media=local_file_name,
                                                 thumb=thumb,
                                                 caption=caption_str,
                                                 parse_mode="html")
                        # quote=True,
                    )
                elif base_file_name.lower().startswith(("@dramaost", "[d&o]")):
                    for l, s in zip(name_ids, chan_ids):
                        h = l.lower()
                        b = base_file_name.lower()
                        if re.search(h, b):
                            m4 = f"<b>Join: {s}</b>"
                            caption_str = re.sub(".mkv",
                                                 f".mkv</code>\n\n{m4}",
                                                 caption_str)
                            break
                    sent_message = await message.reply_document(
                        document=local_file_name,
                        # quote=True,
                        thumb=thumb,
                        caption=caption_str,
                        parse_mode="html",
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))

                else:
                    sent_message = await message.reply_document(
                        document=local_file_name,
                        # quote=True,
                        thumb=thumb,
                        caption=caption_str,
                        parse_mode="html",
                        disable_notification=True,
                        # reply_to_message_id=message.reply_to_message.message_id,
                        progress=progress_for_pyrogram,
                        progress_args=("trying to upload",
                                       message_for_progress_display,
                                       start_time))

                if thumb is not None:
                    os.remove(thumb)
        except Exception as e:
            await message_for_progress_display.edit_text("**FAILED**\n" +
                                                         str(e))
        else:
            if message.message_id != message_for_progress_display.message_id:
                await message_for_progress_display.delete()
        os.remove(local_file_name)
        return sent_message