From 94b5423c3151077140763e4b7d209d3da1e236bf Mon Sep 17 00:00:00 2001
From: Sourcery AI <>
Date: Mon, 6 Sep 2021 05:54:50 +0000
Subject: [PATCH] 'Refactored by Sourcery'
---
bot/__init__.py | 13 +-
bot/helper/ext_utils/bot_utils.py | 32 ++---
bot/helper/ext_utils/db_handler.py | 80 ++++++-------
bot/helper/ext_utils/fs_utils.py | 2 +-
.../download_utils/aria2_download.py | 3 +-
.../download_utils/direct_link_generator.py | 15 +--
.../download_utils/telegram_downloader.py | 5 +-
.../status_utils/aria_download_status.py | 9 +-
.../mirror_utils/upload_utils/gdriveTools.py | 113 +++++++++---------
bot/helper/telegram_helper/message_utils.py | 1 -
bot/modules/authorize.py | 86 ++++++-------
bot/modules/cancel_mirror.py | 25 ++--
bot/modules/delete.py | 2 +-
bot/modules/mirror.py | 24 ++--
bot/modules/watch.py | 6 +-
gen_sa_accounts.py | 36 ++----
generate_drive_token.py | 10 +-
17 files changed, 212 insertions(+), 250 deletions(-)
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'
{file.get('name')}
(folderπ)
{file.get('name')}
({get_readable_file_size(int(file.get('size')))})π
{file.get('name')}
(folderπ)
{file.get('name')}
({get_readable_file_size(int(file.get('size')))})π