diff --git a/bot/__init__.py b/bot/__init__.py index eb440622..c8a8a4a5 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -84,8 +84,7 @@ def mktable(): parent_id = getConfig('GDRIVE_FOLDER_ID') telegraph_token = getConfig('TELEGRAPH_TOKEN') DOWNLOAD_DIR = getConfig('DOWNLOAD_DIR') - if DOWNLOAD_DIR[-1] != '/' or DOWNLOAD_DIR[-1] != '\\': - DOWNLOAD_DIR = DOWNLOAD_DIR + '/' + DOWNLOAD_DIR = DOWNLOAD_DIR + '/' DOWNLOAD_STATUS_UPDATE_INTERVAL = int(getConfig('DOWNLOAD_STATUS_UPDATE_INTERVAL')) OWNER_ID = int(getConfig('OWNER_ID')) AUTO_DELETE_MESSAGE_DURATION = int(getConfig('AUTO_DELETE_MESSAGE_DURATION')) @@ -139,19 +138,13 @@ def mktable(): INDEX_URL = None try: IS_TEAM_DRIVE = getConfig('IS_TEAM_DRIVE') - if IS_TEAM_DRIVE.lower() == 'true': - IS_TEAM_DRIVE = True - else: - IS_TEAM_DRIVE = False + IS_TEAM_DRIVE = IS_TEAM_DRIVE.lower() == 'true' except KeyError: IS_TEAM_DRIVE = False try: USE_SERVICE_ACCOUNTS = getConfig('USE_SERVICE_ACCOUNTS') - if USE_SERVICE_ACCOUNTS.lower() == 'true': - USE_SERVICE_ACCOUNTS = True - else: - USE_SERVICE_ACCOUNTS = False + USE_SERVICE_ACCOUNTS = USE_SERVICE_ACCOUNTS.lower() == 'true' except KeyError: USE_SERVICE_ACCOUNTS = False diff --git a/bot/helper/ext_utils/bot_utils.py b/bot/helper/ext_utils/bot_utils.py index b387e02b..d9ec56a1 100644 --- a/bot/helper/ext_utils/bot_utils.py +++ b/bot/helper/ext_utils/bot_utils.py @@ -63,20 +63,23 @@ def getDownloadByGid(gid): with download_dict_lock: for dl in download_dict.values(): status = dl.status() - if status != MirrorStatus.STATUS_UPLOADING and status != MirrorStatus.STATUS_ARCHIVING\ - and status != MirrorStatus.STATUS_EXTRACTING: - if dl.gid() == gid: - return dl + if ( + status + not in [ + MirrorStatus.STATUS_UPLOADING, + MirrorStatus.STATUS_ARCHIVING, + MirrorStatus.STATUS_EXTRACTING, + ] + and dl.gid() == gid + ): + return dl return None def get_progress_bar_string(status): completed = status.processed_bytes() / 8 total = status.size_raw() / 8 - if total == 0: - p = 0 - else: - p = round(completed * 100 / total) + p = 0 if total == 0 else round(completed * 100 / total) p = min(max(p, 0), 100) cFull = p // 8 cPart = p % 8 - 1 @@ -94,7 +97,10 @@ def get_readable_message(): for download in list(download_dict.values()): msg += f"FileName : {download.name()} \n\nStatus : " msg += download.status() - if download.status() != MirrorStatus.STATUS_ARCHIVING and download.status() != MirrorStatus.STATUS_EXTRACTING: + if download.status() not in [ + MirrorStatus.STATUS_ARCHIVING, + MirrorStatus.STATUS_EXTRACTING, + ]: msg += f"\n\n{get_progress_bar_string(download)} {download.progress()}" \ f"\n\nProgress : {get_readable_file_size(download.processed_bytes())}" \ f"\n\nSize : {download.size()}" \ @@ -129,16 +135,12 @@ def get_readable_time(seconds: int) -> str: def is_url(url: str): url = re.findall(URL_REGEX, url) - if url: - return True - return False + return bool(url) def is_magnet(url: str): magnet = re.findall(MAGNET_REGEX, url) - if magnet: - return True - return False + return bool(magnet) def is_mega_link(url: str): diff --git a/bot/helper/ext_utils/db_handler.py b/bot/helper/ext_utils/db_handler.py index 4e635d56..4dadc34c 100644 --- a/bot/helper/ext_utils/db_handler.py +++ b/bot/helper/ext_utils/db_handler.py @@ -20,59 +20,55 @@ def disconnect(self): def db_auth(self,chat_id: int): self.connect() - if self.err : + if self.err: return "There's some error check log for details" - else: - sql = 'INSERT INTO users VALUES ({});'.format(chat_id) - self.cur.execute(sql) - self.conn.commit() - self.disconnect() - AUTHORIZED_CHATS.add(chat_id) - return 'Authorized successfully' + sql = 'INSERT INTO users VALUES ({});'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + AUTHORIZED_CHATS.add(chat_id) + return 'Authorized successfully' def db_unauth(self,chat_id: int): self.connect() - if self.err : + if self.err: return "There's some error check log for details" - else: - sql = 'DELETE from users where uid = {};'.format(chat_id) - self.cur.execute(sql) - self.conn.commit() - self.disconnect() - AUTHORIZED_CHATS.remove(chat_id) - if chat_id in SUDO_USERS: - SUDO_USERS.remove(chat_id) - return 'Unauthorized successfully' + sql = 'DELETE from users where uid = {};'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + AUTHORIZED_CHATS.remove(chat_id) + if chat_id in SUDO_USERS: + SUDO_USERS.remove(chat_id) + return 'Unauthorized successfully' def db_addsudo(self,chat_id: int): self.connect() - if self.err : + if self.err: return "There's some error check log for details" + if chat_id in AUTHORIZED_CHATS: + sql = 'UPDATE users SET sudo = TRUE where uid = {};'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + SUDO_USERS.add(chat_id) + return 'Successfully promoted as sudo' else: - if chat_id in AUTHORIZED_CHATS: - sql = 'UPDATE users SET sudo = TRUE where uid = {};'.format(chat_id) - self.cur.execute(sql) - self.conn.commit() - self.disconnect() - SUDO_USERS.add(chat_id) - return 'Successfully promoted as sudo' - else: - sql = 'INSERT INTO users VALUES ({},TRUE);'.format(chat_id) - self.cur.execute(sql) - self.conn.commit() - self.disconnect() - AUTHORIZED_CHATS.add(chat_id) - SUDO_USERS.add(chat_id) - return 'Successfully Authorized and promoted as sudo' + sql = 'INSERT INTO users VALUES ({},TRUE);'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + AUTHORIZED_CHATS.add(chat_id) + SUDO_USERS.add(chat_id) + return 'Successfully Authorized and promoted as sudo' def db_rmsudo(self,chat_id: int): self.connect() - if self.err : + if self.err: return "There's some error check log for details" - else: - sql = 'UPDATE users SET sudo = FALSE where uid = {};'.format(chat_id) - self.cur.execute(sql) - self.conn.commit() - self.disconnect() - SUDO_USERS.remove(chat_id) - return 'Successfully removed from Sudo' \ No newline at end of file + sql = 'UPDATE users SET sudo = FALSE where uid = {};'.format(chat_id) + self.cur.execute(sql) + self.conn.commit() + self.disconnect() + SUDO_USERS.remove(chat_id) + return 'Successfully removed from Sudo' \ No newline at end of file diff --git a/bot/helper/ext_utils/fs_utils.py b/bot/helper/ext_utils/fs_utils.py index e0b4cc7f..dbe724c9 100644 --- a/bot/helper/ext_utils/fs_utils.py +++ b/bot/helper/ext_utils/fs_utils.py @@ -137,5 +137,5 @@ def get_base_name(orig_path: str): def get_mime_type(file_path): mime = magic.Magic(mime=True) mime_type = mime.from_file(file_path) - mime_type = mime_type if mime_type else "text/plain" + mime_type = mime_type or "text/plain" return mime_type diff --git a/bot/helper/mirror_utils/download_utils/aria2_download.py b/bot/helper/mirror_utils/download_utils/aria2_download.py index a610f811..0aea8c78 100644 --- a/bot/helper/mirror_utils/download_utils/aria2_download.py +++ b/bot/helper/mirror_utils/download_utils/aria2_download.py @@ -31,8 +31,7 @@ def __onDownloadComplete(self, api: API, gid): download_dict[dl.uid()].is_torrent = True update_all_messages() LOGGER.info(f'Changed gid from {gid} to {new_gid}') - else: - if dl: threading.Thread(target=dl.getListener().onDownloadComplete).start() + elif dl: threading.Thread(target=dl.getListener().onDownloadComplete).start() @new_thread def __onDownloadPause(self, api, gid): diff --git a/bot/helper/mirror_utils/download_utils/direct_link_generator.py b/bot/helper/mirror_utils/download_utils/direct_link_generator.py index 84ea43a5..e9133fa2 100644 --- a/bot/helper/mirror_utils/download_utils/direct_link_generator.py +++ b/bot/helper/mirror_utils/download_utils/direct_link_generator.py @@ -72,12 +72,10 @@ def yandex_disk(url: str) -> str: try: link = re.findall(r'\bhttps?://.*yadi\.sk\S+', url)[0] except IndexError: - reply = "`No Yandex.Disk links found`\n" - return reply + return "`No Yandex.Disk links found`\n" api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}' try: - dl_url = requests.get(api.format(link)).json()['href'] - return dl_url + return requests.get(api.format(link)).json()['href'] except KeyError: raise DirectDownloadLinkException("`Error: File not found / Download limit reached`\n") @@ -97,8 +95,7 @@ def cm_ru(url: str) -> str: data = json.loads(result) except json.decoder.JSONDecodeError: raise DirectDownloadLinkException("`Error: Can't extract the link`\n") - dl_url = data['download'] - return dl_url + return data['download'] def mediafire(url: str) -> str: @@ -109,8 +106,7 @@ def mediafire(url: str) -> str: raise DirectDownloadLinkException("`No MediaFire links found`\n") page = BeautifulSoup(requests.get(link).content, 'lxml') info = page.find('a', {'aria-label': 'Download file'}) - dl_url = info.get('href') - return dl_url + return info.get('href') def osdn(url: str) -> str: @@ -140,8 +136,7 @@ def github(url: str) -> str: raise DirectDownloadLinkException("`No GitHub Releases links found`\n") download = requests.get(url, stream=True, allow_redirects=False) try: - dl_url = download.headers["location"] - return dl_url + return download.headers["location"] except KeyError: raise DirectDownloadLinkException("`Error: Can't extract the link`\n") diff --git a/bot/helper/mirror_utils/download_utils/telegram_downloader.py b/bot/helper/mirror_utils/download_utils/telegram_downloader.py index b35f7f3d..45aed145 100644 --- a/bot/helper/mirror_utils/download_utils/telegram_downloader.py +++ b/bot/helper/mirror_utils/download_utils/telegram_downloader.py @@ -80,9 +80,8 @@ def __download(self, message, path): progress=self.__onDownloadProgress, file_name=path) if download is not None: self.__onDownloadComplete() - else: - if not self.__is_cancelled: - self.__onDownloadError('Internal error occurred') + elif not self.__is_cancelled: + self.__onDownloadError('Internal error occurred') def add_download(self, message, path): _message = self.__user_bot.get_messages(message.chat.id, message.message_id) diff --git a/bot/helper/mirror_utils/status_utils/aria_download_status.py b/bot/helper/mirror_utils/status_utils/aria_download_status.py index ef04a793..f9c4e95f 100644 --- a/bot/helper/mirror_utils/status_utils/aria_download_status.py +++ b/bot/helper/mirror_utils/status_utils/aria_download_status.py @@ -61,14 +61,13 @@ def eta(self): def status(self): download = self.aria_download() if download.is_waiting: - status = MirrorStatus.STATUS_WAITING + return MirrorStatus.STATUS_WAITING elif download.is_paused: - status = MirrorStatus.STATUS_CANCELLED + return MirrorStatus.STATUS_CANCELLED elif download.has_failed: - status = MirrorStatus.STATUS_FAILED + return MirrorStatus.STATUS_FAILED else: - status = MirrorStatus.STATUS_DOWNLOADING - return status + return MirrorStatus.STATUS_DOWNLOADING def aria_download(self): self.__update() diff --git a/bot/helper/mirror_utils/upload_utils/gdriveTools.py b/bot/helper/mirror_utils/upload_utils/gdriveTools.py index 9b8d0318..11dccd8c 100644 --- a/bot/helper/mirror_utils/upload_utils/gdriveTools.py +++ b/bot/helper/mirror_utils/upload_utils/gdriveTools.py @@ -167,13 +167,15 @@ def upload_file(self, file_path, file_name, mime_type, parent_id): except HttpError as err: if err.resp.get('content-type', '').startswith('application/json'): reason = json.loads(err.content).get('error').get('errors')[0].get('reason') - if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded': - if USE_SERVICE_ACCOUNTS: - self.switchServiceAccount() - LOGGER.info(f"Got: {reason}, Trying Again.") - return self.upload_file(file_path, file_name, mime_type, parent_id) - else: + if reason not in [ + 'userRateLimitExceeded', + 'dailyLimitExceeded', + ]: raise err + if USE_SERVICE_ACCOUNTS: + self.switchServiceAccount() + LOGGER.info(f"Got: {reason}, Trying Again.") + return self.upload_file(file_path, file_name, mime_type, parent_id) self._file_uploaded_bytes = 0 # Insert new permissions if not IS_TEAM_DRIVE: @@ -261,19 +263,23 @@ def copyFile(self, file_id, dest_id): } try: - res = self.__service.files().copy(supportsAllDrives=True,fileId=file_id,body=body).execute() - return res + return ( + self.__service.files() + .copy(supportsAllDrives=True, fileId=file_id, body=body) + .execute() + ) + except HttpError as err: if err.resp.get('content-type', '').startswith('application/json'): reason = json.loads(err.content).get('error').get('errors')[0].get('reason') - if reason == 'userRateLimitExceeded' or reason == 'dailyLimitExceeded': - if USE_SERVICE_ACCOUNTS: - self.switchServiceAccount() - LOGGER.info(f"Got: {reason}, Trying Again.") - return self.copyFile(file_id,dest_id) - else: + if reason not in ['userRateLimitExceeded', 'dailyLimitExceeded']: raise err + if USE_SERVICE_ACCOUNTS: + self.switchServiceAccount() + LOGGER.info(f"Got: {reason}, Trying Again.") + return self.copyFile(file_id,dest_id) + @retry(wait=wait_exponential(multiplier=2, min=3, max=6), stop=stop_after_attempt(5), retry=retry_if_exception_type(HttpError), before=before_log(LOGGER, logging.DEBUG)) def getFileMetadata(self,file_id): @@ -472,52 +478,51 @@ def drive_list(self, fileName): fields='files(id, name, mimeType, size)', orderBy='modifiedTime desc').execute() - if response["files"]: - content_count = 0 - self.telegraph_content = [] - self.path = [] - msg += f'

Results : {fileName}


@LoaderXbot #ProjektX

' + if not response["files"]: + return "No Result Found :(", None - for file in response.get('files', []): - if file.get('mimeType') == "application/vnd.google-apps.folder": # Detect Whether Current Entity is a Folder or File. - msg += f"⁍{file.get('name')}
(folderπŸ“)

" \ - f"Drive Link" - if INDEX_URL is not None: - url_path = requests.utils.quote(f'{file.get("name")}') - url = f'{INDEX_URL}/{url_path}/' - msg += f' | Index Link' + content_count = 0 + self.telegraph_content = [] + self.path = [] + msg += f'

Results : {fileName}


@LoaderXbot #ProjektX

' - else: - msg += f"⁍{file.get('name')}
({get_readable_file_size(int(file.get('size')))})πŸ“„

" \ - f"Drive Link" - if INDEX_URL is not None: - url_path = requests.utils.quote(f'{file.get("name")}') - url = f'{INDEX_URL}/{url_path}' - msg += f' | Index Link' - msg += '

' - content_count += 1 - if content_count == TELEGRAPHLIMIT : - self.telegraph_content.append(msg) - msg = "" - content_count = 0 - - if msg != '': + for file in response.get('files', []): + if file.get('mimeType') == "application/vnd.google-apps.folder": # Detect Whether Current Entity is a Folder or File. + msg += f"⁍{file.get('name')}
(folderπŸ“)

" \ + f"Drive Link" + if INDEX_URL is not None: + url_path = requests.utils.quote(f'{file.get("name")}') + url = f'{INDEX_URL}/{url_path}/' + msg += f' | Index Link' + + else: + msg += f"⁍{file.get('name')}
({get_readable_file_size(int(file.get('size')))})πŸ“„

" \ + f"Drive Link" + if INDEX_URL is not None: + url_path = requests.utils.quote(f'{file.get("name")}') + url = f'{INDEX_URL}/{url_path}' + msg += f' | Index Link' + msg += '

' + content_count += 1 + if content_count == TELEGRAPHLIMIT : self.telegraph_content.append(msg) + msg = "" + content_count = 0 - for content in self.telegraph_content : - self.path.append(telegra_ph.create_page(title = 'LoaderX', - html_content=content )['path']) + if msg != '': + self.telegraph_content.append(msg) - self.num_of_path = len(self.path) - if self.num_of_path > 1: - self.edit_telegraph() + for content in self.telegraph_content : + self.path.append(telegra_ph.create_page(title = 'LoaderX', + html_content=content )['path']) - msg = f"Search Results For {fileName} πŸ‘‡" - buttons = button_builder.ButtonMaker() - buttons.buildbutton("HERE", f"https://telegra.ph/{self.path[0]}") + self.num_of_path = len(self.path) + if self.num_of_path > 1: + self.edit_telegraph() - return msg, InlineKeyboardMarkup(buttons.build_menu(1)) + msg = f"Search Results For {fileName} πŸ‘‡" + buttons = button_builder.ButtonMaker() + buttons.buildbutton("HERE", f"https://telegra.ph/{self.path[0]}") - else : - return "No Result Found :(", None + return msg, InlineKeyboardMarkup(buttons.build_menu(1)) diff --git a/bot/helper/telegram_helper/message_utils.py b/bot/helper/telegram_helper/message_utils.py index 8b500b82..07d96068 100644 --- a/bot/helper/telegram_helper/message_utils.py +++ b/bot/helper/telegram_helper/message_utils.py @@ -104,7 +104,6 @@ def sendStatusMessage(msg, bot): except Exception as e: LOGGER.error(str(e)) del status_reply_dict[msg.message.chat.id] - pass if len(progress) == 0: progress = "Starting DL" message = sendMessage(progress, bot, msg) diff --git a/bot/modules/authorize.py b/bot/modules/authorize.py index 5f7f0d2c..32b4bb78 100644 --- a/bot/modules/authorize.py +++ b/bot/modules/authorize.py @@ -19,22 +19,21 @@ def authorize(update,context): msg = DbManger().db_auth(chat_id) else: msg = 'User already authorized' - else: - if reply_message is None: - # Trying to authorize a chat - chat_id = update.effective_chat.id - if chat_id not in AUTHORIZED_CHATS: - msg = DbManger().db_auth(chat_id) - else: - msg = 'Already authorized chat' + elif reply_message is None: + # Trying to authorize a chat + chat_id = update.effective_chat.id + if chat_id not in AUTHORIZED_CHATS: + msg = DbManger().db_auth(chat_id) + else: + msg = 'Already authorized chat' + else: + # Trying to authorize someone in specific + user_id = reply_message.from_user.id + if user_id not in AUTHORIZED_CHATS: + msg = DbManger().db_auth(user_id) else: - # Trying to authorize someone in specific - user_id = reply_message.from_user.id - if user_id not in AUTHORIZED_CHATS: - msg = DbManger().db_auth(user_id) - else: - msg = 'User already authorized' + msg = 'User already authorized' sendMessage(msg, context.bot, update) @@ -50,21 +49,20 @@ def unauthorize(update,context): msg = DbManger().db_unauth(chat_id) else: msg = 'User already unauthorized' + elif reply_message is None: + # Trying to unauthorize a chat + chat_id = update.effective_chat.id + if chat_id in AUTHORIZED_CHATS: + msg = DbManger().db_unauth(chat_id) + else: + msg = 'Already unauthorized chat' else: - if reply_message is None: - # Trying to unauthorize a chat - chat_id = update.effective_chat.id - if chat_id in AUTHORIZED_CHATS: - msg = DbManger().db_unauth(chat_id) - else: - msg = 'Already unauthorized chat' + # Trying to authorize someone in specific + user_id = reply_message.from_user.id + if user_id in AUTHORIZED_CHATS: + msg = DbManger().db_unauth(user_id) else: - # Trying to authorize someone in specific - user_id = reply_message.from_user.id - if user_id in AUTHORIZED_CHATS: - msg = DbManger().db_unauth(user_id) - else: - msg = 'User already unauthorized' + msg = 'User already unauthorized' sendMessage(msg, context.bot, update) @@ -80,16 +78,15 @@ def addSudo(update,context): msg = DbManger().db_addsudo(chat_id) else: msg = 'Already Sudo' + elif reply_message is None: + msg = "Give ID or Reply To message of whom you want to Promote" else: - if reply_message is None: - msg = "Give ID or Reply To message of whom you want to Promote" + # Trying to authorize someone in specific + user_id = reply_message.from_user.id + if user_id not in SUDO_USERS: + msg = DbManger().db_addsudo(user_id) else: - # Trying to authorize someone in specific - user_id = reply_message.from_user.id - if user_id not in SUDO_USERS: - msg = DbManger().db_addsudo(user_id) - else: - msg = 'Already Sudo' + msg = 'Already Sudo' sendMessage(msg, context.bot, update) @@ -98,22 +95,15 @@ def removeSudo(update,context): reply_message = None message_ = None reply_message = update.message.reply_to_message - message_ = update.message.text.split(' ') + message_ = update.message.text.split(' ') if len(message_) == 2: chat_id = int(message_[1]) - if chat_id in SUDO_USERS: - msg = DbManger().db_rmsudo(chat_id) - else: - msg = 'Not a Sudo' + msg = DbManger().db_rmsudo(chat_id) if chat_id in SUDO_USERS else 'Not a Sudo' + elif reply_message is None: + msg = "Give ID or Reply To message of whom you want to remove from Sudo" else: - if reply_message is None: - msg = "Give ID or Reply To message of whom you want to remove from Sudo" - else: - user_id = reply_message.from_user.id - if user_id in SUDO_USERS: - msg = DbManger().db_rmsudo(user_id) - else: - msg = 'Not a Sudo' + user_id = reply_message.from_user.id + msg = DbManger().db_rmsudo(user_id) if user_id in SUDO_USERS else 'Not a Sudo' sendMessage(msg, context.bot, update) diff --git a/bot/modules/cancel_mirror.py b/bot/modules/cancel_mirror.py index a4d2d741..15156209 100644 --- a/bot/modules/cancel_mirror.py +++ b/bot/modules/cancel_mirror.py @@ -28,17 +28,16 @@ def cancel_mirror(update, context): with download_dict_lock: keys = list(download_dict.keys()) dl = download_dict[mirror_message.message_id] - if len(args) == 1: - if mirror_message is None or mirror_message.message_id not in keys: - if BotCommands.MirrorCommand in mirror_message.text or \ + if len(args) == 1 and ( + mirror_message is None or mirror_message.message_id not in keys + ): + if BotCommands.MirrorCommand in mirror_message.text or \ BotCommands.TarMirrorCommand in mirror_message.text: - msg = "Mirror already have been cancelled" - sendMessage(msg, context.bot, update) - return - else: - msg = "Please reply to the /mirror message which was used to start the download or /cancel gid to cancel it!" - sendMessage(msg, context.bot, update) - return + msg = "Mirror already have been cancelled" + else: + msg = "Please reply to the /mirror message which was used to start the download or /cancel gid to cancel it!" + sendMessage(msg, context.bot, update) + return if dl.status() == "Uploading": sendMessage("Upload in Progress, Don't Cancel it.", context.bot, update) return @@ -56,8 +55,10 @@ def cancel_all(update, context): with download_dict_lock: count = 0 for dlDetails in list(download_dict.values()): - if dlDetails.status() == MirrorStatus.STATUS_DOWNLOADING \ - or dlDetails.status() == MirrorStatus.STATUS_WAITING: + if dlDetails.status() in [ + MirrorStatus.STATUS_DOWNLOADING, + MirrorStatus.STATUS_WAITING, + ]: dlDetails.download().cancel_download() count += 1 delete_all_messages() diff --git a/bot/modules/delete.py b/bot/modules/delete.py index eb0d8d48..e098b0a9 100644 --- a/bot/modules/delete.py +++ b/bot/modules/delete.py @@ -13,7 +13,7 @@ def deletefile(update, context): msg = '' try: link = msg_args[1] - LOGGER.info(msg_args[1]) + LOGGER.info(link) except IndexError: msg = 'send a link along with command' diff --git a/bot/modules/mirror.py b/bot/modules/mirror.py index ce2b43d1..7e3f0438 100644 --- a/bot/modules/mirror.py +++ b/bot/modules/mirror.py @@ -116,7 +116,6 @@ def onDownloadError(self, error): LOGGER.info(str(download_dict)) except Exception as e: LOGGER.error(str(e)) - pass count = len(download_dict) if self.message.from_user.username: uname = f"@{self.message.from_user.username}" @@ -199,18 +198,17 @@ def _mirror(bot, update, isTar=False, extract=False): file = i break - if len(link) == 0: - if file is not None: - if file.mime_type != "application/x-bittorrent": - listener = MirrorListener(bot, update, isTar, tag) - tg_downloader = TelegramDownloadHelper(listener) - tg_downloader.add_download(reply_to, f'{DOWNLOAD_DIR}{listener.uid}/') - sendStatusMessage(update, bot) - if len(Interval) == 0: - Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages)) - return - else: - link = file.get_file().file_path + if len(link) == 0 and file is not None: + if file.mime_type != "application/x-bittorrent": + listener = MirrorListener(bot, update, isTar, tag) + tg_downloader = TelegramDownloadHelper(listener) + tg_downloader.add_download(reply_to, f'{DOWNLOAD_DIR}{listener.uid}/') + sendStatusMessage(update, bot) + if len(Interval) == 0: + Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages)) + return + else: + link = file.get_file().file_path else: tag = None if not bot_utils.is_url(link) and not bot_utils.is_magnet(link): diff --git a/bot/modules/watch.py b/bot/modules/watch.py index 42bdb1d7..4477905d 100644 --- a/bot/modules/watch.py +++ b/bot/modules/watch.py @@ -17,11 +17,7 @@ def _watch(bot: Bot, update: Update, args: list, isTar=False): sendMessage(f'/{BotCommands.WatchCommand} [yt_dl supported link] to mirror with youtube_dl', bot, update) return reply_to = update.message.reply_to_message - if reply_to is not None: - tag = reply_to.from_user.username - else: - tag = None - + tag = reply_to.from_user.username if reply_to is not None else None listener = MirrorListener(bot, update, isTar, tag) ydl = YoutubeDLHelper(listener) threading.Thread(target=ydl.add_download,args=(link, f'{DOWNLOAD_DIR}{listener.uid}')).start() diff --git a/gen_sa_accounts.py b/gen_sa_accounts.py index ff6f144b..7f1d7e08 100644 --- a/gen_sa_accounts.py +++ b/gen_sa_accounts.py @@ -24,7 +24,7 @@ # Create count SAs in project def _create_accounts(service, project, count): batch = service.new_batch_http_request(callback=_def_batch_resp) - for i in range(count): + for _ in range(count): aid = _generate_id('mfc-') batch.add(service.projects().serviceAccounts().create(name='projects/' + project, body={'accountId': aid, 'serviceAccount': { @@ -76,7 +76,7 @@ def _create_projects(cloud, count): global project_create_ops batch = cloud.new_batch_http_request(callback=_pc_resp) new_projs = [] - for i in range(count): + for _ in range(count): new_proj = _generate_id() new_projs.append(new_proj) batch.add(cloud.projects().create(body={'project_id': new_proj})) @@ -145,11 +145,9 @@ def _create_sa_keys(iam, projects, path): print('Redownloading keys from %s' % i) current_key_dump = [] else: - index = 0 - for j in current_key_dump: + for index, j in enumerate(current_key_dump): with open(f'{path}/{index}.json', 'w+') as f: f.write(j[1]) - index += 1 # Delete Service Accounts @@ -198,7 +196,7 @@ def serviceaccountfactory( serviceusage = build('serviceusage', 'v1', credentials=creds) projs = None - while projs == None: + while projs is None: try: projs = _get_projects(cloud) except HttpError as e: @@ -233,8 +231,7 @@ def serviceaccountfactory( input("Press Enter to continue...") if enable_services: - ste = [] - ste.append(enable_services) + ste = [enable_services] if enable_services == '~': ste = selected_projects elif enable_services == '*': @@ -243,8 +240,7 @@ def serviceaccountfactory( print('Enabling services') _enable_services(serviceusage, ste, services) if create_sas: - stc = [] - stc.append(create_sas) + stc = [create_sas] if create_sas == '~': stc = selected_projects elif create_sas == '*': @@ -255,12 +251,9 @@ def serviceaccountfactory( try: os.mkdir(path) except OSError as e: - if e.errno == errno.EEXIST: - pass - else: + if e.errno != errno.EEXIST: raise - std = [] - std.append(download_keys) + std = [download_keys] if download_keys == '~': std = selected_projects elif download_keys == '*': @@ -309,26 +302,19 @@ def serviceaccountfactory( if len(options) < 1: exit(-1) else: - i = 0 print('Select a credentials file below.') inp_options = [str(i) for i in list(range(1, len(options) + 1))] + options - while i < len(options): + for i in range(len(options)): print(' %d) %s' % (i + 1, options[i])) - i += 1 inp = None while True: inp = input('> ') if inp in inp_options: break - if inp in options: - args.credentials = inp - else: - args.credentials = options[int(inp) - 1] + args.credentials = inp if inp in options else options[int(inp) - 1] print('Use --credentials %s next time to use this credentials file.' % args.credentials) if args.quick_setup: - opt = '*' - if args.new_only: - opt = '~' + opt = '~' if args.new_only else '*' args.services = ['iam', 'drive'] args.create_projects = args.quick_setup args.enable_services = opt diff --git a/generate_drive_token.py b/generate_drive_token.py index eafad5a7..22662689 100644 --- a/generate_drive_token.py +++ b/generate_drive_token.py @@ -9,9 +9,13 @@ if os.path.exists(__G_DRIVE_TOKEN_FILE): with open(__G_DRIVE_TOKEN_FILE, 'rb') as f: credentials = pickle.load(f) - if credentials is None or not credentials.valid: - if credentials and credentials.expired and credentials.refresh_token: - credentials.refresh(Request()) + if ( + (credentials is None or not credentials.valid) + and credentials + and credentials.expired + and credentials.refresh_token + ): + credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', __OAUTH_SCOPE)