async def gdrive_upload_function(dryb): """ For .gdrive command, upload files to google drive. """ await dryb.edit("Processing ...") 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 speed = downloader.get_speed() elapsed_time = 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)) pass 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}`")
async def download_video(v_url): """ For .rip command, download media from YouTube and many other sites. """ url = v_url.pattern_match.group(2) type = v_url.pattern_match.group(1).lower() await v_url.edit("`Preparing to download...`") if type == "audio": opts = { 'format': 'bestaudio', 'addmetadata': True, 'key': 'FFmpegMetadata', 'writethumbnail': True, 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl': '%(id)s.mp3', 'quiet': True, 'logtostderr': False } video = False song = True elif type == "video": opts = { 'format': 'best', 'addmetadata': True, 'key': 'FFmpegMetadata', 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegVideoConvertor', 'preferedformat': 'mp4' }], 'outtmpl': '%(id)s.mp4', 'logtostderr': False, 'quiet': True } song = False video = True try: await v_url.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await v_url.edit(f"`{str(DE)}`") return except ContentTooShortError: await v_url.edit("`The download content was too short.`") return except GeoRestrictedError: await v_url.edit( "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`" ) return except MaxDownloadsReached: await v_url.edit("`Max-downloads limit has been reached.`") return except PostProcessingError: await v_url.edit("`There was an error during post processing.`") return except UnavailableVideoError: await v_url.edit("`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await v_url.edit("`There was an error during info extraction.`") return except Exception as e: await v_url.edit(f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await v_url.edit(f"`Preparing to upload song:`\ \n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio(duration=int(rip_data['duration']), title=str(rip_data['title']), performer=str(rip_data['uploader'])) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3"))) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await v_url.edit(f"`Preparing to upload video:`\ \n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=rip_data['title'], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4"))) os.remove(f"{rip_data['id']}.mp4") await v_url.delete()