Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion add_to_team_drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
drive = googleapiclient.discovery.build("drive", "v3", credentials=creds)
batch = drive.new_batch_http_request()

aa = glob.glob('%s/*.json' % acc_dir)
aa = glob.glob(f'{acc_dir}/*.json')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 60-60 refactored with the following changes:

pbar = progress.bar.Bar("Readying accounts", max=len(aa))
for i in aa:
ce = json.loads(open(i, 'r').read())['client_email']
Expand Down
43 changes: 17 additions & 26 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,6 @@ def get_client():
MIRROR_LOGS.add(int(chats))
except:
logging.warning('Logs Chat Details not provided!')
pass

Comment on lines -179 to -180
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 179-231 refactored with the following changes:

if ospath.exists("link_logs.txt"):
with open("link_logs.txt", "r+") as f:
lines = f.readlines()
Expand All @@ -191,8 +189,6 @@ def get_client():
LINK_LOGS.add(int(chats))
except:
logging.warning('LINK_LOGS Chat id not provided, Proceeding Without it')
pass

if ospath.exists("logs_chat.txt"):
with open("logs_chat.txt", "r+") as f:
lines = f.readlines()
Expand All @@ -213,22 +209,19 @@ def get_client():
LEECH_LOG.add(int(chats))
except:
logging.warning('Leech Log Channel ID not Provided!')
pass

try:
achats = getConfig("LEECH_LOG_ALT")
achats = achats.split(" ")
for chats in achats:
LEECH_LOG_ALT.add(int(chats))
except:
logging.warning('Leech Log alt Channel ID not Provided!')
pass
try:
BOT_TOKEN = getConfig('BOT_TOKEN')
parent_id = getConfig('GDRIVE_FOLDER_ID')
DOWNLOAD_DIR = getConfig('DOWNLOAD_DIR')
if not DOWNLOAD_DIR.endswith("/"):
DOWNLOAD_DIR = DOWNLOAD_DIR + '/'
DOWNLOAD_DIR = f'{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'))
Expand Down Expand Up @@ -267,7 +260,6 @@ def aria2c_init():
aria2.remove([download], force=True, files=True)
except Exception as e:
logging.error(f"Aria2c initializing error: {e}")
pass
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function aria2c_init refactored with the following changes:


if not ospath.isfile(".restartmsg"):
sleep(1)
Expand Down Expand Up @@ -306,7 +298,7 @@ def aria2c_init():
except KeyError:
MEGA_API_KEY = None
LOGGER.info("MEGA API KEY NOT AVAILABLE")
if MEGAREST is True:
if MEGAREST:
Comment on lines -309 to +301
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 309-638 refactored with the following changes:

# Start megasdkrest binary
Popen(["megasdkrest", "--apikey", MEGA_API_KEY])
sleep(3) # Wait for the mega server to start listening
Expand Down Expand Up @@ -583,15 +575,15 @@ def aria2c_init():
FSUB = FSUB.lower() == 'true'
except KeyError:
FSUB = False

try:
FSUB_CHANNEL_ID = int(getConfig('FSUB_CHANNEL_ID'))
except KeyError:
FSUB_CHANNEL_ID = ""

try:
CHANNEL_USERNAME: str = getConfig('CHANNEL_USERNAME').replace("@", "")
if len(CHANNEL_USERNAME) == 0:
if not CHANNEL_USERNAME:
CHANNEL_USERNAME = 'heliosmirror'
except KeyError:
logging.warning('CHANNEL_USERNAME not provided')
Expand Down Expand Up @@ -622,20 +614,19 @@ def aria2c_init():
ACCOUNTS_ZIP_URL = getConfig('ACCOUNTS_ZIP_URL')
if len(ACCOUNTS_ZIP_URL) == 0:
raise KeyError
else:
try:
res = rget(ACCOUNTS_ZIP_URL)
if res.status_code == 200:
with open('accounts.zip', 'wb+') as f:
f.write(res.content)
else:
logging.error(f"Failed to download accounts.zip, link got HTTP response: {res.status_code}")
except Exception as e:
logging.error(f"ACCOUNTS_ZIP_URL: {e}")
raise KeyError
srun(["unzip", "-q", "-o", "accounts.zip"])
srun(["chmod", "-R", "777", "accounts"])
osremove("accounts.zip")
try:
res = rget(ACCOUNTS_ZIP_URL)
if res.status_code == 200:
with open('accounts.zip', 'wb+') as f:
f.write(res.content)
else:
logging.error(f"Failed to download accounts.zip, link got HTTP response: {res.status_code}")
except Exception as e:
logging.error(f"ACCOUNTS_ZIP_URL: {e}")
raise KeyError
srun(["unzip", "-q", "-o", "accounts.zip"])
srun(["chmod", "-R", "777", "accounts"])
osremove("accounts.zip")
except KeyError:
pass
try:
Expand Down
11 changes: 5 additions & 6 deletions bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,13 @@ def start(update, context):
else:
if BOT_PM:
message = sendMessage(f'Dear {uname},\n\nIf You Want To Use Me, You Have To Join @{CHANNEL_USERNAME}\n\n<b>NOTE:</b> All The Uploaded Links and Leeched Files By You Will Be Sent Here In Your Private Chat From Now.', context.bot, update)
Thread(target=auto_delete_message, args=(context.bot, update.message, message)).start()
return
else:
message = sendMarkup(
f'Dear {uname},\n\nIf You Want To Use Me, You Have To Join @{CHANNEL_USERNAME}\n\n',
context.bot, update, reply_markup)
Thread(target=auto_delete_message, args=(context.bot, update.message, message)).start()
return

Thread(target=auto_delete_message, args=(context.bot, update.message, message)).start()
return
Comment on lines -78 to +84
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function start refactored with the following changes:

def restart(update, context):
restart_message = sendMessage("Restarting...", context.bot, update)
if Interval:
Expand Down Expand Up @@ -287,9 +286,9 @@ def main():
osremove(".restartmsg")
elif OWNER_ID:
try:
text = "<b>Bot Restarted!</b>"
message = bot.sendMessage(chat_id=OWNER_ID, text=text, parse_mode=ParseMode.HTML)
if AUTHORIZED_CHATS:
text = "<b>Bot Restarted!</b>"
message = bot.sendMessage(chat_id=OWNER_ID, text=text, parse_mode=ParseMode.HTML)
Comment on lines -290 to +291
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

for i in AUTHORIZED_CHATS:
bot.sendMessage(chat_id=i, text=text, parse_mode=ParseMode.HTML)
except Exception as e:
Expand Down
77 changes: 38 additions & 39 deletions bot/helper/ext_utils/db_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@ def db_init(self):
def db_load(self):
# User Data
self.cur.execute("SELECT * from users")
rows = self.cur.fetchall() #returns a list ==> (uid, sudo, auth, media, doc, thumb)
if rows:
if rows := self.cur.fetchall():
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.db_load refactored with the following changes:

This removes the following comments ( why? ):

#returns a list ==> (uid, sudo, auth, media, doc, thumb)
#returns a list ==> (name, feed_link, last_link, last_title, filters)

for row in rows:
if row[1] and row[0] not in SUDO_USERS:
SUDO_USERS.add(row[0])
Expand All @@ -80,8 +79,7 @@ def db_load(self):
LOGGER.info("Users data has been imported from Database")
# Rss Data
self.cur.execute("SELECT * FROM rss")
rows = self.cur.fetchall() #returns a list ==> (name, feed_link, last_link, last_title, filters)
if rows:
if rows := self.cur.fetchall():
for row in rows:
f_lists = []
if row[4] is not None:
Expand All @@ -97,9 +95,9 @@ def user_auth(self, chat_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif not self.user_check(chat_id):
sql = 'INSERT INTO users (uid, auth) VALUES ({}, TRUE)'.format(chat_id)
sql = f'INSERT INTO users (uid, auth) VALUES ({chat_id}, TRUE)'
else:
sql = 'UPDATE users SET auth = TRUE WHERE uid = {}'.format(chat_id)
sql = f'UPDATE users SET auth = TRUE WHERE uid = {chat_id}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_auth refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -109,7 +107,7 @@ def user_unauth(self, chat_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif self.user_check(chat_id):
sql = 'UPDATE users SET auth = FALSE WHERE uid = {}'.format(chat_id)
sql = f'UPDATE users SET auth = FALSE WHERE uid = {chat_id}'
Comment on lines -112 to +110
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_unauth refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -120,9 +118,9 @@ def addleech_log(self, chat_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif not self.user_check(chat_id):
sql = 'INSERT INTO users (uid, leechlog) VALUES ({}, TRUE)'.format(chat_id)
sql = f'INSERT INTO users (uid, leechlog) VALUES ({chat_id}, TRUE)'
else:
sql = 'UPDATE users SET leechlog = TRUE WHERE uid = {}'.format(chat_id)
sql = f'UPDATE users SET leechlog = TRUE WHERE uid = {chat_id}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.addleech_log refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -132,7 +130,7 @@ def rmleech_log(self, chat_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif self.user_check(chat_id):
sql = 'UPDATE users SET leechlog = FALSE WHERE uid = {}'.format(chat_id)
sql = f'UPDATE users SET leechlog = FALSE WHERE uid = {chat_id}'
Comment on lines -135 to +133
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.rmleech_log refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -143,9 +141,9 @@ def addleech_log_alt(self, chat_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif not self.user_check(chat_id):
sql = 'INSERT INTO users (uid, leechlogalt) VALUES ({}, TRUE)'.format(chat_id)
sql = f'INSERT INTO users (uid, leechlogalt) VALUES ({chat_id}, TRUE)'
else:
sql = 'UPDATE users SET leechlogalt = TRUE WHERE uid = {}'.format(chat_id)
sql = f'UPDATE users SET leechlogalt = TRUE WHERE uid = {chat_id}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.addleech_log_alt refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -155,7 +153,7 @@ def rmleech_log_alt(self, chat_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif self.user_check(chat_id):
sql = 'UPDATE users SET leechlogalt = FALSE WHERE uid = {}'.format(chat_id)
sql = f'UPDATE users SET leechlogalt = FALSE WHERE uid = {chat_id}'
Comment on lines -158 to +156
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.rmleech_log_alt refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -165,9 +163,9 @@ def user_addsudo(self, user_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif not self.user_check(user_id):
sql = 'INSERT INTO users (uid, sudo) VALUES ({}, TRUE)'.format(user_id)
sql = f'INSERT INTO users (uid, sudo) VALUES ({user_id}, TRUE)'
else:
sql = 'UPDATE users SET sudo = TRUE WHERE uid = {}'.format(user_id)
sql = f'UPDATE users SET sudo = TRUE WHERE uid = {user_id}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_addsudo refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -177,19 +175,19 @@ def user_rmsudo(self, user_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif self.user_check(user_id):
sql = 'UPDATE users SET sudo = FALSE WHERE uid = {}'.format(user_id)
self.cur.execute(sql)
self.conn.commit()
self.disconnect()
return 'Successfully removed from Sudo'
sql = f'UPDATE users SET sudo = FALSE WHERE uid = {user_id}'
self.cur.execute(sql)
self.conn.commit()
self.disconnect()
return 'Successfully removed from Sudo'
Comment on lines -180 to +182
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_rmsudo refactored with the following changes:


def user_media(self, user_id: int):
if self.err:
return
elif not self.user_check(user_id):
sql = 'INSERT INTO users (uid, media) VALUES ({}, TRUE)'.format(user_id)
sql = f'INSERT INTO users (uid, media) VALUES ({user_id}, TRUE)'
else:
sql = 'UPDATE users SET media = TRUE, doc = FALSE WHERE uid = {}'.format(user_id)
sql = f'UPDATE users SET media = TRUE, doc = FALSE WHERE uid = {user_id}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_media refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -198,9 +196,9 @@ def user_doc(self, user_id: int):
if self.err:
return
elif not self.user_check(user_id):
sql = 'INSERT INTO users (uid, doc) VALUES ({}, TRUE)'.format(user_id)
sql = f'INSERT INTO users (uid, doc) VALUES ({user_id}, TRUE)'
else:
sql = 'UPDATE users SET media = FALSE, doc = TRUE WHERE uid = {}'.format(user_id)
sql = f'UPDATE users SET media = FALSE, doc = TRUE WHERE uid = {user_id}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_doc refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -210,10 +208,12 @@ def user_save_thumb(self, user_id: int, path):
return
image = open(path, 'rb+')
image_bin = image.read()
if not self.user_check(user_id):
sql = 'INSERT INTO users (thumb, uid) VALUES (%s, %s)'
else:
sql = 'UPDATE users SET thumb = %s WHERE uid = %s'
sql = (
'UPDATE users SET thumb = %s WHERE uid = %s'
if self.user_check(user_id)
else 'INSERT INTO users (thumb, uid) VALUES (%s, %s)'
)

Comment on lines -213 to +216
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_save_thumb refactored with the following changes:

self.cur.execute(sql, (image_bin, user_id))
self.conn.commit()
self.disconnect()
Expand All @@ -222,15 +222,14 @@ def user_rm_thumb(self, user_id: int, path):
if self.err:
return
elif self.user_check(user_id):
sql = 'UPDATE users SET thumb = NULL WHERE uid = {}'.format(user_id)
sql = f'UPDATE users SET thumb = NULL WHERE uid = {user_id}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_rm_thumb refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()

def user_check(self, uid: int):
self.cur.execute("SELECT * FROM users WHERE uid = {}".format(uid))
res = self.cur.fetchone()
return res
self.cur.execute(f"SELECT * FROM users WHERE uid = {uid}")
return self.cur.fetchone()
Comment on lines -231 to +232
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_check refactored with the following changes:


def rss_add(self, name, link, last, title, filters):
if self.err:
Expand Down Expand Up @@ -266,9 +265,9 @@ def user_addmod(self, user_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif not self.user_check(user_id):
sql = 'INSERT INTO users (uid, mod) VALUES ({}, TRUE)'.format(user_id)
sql = f'INSERT INTO users (uid, mod) VALUES ({user_id}, TRUE)'
else:
sql = 'UPDATE users SET mod = TRUE WHERE uid = {}'.format(user_id)
sql = f'UPDATE users SET mod = TRUE WHERE uid = {user_id}'
Comment on lines -269 to +270
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_addmod refactored with the following changes:

self.cur.execute(sql)
self.conn.commit()
self.disconnect()
Expand All @@ -278,11 +277,11 @@ def user_rmmod(self, user_id: int):
if self.err:
return "Error in DB connection, check log for details"
elif self.user_check(user_id):
sql = 'UPDATE users SET mod = FALSE WHERE uid = {}'.format(user_id)
self.cur.execute(sql)
self.conn.commit()
self.disconnect()
return 'Successfully removed from Moderator'
sql = f'UPDATE users SET mod = FALSE WHERE uid = {user_id}'
self.cur.execute(sql)
self.conn.commit()
self.disconnect()
return 'Successfully removed from Moderator'
Comment on lines -281 to +284
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DbManger.user_rmmod refactored with the following changes:


if DB_URI is not None:
DbManger().db_init()
Expand Down
6 changes: 3 additions & 3 deletions bot/helper/ext_utils/fs_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ def split(path, size, file_, dirpath, split_size, start_time=0, i=1, inLoop=Fals
if file_.upper().endswith(VIDEO_SUFFIXES):
base_name, extension = ospath.splitext(file_)
split_size = split_size - 2500000
while i <= parts :
parted_name = "{}.part{}{}".format(str(base_name), str(i).zfill(3), str(extension))
while i <= parts:
parted_name = f"{str(base_name)}.part{str(i).zfill(3)}{str(extension)}"
Comment on lines -181 to +182
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function split refactored with the following changes:

out_path = ospath.join(dirpath, parted_name)
run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-i",
path, "-ss", str(start_time), "-fs", str(split_size),
Expand All @@ -197,7 +197,7 @@ def split(path, size, file_, dirpath, split_size, start_time=0, i=1, inLoop=Fals
start_time += lpd - 3
i = i + 1
else:
out_path = ospath.join(dirpath, file_ + ".")
out_path = ospath.join(dirpath, f"{file_}.")
run(["split", "--numeric-suffixes=1", "--suffix-length=3", f"--bytes={split_size}", path, out_path])

def get_media_info(path):
Expand Down
Loading