Beispiel #1
0
async def gdrive_search_list(event):
    if not get_parent_id():
        pass
    else:
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            catparent_id[0].cat
        elif len(catparent_id) > 1:
            for fid in catparent_id:
                rmparent_id(fid.cat)
    await event.edit("Processing ...")
    if CLIENT_ID is None or CLIENT_SECRET is None:
        return
    input_str = event.pattern_match.group(1).strip()
    # TODO: remove redundant code
    if G_DRIVE_AUTH_TOKEN_DATA is not None:
        with open(G_DRIVE_TOKEN_FILE, "w") as t_file:
            t_file.write(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
    await event.edit(f"Searching for {input_str} in your Google Drive ...")
    gsearch_results = await gdrive_search(http, input_str)
    await event.edit(gsearch_results, link_preview=False)
Beispiel #2
0
async def upload_dir_to_gdrive(event):
    await event.edit("Processing ...")
    if not get_parent_id():
        parent_id = None
    else:
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            parent_id = catparent_id[0].cat
        elif len(catparent_id) > 1:
            for fid in catparent_id:
                rmparent_id(fid.cat)
            parent_id = None
    if CLIENT_ID is None or CLIENT_SECRET is None:
        return
    input_str = event.pattern_match.group(1)
    if os.path.isdir(input_str):
        # TODO: remove redundant code
        if G_DRIVE_AUTH_TOKEN_DATA is not None:
            with open(G_DRIVE_TOKEN_FILE, "w") as t_file:
                t_file.write(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
        # first, create a sub-directory
        dir_id = await create_directory(
            http, os.path.basename(os.path.abspath(input_str)), parent_id)
        await DoTeskWithDir(http, input_str, event, dir_id)
        dir_link = "https://drive.google.com/folderview?id={}".format(dir_id)
        await event.edit(f"Here is your Google Drive [link]({dir_link})")
    else:
        await event.edit(f"Directory {input_str} does not seem to exist")
Beispiel #3
0
async def download(cat):
    await cat.delete()
    if not get_parent_id():
        parent_id = None
    else:
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            parent_id = catparent_id[0].cat
        elif len(catparent_id) > 1:
            for fid in catparent_id:
                rmparent_id(fid.cat)
            parent_id = None
    setf = await cat.reply("Processing ...")
    input_str = cat.pattern_match.group(1)
    if input_str:
        gid = input_str
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            if is_folder(parent_id):
                rmparent_id(parent_id)
        gparent_id(gid)
        await setf.edit(
            f"Custom Folder ID set successfully. The next uploads will upload to `{gid}` till `.gsetclear`"
        )
    else:
        await setf.edit(
            "Use `.gsetf <link to GDrive Folder>` to set the folder to upload new files to."
        )
Beispiel #4
0
async def download(gclr):
    if not get_parent_id():
        parent_id = None
    else:
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            parent_id = catparent_id[0].cat
        elif len(catparent_id) > 1:
            for fid in catparent_id:
                rmparent_id(fid.cat)
            parent_id = None
    if parent_id:
        if is_folder(parent_id):
            rmparent_id(parent_id)
    await gclr.edit("Custom Folder ID cleared successfully.")
Beispiel #5
0
async def gdrive_search(http, search_query):
    if not get_parent_id():
        parent_id = None
    else:
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            parent_id = catparent_id[0].cat
        elif len(catparent_id) > 1:
            for fid in catparent_id:
                rmparent_id(fid.cat)
            parent_id = None
    if parent_id:
        query = "'{}' in parents and (title contains '{}')".format(
            parent_id, search_query)
    else:
        query = "title contains '{}'".format(search_query)
    drive_service = build("drive", "v2", http=http, cache_discovery=False)
    page_token = None
    res = ""
    while True:
        try:
            response = (drive_service.files().list(
                q=query,
                spaces="drive",
                fields="nextPageToken, items(id, title, mimeType)",
                pageToken=page_token,
            ).execute())
            for file in response.get("items", []):
                file_title = file.get("title")
                file_id = file.get("id")
                if file.get("mimeType") == G_DRIVE_DIR_MIME_TYPE:
                    res += f"`[FOLDER] {file_title}`\nhttps://drive.google.com/drive/folders/{file_id}\n\n"
                else:
                    res += f"`{file_title}`\nhttps://drive.google.com/uc?id={file_id}&export=download\n\n"
            page_token = response.get("nextPageToken", None)
            if page_token is None:
                break
        except Exception as e:
            res += str(e)
            break
    msg = f"**Google Drive Query**:\n`{search_query}`\n\n**Results**\n\n{res}"
    return msg
Beispiel #6
0
async def show_current_gdrove_folder(event):
    if not get_parent_id():
        parent_id = None
    else:
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            parent_id = catparent_id[0].cat
        elif len(catparent_id) > 1:
            for fid in catparent_id:
                rmparent_id(fid.cat)
            parent_id = None
    if parent_id:
        folder_link = f"https://drive.google.com/drive/folders/" + parent_id
        await event.edit(
            f"My userbot is currently uploading files [here]({folder_link})")
    else:
        await event.edit(
            f"My userbot is currently uploading files to the root of my Google Drive storage.\
            \nFind uploaded files [here](https://drive.google.com/drive/my-drive)"
        )
Beispiel #7
0
async def gdrive_upload_function(dryb):
    """ For .gdrive command, upload files to google drive. """
    await dryb.edit("Processing ...")
    if not get_parent_id():
        parent_id = None
    else:
        catparent_id = get_parent_id()
        if len(catparent_id) == 1:
            parent_id = catparent_id[0].cat
        elif len(catparent_id) > 1:
            for fid in catparent_id:
                rmparent_id(fid.cat)
            parent_id = None
    input_str = dryb.pattern_match.group(1)
    if CLIENT_ID is None or CLIENT_SECRET is None:
        return
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
        required_file_name = None
    if "|" in input_str:
        url, file_name = input_str.split("|")
        url = url.strip()
        # https://stackoverflow.com/a/761825/4723940
        file_name = file_name.strip()
        head, tail = os.path.split(file_name)
        if head:
            if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)):
                os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head))
                file_name = os.path.join(head, tail)
        downloaded_file_name = TEMP_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}] {2}%".format(
                ''.join(["â–ˆ" for i in range(math.floor(percentage / 10))]),
                ''.join(["â–‘"
                         for i in range(10 - math.floor(percentage / 10))]),
                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 round(diff %
                         10.00) == 0 and current_message != display_message:
                    await dryb.edit(current_message)
                    display_message = current_message
            except Exception as e:
                LOGS.info(str(e))
        if downloader.isSuccessful():
            await dryb.edit(
                "Downloaded to `{}` successfully !!\nInitiating Upload to Google Drive.."
                .format(downloaded_file_name))
            required_file_name = downloaded_file_name
        else:
            await dryb.edit("Incorrect URL\n{}".format(url))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            required_file_name = input_str
            await dryb.edit(
                "Found `{}` in local server, Initiating Upload to Google Drive.."
                .format(input_str))
        else:
            await dryb.edit(
                "File not found in local server. Give me a valid file path !")
            return False
    elif dryb.reply_to_msg_id:
        try:
            c_time = time.time()
            downloaded_file_name = await dryb.client.download_media(
                await dryb.get_reply_message(),
                TEMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(progress(d, t, dryb, c_time, "Downloading...")))
        except Exception as e:
            await dryb.edit(str(e))
        else:
            required_file_name = downloaded_file_name
            await dryb.edit(
                "Downloaded to `{}` Successfully !!\nInitiating Upload to Google Drive.."
                .format(downloaded_file_name))
    if required_file_name:
        if G_DRIVE_AUTH_TOKEN_DATA is not None:
            with open(G_DRIVE_TOKEN_FILE, "w") as t_file:
                t_file.write(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,
                                             parent_id)
            await dryb.edit(
                f"File:`{required_file_name}`\nwas 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}`")