Example #1
0
async def progress_status(gid, event, previous):
    global req_file
    try:
        file = aria2.get_download(gid)
        req_file = str(file.name)
        if not file.is_complete:
            if not file.error_message:
                msg = "**Leeching**: `"+str(file.name) + "`\n**Speed**: " + str(file.download_speed_string())+"\n**Progress**: "+str(file.progress_string(
                ))+"\n**Total Size**: "+str(file.total_length_string())+"\n**Status**: "+str(file.status)+"\n**ETA**:  "+str(file.eta_string())+"\n\n"
                if previous != msg:
                    await event.edit(msg)
                    previous = msg
            else:
                logger.info(str(file.error_message))
                await log("Error : `{}`".format(str(file.error_message)))
                return
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await progress_status(gid, event, previous)
        else:
            await event.edit(f"```{file.name}``` leeched successfully!")
            return
    except Exception as e:
        if " not found" in str(e) or "'file'" in str(e):
            await log(str(e))
            return await event.delete()
        elif " depth exceeded" in str(e):
            file.remove(force=True)
            await log(str(e))
        else:
            await log(str(e))
            return await event.delete()
Example #2
0
async def magnet_download(event):
    if event.fwd_from:
        return
    var = event.pattern_match.group(1)
    if not var:
        rep = event.get_reply_message()
        var = rep.text
    # print(var)
    uris = [var]
    # Add URL Into Queue
    try:
        download = aria2.add_uris(uris, options=None, position=None)
    except Exception as e:
        await log(str(e))
        return await event.delete()

    gid = download.gid
    complete = None
    await progress_status(gid=gid, event=event, previous=None)
    file = aria2.get_download(gid)
    if file.followed_by_ids:
        new_gid = await check_metadata(gid)
        await progress_status(gid=new_gid, event=event, previous=None)
    while complete != True:
        file = aria2.get_download(gid)
        complete = file.is_complete
        try:
            msg = "**Leeching:** " + str(file.name) + "\n**Speed:** " + str(
                file.download_speed_string()) + "\n**Progress:** " + str(
                    file.progress_string()) + "\n**Total Size:** " + str(
                        file.total_length_string()) + "\n**ETA:**  " + str(
                            file.eta_string()) + "\n\n"
            await event.edit(msg)
            await asyncio.sleep(10)
        except Exception as e:
            await log(str(e))
            pass

    await event.edit(f"```{file.name}``` leeched successfully!")
Example #3
0
async def leech2drive(event):
    if event.fwd_from:
        return
    var = event.pattern_match.group(1)
    if not var:
        rep = event.get_reply_message()
        var = rep.text
    if str(var) == "setup":
        telegraph = "https://telegra.ph/Leech2Drive-Setup-Tutorial-02-21"
        return await event.edit(f"Find gdrive setup instructions for leech2drive [here]({telegraph}).")
    # print(var)
    uris = [var]
    # Add URL Into Queue
    try:
        download = aria2.add_uris(uris, options=None, position=None)
    except Exception as e:
        await log(str(e))
        return await event.delete()

    gid = download.gid
    complete = None
    await progress_status(gid=gid, event=event, previous=None)
    file = aria2.get_download(gid)
    if file.followed_by_ids:
        new_gid = await check_metadata(gid)
        await progress_status(gid=new_gid, event=event, previous=None)
    while complete != True:
        file = aria2.get_download(gid)
        torrent = str(file.name)
        if torrent.startswith("[METADATA]"):
            torrent = torrent[10:]
        complete = file.is_complete
        try:
            msg = "**Leeching:** "+req_file + "\n**Speed:** " + str(file.download_speed_string())+"\n**Progress:** "+str(
                file.progress_string())+"\n**Total Size:** "+str(file.total_length_string())+"\n**ETA:**  "+str(file.eta_string())+"\n\n"
            await event.edit(msg)
            await asyncio.sleep(10)
        except Exception as e:
            await log(str(e))
            pass
    # GDRIVE UPLOAD
    input_str = req_file
    required_file = req_file
    await event.delete()
    mone = await event.reply(f"Uploading files to Gdrive...")
    if CLIENT_ID is None or CLIENT_SECRET is None:
        await mone.edit(f"Find gdrive setup instructions for leech2drive [here]({telegraph}).")
        return
    if Config.PRIVATE_GROUP_BOT_API_ID is None:
        await mone.edit(f"Find gdrive setup instructions for leech2drive [here]({telegraph}).")
        return
    if os.path.isfile(input_str):
        # Check if token file exists, if not create it by requesting authorization code
        storage = None
        if not os.path.isfile(G_DRIVE_TOKEN_FILE):
            await mone.edit("Please follow instructions sent logger group.\nTimeout = 60seconds.")
            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)
        # 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, file_name, mime_type, mone, None)
            await mone.edit(f"Required file: {g_drive_link}")
        except Exception as e:
            await mone.edit(f"Oh snap! Looks like something went wrong!")
        return
    elif os.path.isdir(input_str):
        # TODO: remove redundant code
        #
        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):
            await mone.edit("Please follow instructions sent in logger group.\nTimeout = 60seconds.")
            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
        # first, create a sub-directory
        dir_id = await create_directory(http, os.path.basename(os.path.abspath(input_str)), G_DRIVE_F_PARENT_ID)
        await DoTeskWithDir(http, input_str, mone, dir_id)
        dir_link = "https://drive.google.com/folderview?id={}".format(dir_id)
        await mone.edit(f"Done! Click [here]({dir_link}) to download the file from gdrive.")
Example #4
0
async def leech2tg(event):
    if event.fwd_from:
        return
    var = event.pattern_match.group(1)
    if not var:
        rep = event.get_reply_message()
        var = rep.text
    # print(var)
    uris = [var]
    # Add URL Into Queue
    try:
        download = aria2.add_uris(uris, options=None, position=None)
    except Exception as e:
        await log(str(e))
        return await event.delete()

    gid = download.gid
    complete = None
    await progress_status(gid=gid, event=event, previous=None)
    file = aria2.get_download(gid)
    if file.followed_by_ids:
        new_gid = await check_metadata(gid)
        await progress_status(gid=new_gid, event=event, previous=None)
    while complete != True:
        file = aria2.get_download(gid)
        complete = file.is_complete
        try:
            msg = "**Leeching:** "+req_file + "\n**Speed:** " + str(file.download_speed_string())+"\n**Progress:** "+str(
                file.progress_string())+"\n**Total Size:** "+str(file.total_length_string())+"\n**ETA:**  "+str(file.eta_string())+"\n\n"
            await event.edit(msg)
            await asyncio.sleep(10)
        except Exception as e:
            await log(str(e))
            pass
        # TG UPLOAD
        to_upload = f"./{req_file}"
    if os.path.isdir(to_upload):
        input_str = to_upload
        if os.path.exists(input_str):
            start = datetime.now()
            # await event.edit("Processing...")
            lst_of_files = sorted(get_lst_of_files(input_str, []))
            logger.info(lst_of_files)
            u = 0
            await event.edit(
                "Found {} files. ".format(len(lst_of_files)) +
                "Uploading will start soon. " +
                "Please wait!"
            )
            thumb = None
            if os.path.exists(thumb_image_path):
                thumb = thumb_image_path
            for single_file in lst_of_files:
                if os.path.exists(single_file):
                    # https://stackoverflow.com/a/678242/4723940
                    caption_rts = os.path.basename(single_file)
                    force_document = True
                    supports_streaming = False
                    document_attributes = []
                    width = 0
                    height = 0
                    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")
                    if single_file.endswith((".mkv", ".mp4", ".webm")):
                        metadata = extractMetadata(createParser(single_file))
                        duration = 0
                        if metadata.has("duration"):
                            duration = metadata.get('duration').seconds
                        document_attributes = [
                            DocumentAttributeVideo(
                                duration=duration,
                                w=width,
                                h=height,
                                round_message=False,
                                supports_streaming=True
                            )
                        ]
                        supports_streaming = True
                        force_document = False
                    if single_file.endswith((".mp3", ".flac", ".wav")):
                        metadata = extractMetadata(createParser(single_file))
                        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")
                        document_attributes = [
                            DocumentAttributeAudio(
                                duration=duration,
                                voice=False,
                                title=title,
                                performer=artist,
                                waveform=None
                            )
                        ]
                        supports_streaming = True
                        force_document = False
                    try:
                        await borg.send_file(
                            event.chat_id,
                            single_file,
                            caption=caption_rts,
                            force_document=force_document,
                            supports_streaming=supports_streaming,
                            allow_cache=False,
                            reply_to=event.message.id,
                            thumb=thumb,
                            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)
                    u = u + 1
                    # await event.edit("Uploaded {} / {} files.".format(u, len(lst_of_files)))
                    # @ControllerBot was having issues,
                    # if both edited_updates and update events come simultaneously.
                    await asyncio.sleep(5)
            end = datetime.now()
            ms = (end - start).seconds
            await event.edit("Uploaded {} files in {} seconds.".format(u, ms))
        else:
            await event.edit("Oh snap! Something went wrong!")
    elif os.path.isfile(to_upload):
        mone = await event.edit("Uploading required file..")
        input_str = to_upload
        thumb = None
        if os.path.exists(thumb_image_path):
            thumb = thumb_image_path
        if os.path.exists(input_str):
            start = datetime.now()
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                input_str,
                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, mone, c_time, "")
                )
            )
            end = datetime.now()
            # os.remove(input_str)
            ms = (end - start).seconds
            await mone.edit(f"Uploaded {input_str} in {ms} seconds.")
        else:
            await mone.edit("Oh snap! Something went wrong!")
    else:
        await ("Oh snap! Something went wrong!")