Exemplo n.º 1
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.reply("Processing ...")
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        start = datetime.now()
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(
                        d, t, mone, c_time,
                        "Downloading This File Onto Your Xiaomi Redmi 7 Device..."
                    )))
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
        else:
            end = datetime.now()
            ms = (end - start).seconds
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
    elif input_str:
        start = datetime.now()
        url = input_str
        file_name = os.path.basename(url)
        to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
        if "|" in input_str:
            url, file_name = input_str.split("|")
        url = url.strip()
        file_name = file_name.strip()
        downloaded_file_name = os.path.join(to_download_directory, file_name)
        async with aiohttp.ClientSession() as session:
            c_time = time.time()
            await download_coroutine(session, url, downloaded_file_name, mone,
                                     c_time)
        end = datetime.now()
        ms = (end - start).seconds
        if os.path.exists(downloaded_file_name):
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
        else:
            await mone.edit("Incorrect URL\n {}".format(input_str))
    else:
        await mone.edit("Reply to a message to download to my local server.")
Exemplo n.º 2
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    replied = event.reply_to_msg_id
    if not replied:
        await event.edit("LMAO no one's gonna help you, if u use .help now then u **Gey**")
        await borg.send_file(event.chat_id, "CAADAQADhAAD3gkwRviGxMVn5813FgQ")
            
        return
    
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    await event.edit("He he, let me use my skills")
    c_time = time.time()
    reply_message = await event.get_reply_message()
    dls = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, event, c_time, "trying to download")
                )
            )
    dls_loc = os.path.join(Config.TMP_DOWNLOAD_DIRECTORY, os.path.basename(dls))
    if dls.endswith(".tgs"):
        await event.edit("OMG, an Animated sticker ⊙_⊙, lemme do my bleck megik...")
        png_file = os.path.join(Config.TMP_DOWNLOAD_DIRECTORY, "meme.png")
        cmd = f"lottie_convert.py --frame 0 -if lottie -of PNG {dls_loc} {png_file}"
        stdout, stderr = (await runcmd(cmd))[:2]
        os.remove(dls_loc)
        if not os.path.lexists(png_file):
            await event.edit("This sticker is Gey, i won't memify it ≧ω≦")
            raise Exception(stdout + stderr)
        dls_loc = png_file
    if dls.endswith(".mp4"):
        await event.edit("Look it's GF. Oh, no it's just a Gif ")
        jpg_file = os.path.join(Config.TMP_DOWNLOAD_DIRECTORY, "meme.jpg")
        await take_screen_shot(dls_loc, 0, jpg_file)
        os.remove(dls_loc)
        if not os.path.lexists(jpg_file):
            await event.edit("This Gif is Gey (。ì _ í。), won't memify it.")
            return
        dls_loc = jpg_file
    await event.edit("Decoration Time ≧∇≦, I'm an Artist")
    webp_file = await draw_meme_text(dls_loc, input_str)
    await borg.send_file(event.chat_id, webp_file, reply_to=event.reply_to_msg_id)
                              
    await event.delete()
    os.remove(webp_file)
Exemplo n.º 3
0
async def _(event):
    if event.fwd_from:
        return
    thumb = None
    await event.edit(f"Downloading file to local machine..\nThis may take a while depending on the file size.")
    time.sleep(1)
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        start = datetime.now()
        file_name = input_str
        reply_message = await event.get_reply_message()
        to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
        await event.edit(f"Download complete!\nRenaming downloaded file to {input_str}..")
        time.sleep(0.25)
        downloaded_file_name = os.path.join(to_download_directory, file_name)
        downloaded_file_name = await borg.download_media(
            reply_message,
            downloaded_file_name
        )
        end = datetime.now()
        ms_one = (end - start).seconds
        await event.edit("File renamed successfully!\nUploading renamed file..\nThis may take a while depending on the file size.")
        time.sleep(.35)
        if os.path.exists(downloaded_file_name):
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                downloaded_file_name,
                force_document=True,
                supports_streaming=False,
                allow_cache=False,
                reply_to=event.message.id,
                thumb=thumb,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, event, c_time, "trying to upload")
                )
            )
            end_two = datetime.now()
            os.remove(downloaded_file_name)
            ms_two = (end_two - end).seconds
            total_ms = int(ms_one) + int(ms_two)
            await event.edit(f"Uploaded renamed file ```{input_str}``` in {ms_two} seconds!")

        else:
            await event.edit("File {} not found.".format(input_str))
    else:
        await event.edit("Syntax // .rnupload file.name as reply to a Telegram media")
Exemplo n.º 4
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, mone, c_time, "trying to download")
                )
            )
            directory_name = downloaded_file_name
            await event.edit("Finish downloading to my local")
            to_upload_file = directory_name
            output = await create_archive(to_upload_file) 
            is_zip = False
            if is_zip:
                check_if_file = await create_archive(to_upload_file)
                if check_if_file is not None:
                    to_upload_file = check_if_file
            await borg.send_file(
                event.chat_id,
                output,
                caption="TAR By @By_Azade",
                force_document=True,
                allow_cache=False,
                reply_to=event.message.id,
            )
            try:
                os.remove(output)
                os.remove(output)
            except:
                    pass
            await event.edit("Task Completed")
            await asyncio.sleep(3)
            await event.delete()
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    elif input_str:
        directory_name = input_str
        
        await event.edit("Local file compressed to `{}`".format(output))
Exemplo n.º 5
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, mone, c_time, "trying to download")
                )
            )
            directory_name = downloaded_file_name
            await event.edit("Finish downloading to my local")
            command_to_exec = [
                "7z",
                "e",
                "-o" + extracted,
                directory_name]
            sp = subprocess.Popen(
                command_to_exec, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
            await borg.send_file(
                event.chat_id,
                directory_name + ".zip",
                caption="Zipped By @By_Azade",
                force_document=True,
                allow_cache=False,
                reply_to=event.message.id,
            )
            try:
                os.remove(directory_name + ".zip")
                os.remove(directory_name)
            except:
                pass
            await event.edit("Task Completed")
            await asyncio.sleep(3)
            await event.delete()
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    elif input_str:
        directory_name = input_str

        await event.edit("Local file compressed to `{}`".format(directory_name + ".zip"))
Exemplo n.º 6
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, mone, c_time, "trying to download")
                )
            )
            directory_name = downloaded_file_name
            await event.edit("creating 7z archive, please wait..")
            # patoolib.create_archive(directory_name + '.7z',directory_name)
            patoolib.create_archive(
                directory_name + ".7z",
                (directory_name,
                 Config.TMP_DOWNLOAD_DIRECTORY))
            # patoolib.create_archive("/content/21.yy Avrupa (1).pdf.zip",("/content/21.yy Avrupa (1).pdf","/content/"))
            await borg.send_file(
                event.chat_id,
                directory_name + ".7z",
                caption="7z archived By @By_Azade",
                force_document=True,
                allow_cache=False,
                reply_to=event.message.id,
            )
            try:
                os.remove(directory_name + ".7z")
                os.remove(directory_name)
            except BaseException:
                pass
            await event.edit("Task Completed")
            await asyncio.sleep(3)
            await event.delete()
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    elif input_str:
        directory_name = input_str

        await event.edit("Local file compressed to `{}`".format(directory_name + ".7z"))
Exemplo n.º 7
0
async def pinterst_vid_img(event):
    x = await event.edit("`Progressing...`")
    url = event.pattern_match.group(1)
    get_url = get_download_url(url)
    j = download_video(get_url)
    thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg"

    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)

    metadata = extractMetadata(createParser(j))
    duration = 0

    if metadata.has("duration"):
        duration = metadata.get('duration').seconds
        width = 0
        height = 0
        thumb = None

    if os.path.exists(thumb_image_path):
        thumb = thumb_image_path
    else:
        thumb = await take_screen_shot(j, os.path.dirname(os.path.abspath(j)),
                                       (duration / 2))

    c_time = time.time()
    await event.client.send_file(
        event.chat_id,
        j,
        thumb=thumb,
        caption="`pinterest video uploaded by` @By_Azade",
        force_document=False,
        allow_cache=False,
        reply_to=event.message.id,
        attributes=[
            DocumentAttributeVideo(duration=duration,
                                   w=width,
                                   h=height,
                                   round_message=False,
                                   supports_streaming=True)
        ],
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, event, c_time, "trying to upload")))
    await event.delete()
    await x.delete()
    os.remove(Config.TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4')
    os.remove(thumb_image_path)
Exemplo n.º 8
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to download"))
            )
            directory_name = downloaded_file_name
            await event.edit("Finish downloading to my local")
            zipfile.ZipFile(directory_name + '.zip', 'w',
                            zipfile.ZIP_DEFLATED).write(directory_name)
            await borg.send_file(
                event.chat_id,
                directory_name + ".zip",
                caption="Zipped By SnapDragon",
                force_document=True,
                allow_cache=False,
                reply_to=event.message.id,
            )
            try:
                os.remove(directory_name + ".zip")
                os.remove(directory_name)
            except:
                pass
            await event.edit("task Completed")
            await asyncio.sleep(3)
            await event.delete()
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    elif input_str:
        directory_name = input_str
        zipfile.ZipFile(directory_name + '.zip', 'w',
                        zipfile.ZIP_DEFLATED).write(directory_name)
        await event.edit(
            "Local file compressed to `{}`".format(directory_name + ".zip"))
Exemplo n.º 9
0
async def _(event):
    if event.fwd_from:
        return
    thumb = None
    if os.path.exists(thumb_image_path):
        thumb = thumb_image_path
    await event.edit(
        "Rename & Upload in process 🙄🙇‍♂️🙇‍♂️🙇‍♀️ It might take some time if file size is big"
    )
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        start = datetime.now()
        file_name = input_str
        reply_message = await event.get_reply_message()
        to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
        downloaded_file_name = os.path.join(to_download_directory, file_name)
        downloaded_file_name = await borg.download_media(
            reply_message, downloaded_file_name)
        end = datetime.now()
        ms_one = (end - start).seconds
        if os.path.exists(downloaded_file_name):
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                downloaded_file_name,
                force_document=True,
                supports_streaming=False,
                allow_cache=False,
                reply_to=event.message.id,
                thumb=thumb,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, event, c_time, "trying to upload")))
            end_two = datetime.now()
            os.remove(downloaded_file_name)
            ms_two = (end_two - end).seconds
            await event.edit(
                "Downloaded in {} seconds. Uploaded in {} seconds.".format(
                    ms_one, ms_two))
        else:
            await event.edit("File Not Found {}".format(input_str))
    else:
        await event.edit(
            "Syntax // .rnupload file.name as reply to a Telegram media")
Exemplo n.º 10
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.edit("`Unzipping...`")
    input_str = event.pattern_match.group(1)
    if input_str:
        if os.path.exists(input_str):
            downloaded_file_name = input_str
            start = datetime.now()
            with zipfile.ZipFile(downloaded_file_name, "r") as zip_ref:
                zip_ref.extractall(Config.TMP_DOWNLOAD_DIRECTORY)
            end = datetime.now()
            ms = (end - start).seconds
            await event.edit(
                f"unzipped and stored to `{downloaded_file_name[:-4]}` \n**Time Taken :** `{ms} seconds`"
            )
        else:
            await event.edit(f"I can't find that path `{input_str}`")
    else:
        if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
            os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
        if event.reply_to_msg_id:
            start = datetime.now()
            reply_message = await event.get_reply_message()
            try:
                c_time = time.time()
                downloaded_file_name = await borg.download_media(
                    reply_message,
                    Config.TMP_DOWNLOAD_DIRECTORY,
                    progress_callback=lambda d, t: asyncio.get_event_loop().
                    create_task(
                        progress(d, t, mone, c_time, "trying to download")),
                )
            except Exception as e:  # pylint:disable=C0103,W0703
                await mone.edit(str(e))
            await event.edit("Unzipping now")
            with zipfile.ZipFile(downloaded_file_name, "r") as zip_ref:
                zip_ref.extractall(Config.TMP_DOWNLOAD_DIRECTORY)
            end = datetime.now()
            ms = (end - start).seconds
            await event.edit(
                f"unzipped and stored to `{downloaded_file_name[:-4]}` \n**Time Taken :** `{ms} seconds`"
            )
            os.remove(downloaded_file_name)
Exemplo n.º 11
0
async def download(event):
    global reponame
    reponame = Config.GIT_REPO_NAME
    if reponame is None:
        reponame = event.pattern_match.group(1)
    if not reponame and Config.GIT_REPO_NAME is None:
        await event.edit(
            "`Please ADD a proper repo name from Vars or specify your repo name as in the example: .commit <reponame>`"
        )
        return
    if event.fwd_from:
        return
    if Config.GITHUB_ACCESS_TOKEN is None:
        await event.edit("`Please ADD a proper access token from github.com`")
        return
    if Config.GIT_USER_NAME is None:
        await event.edit("`Please ADD a proper github username from vars`")
        return
    mone = await event.reply("**__Processing...__**")
    if not os.path.isdir(GIT_TEMP_DIR):
        os.makedirs(GIT_TEMP_DIR)
    start = datetime.now()
    reply_message = await event.get_reply_message()
    try:
        c_time = time.time()
        downloaded_file_name = await borg.download_media(
            reply_message,
            GIT_TEMP_DIR,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, mone, c_time, "**__trying to download__**")))
    except Exception as e:
        await mone.edit(str(e))
    else:
        end = datetime.now()
        ms = (end - start).seconds
        await event.delete()
        await mone.edit("**__Downloaded to `{}` in {} seconds.__**".format(
            downloaded_file_name, ms))
        await mone.edit("**__Committing to Github....__**")
        await git_commit(downloaded_file_name, mone)
Exemplo n.º 12
0
async def pinterst_img_vid(event):
    x = await event.edit("`Progressing...`")
    url = event.pattern_match.group(1)
    get_url = get_download_url(url)
    j = download_image(get_url)

    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    c_time = time.time()
    await event.client.send_file(
        event.chat_id,
        j,
        caption="`pinterest image uploaded by` @By_Azade",
        force_document=False,
        allow_cache=False,
        reply_to=event.message.id,
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, event, c_time, "trying to upload")))
    await event.delete()
    await x.delete()
    os.remove(Config.TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg')
Exemplo n.º 13
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    mone = await event.edit("Zipping in progress....")
    if event.reply_to_msg_id:
        if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
            os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(d, t, mone, c_time, "trying to download")),
            )
            directory_name = downloaded_file_name
            await event.edit("Finish downloading to my local")
            zipfile.ZipFile(directory_name + ".zip", "w",
                            zipfile.ZIP_DEFLATED).write(directory_name)
            os.remove(directory_name)
            cat = directory_name + ".zip"
            await event.edit(f"compressed successfully into `{cat}`")
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    elif input_str:
        if not os.path.exists(input_str):
            await event.edit(
                f"There is no such directory or file with the name `{input_str}` check again"
            )
            return
        filePaths = zipdir(input_str)
        zip_file = zipfile.ZipFile(input_str + ".zip", "w")
        with zip_file:
            for file in filePaths:
                zip_file.write(file)
        await event.edit("Local file compressed to `{}`".format(input_str +
                                                                ".zip"))
Exemplo n.º 14
0
async def ff_mpeg_save_cmd(event):
    if event.fwd_from:
        return
    if not os.path.exists(FF_MPEG_DOWN_LOAD_MEDIA_PATH):
        if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
            os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
        if event.reply_to_msg_id:
            start = datetime.now()
            reply_message = await event.get_reply_message()
            try:
                c_time = time.time()
                downloaded_file_name = await borg.download_media(
                    reply_message,
                    FF_MPEG_DOWN_LOAD_MEDIA_PATH,
                    progress_callback=lambda d, t: asyncio.get_event_loop(
                    ).create_task(
                        progress(d, t, event, c_time, "trying to download")))
            except Exception as e:  # pylint:disable=C0103,W0703
                event.client.send_message(event.chat_id, str(e))
            else:
                end = datetime.now()
                ms = (end - start).seconds
                h = await event.client.send_message(
                    event.chat_id, "Downloaded to `{}` in {} seconds.".format(
                        downloaded_file_name, ms))
                await asyncio.sleep(4)
                await h.delete()
        else:
            f = await event.client.send_message(
                event.chat_id, "Reply to a Telegram media file")
            await asyncio.sleep(4)
            await f.delete()
    else:
        g = await event.client.send_message(
            event.chat_id,
            "a media file already exists in path. Please remove the media and try again! use `.exec rm -rf uniborg.media.ffmpeg`"
        )
        await asyncio.sleep(8)
        await g.delete()
Exemplo n.º 15
0
async def download(url, msg, id):
    idnum = id
    args = url
    event = msg
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                "/app/",
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, event, c_time, "Downloading IPA.."))
            )
        except Exception as e:
            await event.edit(str(e))
        else:
            await event.edit(f"Downloaded IPA to `{downloaded_file_name}`.")
            ipa_split = downloaded_file_name.split("/")
            ipa_full = ipa_split[-1]
            ipa_noext = ipa_full[:-4]
            ipa = f"{ipa_noext}_{idnum}.ipa"
            os.rename(ipa_full, ipa)
            return ipa
    elif args.startswith("http"):
        if not args.endswith(".ipa"):
            return await event.edit(
                "Unsupported link!\nPlease provide a direct link to the IPA file."
            )
        ipa_split = args.split("/")
        ipa = ipa_split[-1]
        ipa_noext = ipa[:-4]
        ipa = f"{ipa_noext}_{idnum}.ipa"
        await event.edit(f"Downloading IPA: `{ipa}`")
        request = requests.get(args)
        with open(ipa, "wb") as f:
            f.write(request.content)
        return ipa
Exemplo n.º 16
0
async def upload_zip(up):
    if not os.path.isdir(ZIP_DOWNLOAD_DIRECTORY):
        await up.edit("`Files not found`")
        return
    mone = await up.edit("`Zipping File...`")
    input_str = up.pattern_match.group(1)
    curdate = today.strftime("%m%d%y")
    title = str(input_str) if input_str else "zipfile" + f"{curdate}"
    zipf = zipfile.ZipFile(title + '.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir(ZIP_DOWNLOAD_DIRECTORY, zipf)
    zipf.close()
    c_time = time.time()
    await bot.send_file(
        up.chat_id,
        title + ".zip",
        force_document=True,
        allow_cache=False,
        reply_to=up.message.id,
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, mone, c_time, "[UPLOADING]", input_str)),
    )
    os.rmdir(ZIP_DOWNLOAD_DIRECTORY)
    await up.delete()
Exemplo n.º 17
0
async def download(event):
    if event.fwd_from:
        return
    if Config.GITHUB_ACCESS_TOKEN is None:
        await event.edit("`Please ADD Proper Access Token from github.com`")
        return
    if Config.GIT_REPO_NAME is None:
        await event.edit("`Please ADD Proper Github Repo Name of your userbot`"
                         )
        return
    mone = await event.reply("Processing ...")
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(GIT_TEMP_DIR):
        os.makedirs(GIT_TEMP_DIR)
    start = datetime.now()
    reply_message = await event.get_reply_message()
    try:
        c_time = time.time()
        downloaded_file_name = await borg.download_media(
            reply_message,
            GIT_TEMP_DIR,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(progress(d, t, mone, c_time, "trying to download")))
    except Exception as e:
        await mone.edit(str(e))
    else:
        end = datetime.now()
        ms = (end - start).seconds
        await event.delete()
        await mone.edit("Downloaded to `{}` in {} seconds.".format(
            downloaded_file_name, ms))
        await mone.edit("Committing to Github....")
        try:
            await git_commit(downloaded_file_name, mone)
        except:
            await mone.edit("`Please reply to a python module`")
Exemplo n.º 18
0
async def _(event):
    if event.fwd_from:
        return
    if not event.is_reply:
        await event.edit("Reply to a file to compress it.")
        return
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to download"))
            )
            directory_name = downloaded_file_name
            await event.edit(downloaded_file_name)
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
    zipfile.ZipFile(directory_name + '.zip', 'w',
                    zipfile.ZIP_DEFLATED).write(directory_name)
    await borg.send_file(
        event.chat_id,
        directory_name + ".zip",
        caption="Zipped By SnapDragon",
        force_document=True,
        allow_cache=False,
        reply_to=event.message.id,
    )
    await event.edit("DONE!!!")
    await asyncio.sleep(7)
    await event.delete()
Exemplo n.º 19
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.edit("Processing ...")
    input_str = event.pattern_match.group(1)
    thumb = None
    file_name = input_str
    if os.path.exists(file_name):
        if not file_name.endswith((".mkv", ".mp4", ".mp3", ".flac")):
            await mone.edit("Sorry. But I don't think {} is a streamable file."
                            .format(file_name) + " Please try again.\n" +
                            "**Supported Formats**: MKV, MP4, MP3, FLAC")
            return False
        if os.path.exists(thumb_image_path):
            thumb = thumb_image_path
        else:
            thumb = get_video_thumb(file_name, thumb_image_path)
        start = datetime.now()
        metadata = extractMetadata(createParser(file_name))
        duration = 0
        width = 0
        height = 0
        if metadata.has("duration"):
            duration = metadata.get('duration').seconds
        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")
        # Telegram only works with MP4 files
        # this is good, since with MKV files sent as streamable Telegram responds,
        # Bad Request: VIDEO_CONTENT_TYPE_INVALID
        c_time = time.time()
        try:
            await borg.send_file(
                event.chat_id,
                file_name,
                thumb=thumb,
                caption=input_str,
                force_document=False,
                allow_cache=False,
                reply_to=event.message.id,
                attributes=[
                    DocumentAttributeVideo(duration=duration,
                                           w=width,
                                           h=height,
                                           round_message=False,
                                           supports_streaming=True)
                ],
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to upload")))
        except Exception as e:
            await mone.edit(str(e))
        else:
            end = datetime.now()
            os.remove(input_str)
            ms = (end - start).seconds
            await mone.edit("Uploaded in {} seconds.".format(ms))
    else:
        await mone.edit("404: File Not Found")
Exemplo n.º 20
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.edit("Processing ...")
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    extracted = Config.TMP_DOWNLOAD_DIRECTORY + "extracted/"
    thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg"
    if not os.path.isdir(extracted):
        os.makedirs(extracted)
    if event.reply_to_msg_id:
        start = datetime.now()
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to download"))
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
        else:
            end = datetime.now()
            ms = (end - start).seconds
            await mone.edit("Stored the rar to `{}` in {} seconds.".format(
                downloaded_file_name, ms))

        patoolib.extract_archive(downloaded_file_name, outdir=extracted)
        filename = sorted(get_lst_of_files(extracted, []))
        #filename = filename + "/"
        await event.edit("Unraring now")
        # r=root, d=directories, f = files
        for single_file in filename:
            if os.path.exists(single_file):
                # https://stackoverflow.com/a/678242/4723940
                caption_rts = os.path.basename(single_file)
                force_document = False
                supports_streaming = True
                document_attributes = []
                if single_file.endswith((".mp4", ".mp3", ".flac", ".webm")):
                    metadata = extractMetadata(createParser(single_file))
                    duration = 0
                    width = 0
                    height = 0
                    if metadata.has("duration"):
                        duration = metadata.get('duration').seconds
                    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")
                    document_attributes = [
                        DocumentAttributeVideo(duration=duration,
                                               w=width,
                                               h=height,
                                               round_message=False,
                                               supports_streaming=True)
                    ]
                try:
                    await borg.send_file(
                        event.chat_id,
                        single_file,
                        caption=f"UnRarred `{caption_rts}`",
                        force_document=force_document,
                        supports_streaming=supports_streaming,
                        allow_cache=False,
                        reply_to=event.message.id,
                        attributes=document_attributes,
                        # progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                        #     progress(d, t, event, c_time, "trying to upload")
                        # )
                    )
                except Exception as e:
                    await borg.send_message(event.chat_id,
                                            "{} caused `{}`".format(
                                                caption_rts, str(e)),
                                            reply_to=event.message.id)
                    # some media were having some issues
                    continue
                os.remove(single_file)
        os.remove(downloaded_file_name)
    await asyncio.sleep(2)
    shutil.rmtree(Config.TMP_DOWNLOAD_DIRECTORY)
Exemplo n.º 21
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    reply_message = await event.get_reply_message()
    if reply_message is None:
        await event.edit("reply to a media to use the `nfc` operation.")
        return
    await event.edit("trying to download media file, to my local")
    try:
        start = datetime.now()
        c_time = time.time()
        downloaded_file_name = await borg.download_media(
            reply_message,
            Config.TMP_DOWNLOAD_DIRECTORY,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(progress(d, t, event, c_time, "indiriliyor")))
    except Exception as e:  # pylint:disable=C0103,W0703
        await event.edit(str(e))
    else:
        end = datetime.now()
        ms = (end - start).seconds
        await event.edit("Downloaded to `{}` in {} seconds.".format(
            downloaded_file_name, ms))
        new_required_file_name = ""
        new_required_file_caption = ""
        command_to_run = []
        force_document = False
        voice_note = False
        supports_streaming = False
        if input_str == "voice":
            new_required_file_caption = downloaded_file_name[12:-4] + ".opus"
            new_required_file_name = new_required_file_caption
            command_to_run = [
                "ffmpeg", "-i", downloaded_file_name, "-map", "0:a",
                "-codec:a", "libopus", "-b:a", "100k", "-vbr", "on",
                new_required_file_name
            ]
            voice_note = True
            supports_streaming = True
        elif input_str == "mp3":
            new_required_file_caption = downloaded_file_name[12:-4] + ".mp3"
            new_required_file_name = new_required_file_caption
            command_to_run = [
                "ffmpeg", "-i", downloaded_file_name, "-vn",
                new_required_file_name
            ]
            voice_note = False
            supports_streaming = True
        else:
            await event.edit("not supported")
            os.remove(downloaded_file_name)
            return
        logger.info(command_to_run)
        # TODO: re-write create_subprocess_exec 😉
        process = await asyncio.create_subprocess_exec(
            *command_to_run,
            # stdout must a pipe to be accessible as process.stdout
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        # Wait for the subprocess to finish
        stdout, stderr = await process.communicate()
        stderr.decode().strip()
        stdout.decode().strip()

        if os.path.exists(new_required_file_name):
            end_two = datetime.now()
            await borg.send_file(
                entity=event.chat_id,
                file=new_required_file_name,
                caption=new_required_file_caption,
                allow_cache=False,
                silent=True,
                force_document=force_document,
                voice_note=voice_note,
                supports_streaming=supports_streaming,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(progress(d, t, event, c_time, "yükleniyor..")))
            ms_two = (end_two - end).seconds
            os.remove(new_required_file_name)
            await asyncio.sleep(5)
            os.remove(downloaded_file_name)
            a = await event.edit(f"converted in {ms_two} seconds")
            await asyncio.sleep(5)
            await a.delete()
Exemplo n.º 22
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.reply("Processing ...")
    if CLIENT_ID is None or CLIENT_SECRET is None:
        await mone.edit(
            "This module requires credentials from https://da.gd/so63O. Aborting!"
        )
        return
    if Config.PRIVATE_GROUP_BOT_API_ID is None:
        await event.edit(
            "Please set the required environment variable `PRIVATE_GROUP_BOT_API_ID` for this plugin to work"
        )
        return
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    required_file_name = None
    start = datetime.now()
    if event.reply_to_msg_id and not input_str:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to download"))
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
            return False
        else:
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = downloaded_file_name
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = input_str
            await mone.edit("Found `{}` in {} seconds.".format(input_str, ms))
        else:
            await mone.edit(
                "File Not found in local server. Give me a file path :((")
            return False
    # logger.info(required_file_name)
    if required_file_name:
        #
        if Config.G_DRIVE_AUTH_TOKEN_DATA is not None:
            with open(G_DRIVE_TOKEN_FILE, "w") as t_file:
                t_file.write(Config.G_DRIVE_AUTH_TOKEN_DATA)
        # Check if token file exists, if not create it by requesting authorization code
        storage = None
        if not os.path.isfile(G_DRIVE_TOKEN_FILE):
            storage = await create_token_file(G_DRIVE_TOKEN_FILE, event)
        http = authorize(G_DRIVE_TOKEN_FILE, storage)
        # Authorize, get file parameters, upload file and print out result URL for download
        # http = authorize(G_DRIVE_TOKEN_FILE, None)
        file_name, mime_type = file_ops(required_file_name)
        # required_file_name will have the full path
        # Sometimes API fails to retrieve starting URI, we wrap it.
        try:
            g_drive_link = await upload_file(http, required_file_name,
                                             file_name, mime_type, mone,
                                             G_DRIVE_F_PARENT_ID)
            await mone.edit(f"Here is your Google Drive link: {g_drive_link}")
        except Exception as e:
            await mone.edit(f"Exception occurred while uploading to gDrive {e}"
                            )
    else:
        await mone.edit(
            "File Not found in local server. Give me a file path :((")
Exemplo n.º 23
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.edit("Processing ...")
    if Config.VERY_STREAM_LOGIN is None or Config.VERY_STREAM_KEY is None:
        await mone.edit("This module requires API key from https://verystream.com. Aborting!")
        return False
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    required_file_name = None
    start = datetime.now()
    if event.reply_to_msg_id and not input_str:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, mone, c_time, "trying to download")
                )
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
            return False
        else:
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = downloaded_file_name
            await mone.edit("Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = input_str
            await mone.edit("Found `{}` in {} seconds.".format(input_str, ms))
        else:
            await mone.edit("File Not found in local server. Give me a file path :((")
            return False
    # logger.info(required_file_name)
    if required_file_name:
        # required_file_name will have the full path
        file_name = os.path.basename(required_file_name)
        if "." in file_name:
            file_name = file_name.rsplit(".", maxsplit=1)[0]
        file_name = file_name + str(time.time())
        file_size = os.stat(required_file_name).st_size
        # https://stackoverflow.com/a/22058673/4723940
        sha_one_file_hash = get_sha_one_hash(required_file_name, 65536)
        # /* STEP 1: get upload_key */
        login = Config.VERY_STREAM_LOGIN
        key = Config.VERY_STREAM_KEY
        sha1 = sha_one_file_hash
        mime = magic.Magic(mime=True)
        step_zero_url = f"https://api.verystream.com/file/createfolder?login={login}&key={key}&name={file_name}"
        async with aiohttp.ClientSession() as session:
            resp_zero = await session.get(step_zero_url)
            step_zero_response_text = json.loads(await resp_zero.text())
            # logger.info(step_zero_response_text)
            if step_zero_response_text["status"] == 200:
                folder_id_e = step_zero_response_text["result"]["folderid"]
                await mone.edit(f"Created Folder with ID: {folder_id_e}")
                step_one_url = f"https://api.verystream.com/file/ul?login={login}&key={key}&sha1={sha1}&folder={folder_id_e}"
                resp = await session.get(step_one_url)
                # logger.info(resp.status)
                step_one_response_text = json.loads(await resp.text())
                # logger.info(step_one_response_text)
                if step_one_response_text["status"] == 200:
                    url = step_one_response_text["result"]["url"]
                    await mone.edit(f"Start Uploading to {url}")
                    start = datetime.now()
                    files = {"file1": (file_name, open(
                        required_file_name, "rb"))}
                    resp = requests.post(url, files=files)
                    step_two_response_text = resp.json()
                    # logger.info(step_two_response_text)
                    if step_two_response_text["status"] == 200:
                        output_str = json.dumps(
                            step_two_response_text["result"], sort_keys=True, indent=4)
                        stream_url = step_two_response_text["result"]["url"]
                        end = datetime.now()
                        ms = (end - start).seconds
                        await mone.edit(f"Obtained {stream_url} in {ms} seconds.\n{output_str}")
                        # cleanup
                        await event.delete()
                        try:
                            os.remove(required_file_name)
                        except:
                            pass
                    else:
                        await mone.edit(f"VeryStream returned {step_two_response_text['status']} => {step_two_response_text['msg']}, after STEP ONE")
                else:
                    await mone.edit(f"VeryStream returned {step_one_response_text['status']} => {step_one_response_text['msg']}, after STEP ONE")
            else:
                await mone.edit(f"VeryStream returned {step_zero_response_text['status']} => {step_zero_response_text['msg']}, after STEP INIT")
    else:
        await mone.edit("File Not found in local server. Give me a file path :((")
Exemplo n.º 24
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.edit("Processing ...")
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        start = datetime.now()
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await download_file(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to download"))
            )
            # downloaded_file_name = await borg.download_media(
            #     reply_message,
            #     Config.TMP_DOWNLOAD_DIRECTORY,
            #     progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            #         progress(d, t, mone, c_time, "trying to download")
            #     )
            # )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
        else:
            end = datetime.now()
            ms = (end - start).seconds
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
    elif input_str:
        start = datetime.now()
        url = input_str
        file_name = os.path.basename(url)
        to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
        if "|" in input_str:
            url, file_name = input_str.split("|")
        url = url.strip()
        file_name = file_name.strip()
        downloaded_file_name = os.path.join(to_download_directory, file_name)
        downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
        downloader.start(blocking=False)
        display_message = ""
        c_time = time.time()
        while not downloader.isFinished():
            total_length = downloader.filesize if downloader.filesize else None
            downloaded = downloader.get_dl_size()
            now = time.time()
            diff = now - c_time
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed()
            elapsed_time = round(diff) * 1000
            progress_str = "[{0}{1}]\nProgress: {2}%".format(
                ''.join(["█" for i in range(math.floor(percentage / 5))]),
                ''.join(["░" for i in range(20 - math.floor(percentage / 5))]),
                round(percentage, 2))
            estimated_total_time = downloader.get_eta(human=True)
            try:
                current_message = f"trying to download\n"
                current_message += f"URL: {url}\n"
                current_message += f"File Name: {file_name}\n"
                current_message += f"{progress_str}\n"
                current_message += f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n"
                current_message += f"ETA: {estimated_total_time}"
                if round(diff %
                         10.00) == 0 and current_message != display_message:
                    await mone.edit(current_message)
                    display_message = current_message
            except Exception as e:
                logger.info(str(e))
        end = datetime.now()
        ms = (end - start).seconds
        if os.path.exists(downloaded_file_name):
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
        else:
            await mone.edit("Incorrect URL\n {}".format(input_str))
    else:
        await mone.edit("Reply to a message to download to my local server.")
Exemplo n.º 25
0
async def download(dryb):
    """ For .gdrive command, upload files to google drive. """
    if not dryb.text[0].isalpha() and dryb.text[0] not in ("/", "#", "@", "!"):
        if dryb.fwd_from:
            return
        await dryb.edit("Processing ...")
        input_str = dryb.pattern_match.group(1)
        if CLIENT_ID is None or CLIENT_SECRET is None:
            return false
        if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
            os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
            required_file_name = None
        elif input_str:
            start = datetime.now()
            url = input_str
            file_name = os.path.basename(url)
            if "|" in input_str:
                url, file_name = input_str.split("|")
            url = url.strip()
            file_name = file_name.strip()
            downloaded_file_name = Config.TMP_DOWNLOAD_DIRECTORY + "" + file_name
            downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
            downloader.start(blocking=False)
            c_time = time.time()
            display_message = None
            while not downloader.isFinished():
                status = downloader.get_status().capitalize()
                total_length = downloader.filesize if downloader.filesize else None
                downloaded = downloader.get_dl_size()
                now = time.time()
                diff = now - c_time
                percentage = downloader.get_progress() * 100
                downloader.get_speed()
                round(diff) * 1000
                progress_str = "[{0}{1}]\nProgress: {2}%".format(
                    "".join(["●" for i in range(math.floor(percentage / 5))]),
                    "".join(
                        ["○" for i in range(20 - math.floor(percentage / 5))]),
                    round(percentage, 2),
                )
                estimated_total_time = downloader.get_eta(human=True)
                try:
                    current_message = f"{status}...\nURL: {url}\nFile Name: {file_name}\n{progress_str}\n{humanbytes(downloaded)} of {humanbytes(total_length)}\nETA: {estimated_total_time}"
                    if current_message != display_message:
                        await dryb.edit(current_message)
                        display_message = current_message
                        await asyncio.sleep(3)
                except Exception as e:
                    logger.info(str(e))
            end = datetime.now()
            ms = (end - start).seconds
            if downloader.isSuccessful():
                await dryb.edit(
                    "Downloaded to `{}` in {} seconds.\nNow Uploading to Google Drive..."
                    .format(downloaded_file_name, ms))
                required_file_name = downloaded_file_name
            else:
                await dryb.edit("Incorrect URL\n{}".format(url))
        elif dryb.reply_to_msg_id:
            start = datetime.now()
            try:
                c_time = time.time()
                downloaded_file_name = await dryb.client.download_media(
                    await dryb.get_reply_message(),
                    Config.TMP_DOWNLOAD_DIRECTORY,
                    progress_callback=lambda d, t: asyncio.get_event_loop(
                    ).create_task(
                        progress(d, t, dryb, c_time, "Downloading...")),
                )
            except Exception as e:  # pylint:disable=C0103,W0703
                await dryb.edit(str(e))
            else:
                end = datetime.now()
                required_file_name = downloaded_file_name
                ms = (end - start).seconds
                await dryb.edit(
                    "Downloaded to `{}` in {} seconds.\nNow Uploading to GDrive..."
                    .format(required_file_name, ms))

    if required_file_name:
        #
        if Config.G_DRIVE_AUTH_TOKEN_DATA is not None:
            with open(G_DRIVE_TOKEN_FILE, "w") as t_file:
                t_file.write(Config.G_DRIVE_AUTH_TOKEN_DATA)
        # Check if token file exists, if not create it by requesting
        # authorization code
        if not os.path.isfile(G_DRIVE_TOKEN_FILE):
            storage = await create_token_file(G_DRIVE_TOKEN_FILE, dryb)
            http = authorize(G_DRIVE_TOKEN_FILE, storage)
        # Authorize, get file parameters, upload file and print out result URL
        # for download
        http = authorize(G_DRIVE_TOKEN_FILE, None)
        file_name, mime_type = file_ops(required_file_name)
        # required_file_name will have the full path
        # Sometimes API fails to retrieve starting URI, we wrap it.
        try:
            g_drive_link = await upload_file(http, required_file_name,
                                             file_name, mime_type, dryb)
            await dryb.edit(
                f"File:`{required_file_name}`\nHas Successfully Uploaded to : [Google Drive]({g_drive_link})"
            )
        except Exception as e:
            await dryb.edit(
                f"Error while uploading to Google Drive\nError Code:\n`{e}`")
Exemplo n.º 26
0
async def _(event):
    if event.fwd_from:
        return
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    thumb = None
    if os.path.exists(thumb_image_path):
        thumb = thumb_image_path
    start = datetime.now()
    input_str = event.pattern_match.group(1)
    url = input_str
    file_name = os.path.basename(url)
    to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
    if "|" in input_str:
        url, file_name = input_str.split("|")
    url = url.strip()
    file_name = file_name.strip()
    downloaded_file_name = os.path.join(to_download_directory, file_name)
    downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
    downloader.start(blocking=False)
    display_message = ""
    c_time = time.time()
    while not downloader.isFinished():
        total_length = downloader.filesize if downloader.filesize else None
        downloaded = downloader.get_dl_size()
        now = time.time()
        diff = now - c_time
        percentage = downloader.get_progress() * 100
        speed = downloader.get_speed()
        elapsed_time = round(diff) * 1000
        progress_str = "[{0}{1}]\nProgress: {2}%".format(
            ''.join(["█" for i in range(math.floor(percentage / 5))]),
            ''.join(["░" for i in range(20 - math.floor(percentage / 5))]),
            round(percentage, 2))
        estimated_total_time = downloader.get_eta(human=True)
        try:
            current_message = f"Downloading......\n"
            current_message += f"URL: {url}\n"
            current_message += f"File Name: {file_name}\n"
            current_message += f"{progress_str}\n"
            current_message += f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n"
            current_message += f"ETA: {estimated_total_time}"
            if round(diff % 10.00) == 0 and current_message != display_message:
                await event.edit(current_message)
                display_message = current_message
        except Exception as e:
            logger.info(str(e))
    end = datetime.now()
    ms_dl = (end - start).seconds
    if downloader.isSuccessful():
        await event.edit("Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms_dl))
        if os.path.exists(downloaded_file_name):
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                downloaded_file_name,
                force_document=True,
                supports_streaming=False,
                allow_cache=False,
                reply_to=event.message.id,
                thumb=thumb,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, event, c_time, "trying to upload")
                )
            )
            end_two = datetime.now()
            os.remove(downloaded_file_name)
            ms_two = (end_two - end).seconds
            await event.edit("Downloaded in {} seconds. Uploaded in {} seconds.".format(ms_dl, ms_two))
        else:
            await event.edit("File Not Found {}".format(input_str))
    else:
        await mone.edit("Incorrect URL\n {}".format(input_str))
Exemplo n.º 27
0
async def _(event):
    if event.fwd_from:
        return
    await event.edit("Rename & Upload as Streamable in process 🙄🙇‍♂️🙇‍♂️🙇‍♀️ It might take some time if file size is big")
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        start = datetime.now()
        file_name = input_str
        reply_message = await event.get_reply_message()
        c_time = time.time()
        to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
        downloaded_file_name = os.path.join(to_download_directory, file_name)
        downloaded_file_name = await borg.download_media(
            reply_message,
            downloaded_file_name,
            progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                progress(d, t, event, c_time, "trying to download")
            )
        )
        end_one = datetime.now()
        ms_one = (end_one - start).seconds
        if os.path.exists(downloaded_file_name):
            thumb = None
            if os.path.exists(thumb_image_path):
                thumb = thumb_image_path
            start = datetime.now()
            metadata = extractMetadata(createParser(downloaded_file_name))
            duration = 0
            width = 0
            height = 0
            if metadata.has("duration"):
                duration = metadata.get('duration').seconds
            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")
            # Telegram only works with MP4 files
            # this is good, since with MKV files sent as streamable Telegram responds,
            # Bad Request: VIDEO_CONTENT_TYPE_INVALID
            c_time = time.time()
            try:
                await borg.send_file(
                    event.chat_id,
                    downloaded_file_name,
                    thumb=thumb,
                    caption=downloaded_file_name,
                    force_document=False,
                    allow_cache=False,
                    reply_to=event.message.id,
                    attributes=[
                        DocumentAttributeVideo(
                            duration=duration,
                            w=width,
                            h=height,
                            round_message=False,
                            supports_streaming=True
                        )
                    ],
                    progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                        progress(d, t, event, c_time, "trying to upload")
                    )
                )
            except Exception as e:
                await event.edit(str(e))
            else:
                end = datetime.now()
                os.remove(downloaded_file_name)
                ms_two = (end - end_one).seconds
                await event.edit("Downloaded in {} seconds. Uploaded in {} seconds.".format(ms_one, ms_two))
        else:
            await event.edit("File Not Found {}".format(input_str))
    else:
        await event.edit("Syntax // .rnstreamupload file.name as reply to a Telegram media")
Exemplo n.º 28
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.reply("Processing ...")
    if Config.MIRROR_ACE_API_KEY is None or Config.MIRROR_ACE_API_TOKEN is None:
        await mone.edit(
            "This module requires API key from https://ouo.io/My1jdU. Aborting!"
        )
        return False
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    required_file_name = None
    start = datetime.now()
    if event.reply_to_msg_id and not input_str:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to download"))
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
            return False
        else:
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = downloaded_file_name
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = input_str
            await mone.edit("Found `{}` in {} seconds.".format(input_str, ms))
        else:
            await mone.edit(
                "File Not found in local server. Give me a file path :((")
            return False
    # logger.info(required_file_name)
    if required_file_name:
        # required_file_name will have the full path
        file_name = os.path.basename(required_file_name)
        file_size = os.stat(required_file_name).st_size
        # /* STEP 1: get upload_key */
        step_one_url = "https://mirrorace.com/api/v1/file/upload"
        step_one_auth_params = {
            "api_key": Config.MIRROR_ACE_API_KEY,
            "api_token": Config.MIRROR_ACE_API_TOKEN
        }
        async with aiohttp.ClientSession() as session:
            resp = await session.post(step_one_url, data=step_one_auth_params)
            # logger.info(resp.status)
            if resp.status == 200:
                step_one_response_json = await resp.json()
                logger.info(step_one_response_json)
                if step_one_response_json["status"] == "success":
                    await mone.edit("Received Upload URL from MirrorAce. ...")
                    start = datetime.now()
                    # /* STEP 2: Upload file */
                    # step one: response vars
                    step_two_upload_url = step_one_response_json["result"][
                        "server_file"]
                    cTracker = step_one_response_json["result"]["cTracker"]
                    upload_key = step_one_response_json["result"]["upload_key"]
                    default_mirrors = step_one_response_json["result"][
                        "default_mirrors"]
                    max_chunk_size = step_one_response_json["result"][
                        "max_chunk_size"]
                    max_file_size = step_one_response_json["result"][
                        "max_file_size"]
                    max_mirrors = step_one_response_json["result"][
                        "max_mirrors"]

                    # check file size limit
                    if int(file_size) >= int(max_file_size):
                        await mone.edit(
                            f"File exceeds maximum file size allowed: {max_file_size}"
                        )
                        return False

                    # step two: setup
                    mirrors = default_mirrors
                    chunk_size = int(max_chunk_size)
                    step_two_params = {
                        "api_key": Config.MIRROR_ACE_API_KEY,
                        "api_token": Config.MIRROR_ACE_API_TOKEN,
                        "cTracker": cTracker,
                        "upload_key": upload_key,
                        "mirrors[]": mirrors,
                        # //these required vars will be added by buildMultiPartRequest function
                        # //'files' => $file,
                        # //'mirrors[1]' => 1,
                        # //'mirrors[2]' => 2,
                    }

                    # //range vars //for multi chunk upload
                    response = False

                    with open(required_file_name, "rb") as f_handle:
                        # start chunk upload
                        for chunk in iter((lambda: f_handle.read(chunk_size)),
                                          ""):
                            # for chunk in f_handle.read(chunk_size):
                            # print(chunk)
                            # while (i < chunks) and not while_error:
                            # chunk = f_handle.read(chunk_size)
                            if not chunk:
                                break
                            headers = {
                                "Content-Range":
                                str(len(chunk)),
                                "Content-Length":
                                str(len(step_two_params) + len(chunk)),
                                # "Content-Type": "multipart/form-data"
                            }

                            # https://github.com/aio-libs/aiohttp/issues/3571#issuecomment-456528924
                            response = requests.post(
                                step_two_upload_url,
                                files=[("files", (file_name, chunk))],
                                data=step_two_params,
                                # headers=headers
                            )
                            logger.info(response.content)

                    logger.info(response)
                    final_response = response.json()
                    if final_response["status"] == "success":
                        end = datetime.now()
                        ms = (end - start).seconds
                        final_url = final_response["result"]["url"]
                        await mone.edit(f"Added to {final_url} in {ms} seconds"
                                        )
                    else:
                        await mone.edit(
                            f"MirrorAce returned {final_response['status']} => {final_response['result']}"
                        )
                else:
                    await mone.edit(
                        f"MirrorAce returned {step_one_response_json['status']} => {step_one_response_json['result']}, after STEP TWO"
                    )
            else:
                await mone.edit(
                    f"MirrorAce returned {resp['status']} => {resp['result']}, after STEP ONE"
                )
    else:
        await mone.edit(
            "File Not found in local server. Give me a file path :((")
Exemplo n.º 29
0
async def magnet_download(event):
    if event.fwd_from:
        return
    if not os.path.exists(Config.FF_MPEG_DOWN_LOAD_MEDIA_PATH):
        await event.edit(
            f"a media file needs to be downloaded, and saved to the following path: `{Config.FF_MPEG_DOWN_LOAD_MEDIA_PATH}`"
        )
        return
    current_message_text = event.raw_text
    cmt = current_message_text.split(" ")
    logger.info(cmt)
    start = datetime.now()
    if len(cmt) == 3:
        # output should be video
        cmd, start_time, end_time = cmt
        o = await cult_small_video(Config.FF_MPEG_DOWN_LOAD_MEDIA_PATH,
                                   Config.TMP_DOWNLOAD_DIRECTORY, start_time,
                                   end_time)
        logger.info(o)
        try:
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                o,
                caption=" ".join(cmt[1:]),
                force_document=False,
                supports_streaming=True,
                allow_cache=False,
                # reply_to=event.message.id,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, event, c_time, "trying to upload")))
            os.remove(o)
        except Exception as e:
            logger.info(str(e))
    elif len(cmt) == 2:
        # output should be image
        cmd, start_time = cmt
        o = await take_screen_shot(Config.FF_MPEG_DOWN_LOAD_MEDIA_PATH,
                                   Config.TMP_DOWNLOAD_DIRECTORY, start_time)
        logger.info(o)
        try:
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                o,
                caption=" ".join(cmt[1:]),
                force_document=True,
                # supports_streaming=True,
                allow_cache=False,
                # reply_to=event.message.id,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, event, c_time, "trying to upload")))
            os.remove(o)
        except Exception as e:
            logger.info(str(e))
    else:
        await event.edit("RTFM")
        return
    end = datetime.now()
    ms = (end - start).seconds
    await event.edit(f"Completed Process in {ms} seconds")
Exemplo n.º 30
0
async def upload_google_photos(event):
    if event.fwd_from:
        return

    input_str = event.pattern_match.group(2)
    logger.info(input_str)

    if not event.reply_to_msg_id and not input_str:
        await event.edit(
            "©️ <b>[Forwarded from utubebot]</b>\nno one gonna help you 🤣🤣🤣🤣",
            parse_mode="html"
        )
        return

    token_file = TOKEN_FILE_NAME
    is_cred_exists, creds = await check_creds(
        token_file,
        event
    )
    if not is_cred_exists:
        await event.edit(
            "😏 <code>gphoto setup</code> first 😡😒😒",
            parse_mode="html"
        )

    service = build(
        "photoslibrary",
        "v1",
        http=creds.authorize(Http())
    )

    # create directory if not exists
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)

    file_path = None

    if input_str and os.path.exists(input_str):
        file_path = input_str

    elif not input_str:
        media_message = await event.client.get_messages(
            entity=event.chat_id,
            ids=event.reply_to_msg_id
        )

        c_time = time.time()
        file_path = await media_message.download_media(
            file=Config.TMP_DOWNLOAD_DIRECTORY,
            progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                progress(d, t, event, c_time, "trying to download")
            )
        )

    logger.info(file_path)

    if not file_path:
        await event.edit(
            "<b>[stop spamming]</b>",
            parse_mode="html"
        )
        return

    file_name, mime_type, file_size = file_ops(file_path)
    await event.edit(
        "file downloaded, "
        "gathering upload informations "
    )

    async with aiohttp.ClientSession() as session:
        headers = {
            "Content-Length": "0",
            "X-Goog-Upload-Command": "start",
            "X-Goog-Upload-Content-Type": mime_type,
            "X-Goog-Upload-File-Name": file_name,
            "X-Goog-Upload-Protocol": "resumable",
            "X-Goog-Upload-Raw-Size": str(file_size),
            "Authorization": "Bearer " + creds.access_token,
        }
        # Step 1: Initiating an upload session
        step_one_response = await session.post(
            f"{PHOTOS_BASE_URI}/v1/uploads",
            headers=headers,
        )

        if step_one_response.status != 200:
            await event.edit(
                (await step_one_response.text())
            )
            return

        step_one_resp_headers = step_one_response.headers
        logger.info(step_one_resp_headers)
        # Step 2: Saving the session URL

        real_upload_url = step_one_resp_headers.get(
            "X-Goog-Upload-URL"
        )
        logger.info(real_upload_url)
        upload_granularity = int(step_one_resp_headers.get(
            "X-Goog-Upload-Chunk-Granularity"
        ))
        logger.info(upload_granularity)
        # https://t.me/c/1279877202/74
        number_of_req_s = int((
            file_size / upload_granularity
        ))
        logger.info(number_of_req_s)

        async with aiofiles.open(
            file_path,
            mode="rb"
        ) as f_d:
            for i in range(number_of_req_s):
                current_chunk = await f_d.read(upload_granularity)

                headers = {
                    "Content-Length": str(len(current_chunk)),
                    "X-Goog-Upload-Command": "upload",
                    "X-Goog-Upload-Offset": str(i * upload_granularity),
                    "Authorization": "Bearer " + creds.access_token,
                }
                logger.info(i)
                logger.info(headers)
                response = await session.post(
                    real_upload_url,
                    headers=headers,
                    data=current_chunk
                )
                logger.info(response.headers)

                await f_d.seek(upload_granularity)
            # await f_d.seek(upload_granularity)
            current_chunk = await f_d.read(upload_granularity)
            # https://t.me/c/1279877202/74

            logger.info(number_of_req_s)
            headers = {
                "Content-Length": str(len(current_chunk)),
                "X-Goog-Upload-Command": "upload, finalize",
                "X-Goog-Upload-Offset": str(number_of_req_s * upload_granularity),
                "Authorization": "Bearer " + creds.access_token,
            }
            logger.info(headers)
            response = await session.post(
                real_upload_url,
                headers=headers,
                data=current_chunk
            )
            logger.info(response.headers)

        final_response_text = await response.text()
        logger.info(final_response_text)

    await event.edit(
        "uploaded to Google Photos, "
        "getting FILE URI 🤔🤔"
    )

    response_create_album = service.mediaItems().batchCreate(
        body={
            "newMediaItems": [{
                "description": "uploaded using @UniBorg v7",
                "simpleMediaItem": {
                    "fileName": file_name,
                    "uploadToken": final_response_text
                }
            }]
        }
    ).execute()
    logger.info(response_create_album)

    try:
        photo_url = response_create_album.get(
            "newMediaItemResults"
        )[0].get("mediaItem").get("productUrl")
        await event.edit(
            photo_url
        )
    except Exception as e:
        await event.edit(str(e))