Skip to content

Commit

Permalink
Rename AUTHORIZED_CHATS env variable to AUTHORIZED_USERS
Browse files Browse the repository at this point in the history
  • Loading branch information
l3v11 authored Sep 20, 2022
1 parent d28ae9c commit 24e8d38
Show file tree
Hide file tree
Showing 18 changed files with 145 additions and 200 deletions.
174 changes: 56 additions & 118 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,17 @@

LOGGER = logging.getLogger(__name__)

def get_config(name: str):
return os.environ[name]

try:
CONFIG_ENV_URL = get_config('CONFIG_ENV_URL')
if len(CONFIG_ENV_URL) == 0:
raise KeyError
CONFIG_ENV_URL = os.environ.get('CONFIG_ENV_URL', '')
if len(CONFIG_ENV_URL) != 0:
try:
res = requests.get(CONFIG_ENV_URL)
if res.status_code == 200:
with open('config.env', 'wb+') as f:
f.write(res.content)
else:
LOGGER.error(f"Failed to load config.env file [{res.status_code}]")
except Exception as e:
LOGGER.error(f"CONFIG_ENV_URL: {e}")
except:
pass
LOGGER.error(f"Failed to load the config.env file [{res.status_code}]")
except Exception as err:
LOGGER.error(f"CONFIG_ENV_URL: {err}")

load_dotenv('config.env', override=True)

Expand All @@ -55,7 +48,8 @@ def get_config(name: str):
INDEX_URLS = []
TELEGRAPH = []

AUTHORIZED_CHATS = set()
def get_config(name: str):
return os.environ[name]

download_dict_lock = Lock()
status_reply_dict_lock = Lock()
Expand Down Expand Up @@ -92,153 +86,97 @@ def get_config(name: str):
LOGGER.error("DOWNLOAD_DIR env variable is missing")
exit(1)

try:
users = get_config('AUTHORIZED_CHATS')
users = users.split()
for user in users:
AUTHORIZED_CHATS.add(int(user.strip()))
except:
pass
users = os.environ.get('AUTHORIZED_USERS', '')
if len(users) != 0:
AUTHORIZED_USERS = {int(user.strip()) for user in users.split()}
else:
AUTHORIZED_USERS = set()

try:
DATABASE_URL = get_config('DATABASE_URL')
if len(DATABASE_URL) == 0:
raise KeyError
except:
DATABASE_URL = os.environ.get('DATABASE_URL', '')
if len(DATABASE_URL) == 0:
DATABASE_URL = None

try:
IS_TEAM_DRIVE = get_config('IS_TEAM_DRIVE')
IS_TEAM_DRIVE = IS_TEAM_DRIVE.lower() == 'true'
except:
IS_TEAM_DRIVE = False
IS_TEAM_DRIVE = os.environ.get('IS_TEAM_DRIVE', '')
IS_TEAM_DRIVE = IS_TEAM_DRIVE.lower() == 'true'

try:
USE_SERVICE_ACCOUNTS = get_config('USE_SERVICE_ACCOUNTS')
USE_SERVICE_ACCOUNTS = USE_SERVICE_ACCOUNTS.lower() == 'true'
except:
USE_SERVICE_ACCOUNTS = False
USE_SERVICE_ACCOUNTS = os.environ.get('USE_SERVICE_ACCOUNTS', '')
USE_SERVICE_ACCOUNTS = USE_SERVICE_ACCOUNTS.lower() == 'true'

try:
STATUS_UPDATE_INTERVAL = get_config('STATUS_UPDATE_INTERVAL')
if len(STATUS_UPDATE_INTERVAL) == 0:
raise KeyError
STATUS_UPDATE_INTERVAL = int(STATUS_UPDATE_INTERVAL)
except:
STATUS_UPDATE_INTERVAL = 10
STATUS_UPDATE_INTERVAL = os.environ.get('STATUS_UPDATE_INTERVAL', '')
STATUS_UPDATE_INTERVAL = 10 if len(STATUS_UPDATE_INTERVAL) == 0 else int(STATUS_UPDATE_INTERVAL)

try:
TELEGRAPH_ACCS = get_config('TELEGRAPH_ACCS')
if len(TELEGRAPH_ACCS) == 0:
raise KeyError
TELEGRAPH_ACCS = int(TELEGRAPH_ACCS)
except:
TELEGRAPH_ACCS = 1
TELEGRAPH_ACCS = os.environ.get('TELEGRAPH_ACCS', '')
TELEGRAPH_ACCS = 1 if len(TELEGRAPH_ACCS) == 0 else int(TELEGRAPH_ACCS)

try:
INDEX_URL = get_config('INDEX_URL').rstrip("/")
if len(INDEX_URL) == 0:
raise KeyError
except:
INDEX_URL = os.environ.get('INDEX_URL', '').rstrip("/")
if len(INDEX_URL) == 0:
INDEX_URL = None

try:
CLONE_LIMIT = get_config('CLONE_LIMIT')
if len(CLONE_LIMIT) == 0:
raise KeyError
CLONE_LIMIT = float(CLONE_LIMIT)
except:
CLONE_LIMIT = None
ARCHIVE_LIMIT = os.environ.get('ARCHIVE_LIMIT', '')
ARCHIVE_LIMIT = None if len(ARCHIVE_LIMIT) == 0 else float(ARCHIVE_LIMIT)

try:
ARCHIVE_LIMIT = get_config('ARCHIVE_LIMIT')
if len(ARCHIVE_LIMIT) == 0:
raise KeyError
ARCHIVE_LIMIT = float(ARCHIVE_LIMIT)
except:
ARCHIVE_LIMIT = None
CLONE_LIMIT = os.environ.get('CLONE_LIMIT', '')
CLONE_LIMIT = None if len(CLONE_LIMIT) == 0 else float(CLONE_LIMIT)

try:
TOKEN_JSON_URL = get_config('TOKEN_JSON_URL')
if len(TOKEN_JSON_URL) == 0:
raise KeyError
TOKEN_JSON_URL = os.environ.get('TOKEN_JSON_URL', '')
if len(TOKEN_JSON_URL) != 0:
try:
res = requests.get(TOKEN_JSON_URL)
if res.status_code == 200:
with open('token.json', 'wb+') as f:
f.write(res.content)
else:
LOGGER.error(f"Failed to load token.json file [{res.status_code}]")
except Exception as e:
LOGGER.error(f"TOKEN_JSON_URL: {e}")
except:
pass
LOGGER.error(f"Failed to load the token.json file [{res.status_code}]")
except Exception as err:
LOGGER.error(f"TOKEN_JSON_URL: {err}")

try:
ACCOUNTS_ZIP_URL = get_config('ACCOUNTS_ZIP_URL')
if len(ACCOUNTS_ZIP_URL) == 0:
raise KeyError
ACCOUNTS_ZIP_URL = os.environ.get('ACCOUNTS_ZIP_URL', '')
if len(ACCOUNTS_ZIP_URL) != 0:
try:
res = requests.get(ACCOUNTS_ZIP_URL)
if res.status_code == 200:
with open('accounts.zip', 'wb+') as f:
f.write(res.content)
subprocess.run(["unzip", "-q", "-o", "accounts.zip"])
subprocess.run(["chmod", "-R", "777", "accounts"])
os.remove("accounts.zip")
else:
LOGGER.error(f"Failed to load accounts.zip file [{res.status_code}]")
except Exception as e:
LOGGER.error(f"ACCOUNTS_ZIP_URL: {e}")
raise KeyError
subprocess.run(["unzip", "-q", "-o", "accounts.zip"])
subprocess.run(["chmod", "-R", "777", "accounts"])
os.remove("accounts.zip")
except:
pass
LOGGER.error(f"Failed to load the accounts.zip file [{res.status_code}]")
except Exception as err:
LOGGER.error(f"ACCOUNTS_ZIP_URL: {err}")

try:
DRIVE_LIST_URL = get_config('DRIVE_LIST_URL')
if len(DRIVE_LIST_URL) == 0:
raise KeyError
DRIVE_LIST_URL = os.environ.get('DRIVE_LIST_URL', '')
if len(DRIVE_LIST_URL) != 0:
try:
res = requests.get(DRIVE_LIST_URL)
if res.status_code == 200:
with open('drive_list', 'wb+') as f:
f.write(res.content)
else:
LOGGER.error(f"Failed to load drive_list file [{res.status_code}]")
except Exception as e:
LOGGER.error(f"DRIVE_LIST_URL: {e}")
except:
pass
LOGGER.error(f"Failed to load the drive_list file [{res.status_code}]")
except Exception as err:
LOGGER.error(f"DRIVE_LIST_URL: {err}")

try:
APPDRIVE_EMAIL = get_config('APPDRIVE_EMAIL')
APPDRIVE_PASS = get_config('APPDRIVE_PASS')
if len(APPDRIVE_EMAIL) == 0 or len(APPDRIVE_PASS) == 0:
raise KeyError
except:
APPDRIVE_EMAIL = os.environ.get('APPDRIVE_EMAIL', '')
APPDRIVE_PASS = os.environ.get('APPDRIVE_PASS', '')
if len(APPDRIVE_EMAIL) == 0 or len(APPDRIVE_PASS) == 0:
APPDRIVE_EMAIL = None
APPDRIVE_PASS = None

try:
GDTOT_CRYPT = get_config('GDTOT_CRYPT')
if len(GDTOT_CRYPT) == 0:
raise KeyError
except:
GDTOT_CRYPT = os.environ.get('GDTOT_CRYPT', '')
if len(GDTOT_CRYPT) == 0:
GDTOT_CRYPT = None

if os.path.exists('drive_list'):
with open('drive_list', 'r+') as f:
lines = f.readlines()
for line in lines:
try:
temp = line.strip().split()
DRIVE_NAMES.append(temp[0].replace("_", " "))
DRIVE_IDS.append(temp[1])
except:
pass
try:
temp = line.strip().split()
DRIVE_NAMES.append(temp[0].replace("_", " "))
DRIVE_IDS.append(temp[1])
if len(temp) > 2:
INDEX_URLS.append(temp[2])
except IndexError:
else:
INDEX_URLS.append(None)

def create_account(sname):
Expand Down
8 changes: 4 additions & 4 deletions bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from sys import executable
from telegram.ext import CommandHandler

from bot import bot, LOGGER, botStartTime, AUTHORIZED_CHATS, TELEGRAPH, Interval, dispatcher, updater
from bot import bot, LOGGER, botStartTime, TELEGRAPH, Interval, dispatcher, updater
from bot.modules import archive, auth, cancel, clone, count, delete, eval, list, permission, shell, status
from bot.helper.ext_utils.bot_utils import get_readable_file_size, get_readable_time
from bot.helper.ext_utils.fs_utils import start_cleanup, clean_all, exit_clean_up
Expand Down Expand Up @@ -143,15 +143,15 @@ def main():

start_handler = CommandHandler(BotCommands.StartCommand, start, run_async=True)
ping_handler = CommandHandler(BotCommands.PingCommand, ping,
filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True)
stats_handler = CommandHandler(BotCommands.StatsCommand, stats,
filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True)
log_handler = CommandHandler(BotCommands.LogCommand, log,
filters=CustomFilters.owner_filter, run_async=True)
restart_handler = CommandHandler(BotCommands.RestartCommand, restart,
filters=CustomFilters.owner_filter, run_async=True)
help_handler = CommandHandler(BotCommands.HelpCommand, bot_help,
filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(ping_handler)
dispatcher.add_handler(stats_handler)
Expand Down
7 changes: 1 addition & 6 deletions bot/helper/download_utils/ddl_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@
from bot import APPDRIVE_EMAIL, APPDRIVE_PASS, GDTOT_CRYPT
from bot.helper.ext_utils.exceptions import DDLExceptionHandler

account = {
'email': APPDRIVE_EMAIL,
'passwd': APPDRIVE_PASS
}

def account_login(client, url, email, password):
data = {
'email': email,
Expand All @@ -35,7 +30,7 @@ def appdrive(url: str) -> str:
client.headers.update({
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
})
account_login(client, url, account['email'], account['passwd'])
account_login(client, url, APPDRIVE_EMAIL, APPDRIVE_PASS)
res = client.get(url)
try:
key = re.findall(r'"key",\s+"(.*?)"', res.text)[0]
Expand Down
19 changes: 11 additions & 8 deletions bot/helper/drive_utils/gdriveTools.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
from io import FileIO
from urllib.parse import parse_qs, urlparse
from random import randrange
from telegraph.exceptions import RetryAfterError
from tenacity import retry, wait_exponential, stop_after_attempt, \
retry_if_exception_type, RetryError

from telegraph.exceptions import RetryAfterError

from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
Expand Down Expand Up @@ -123,7 +122,7 @@ def __switchServiceAccount(self):
else:
self.__service_account_index += 1
self.__sa_count += 1
LOGGER.info(f"Authorizing with {self.__service_account_index}.json file")
LOGGER.info(f"Switching SA to {self.__service_account_index}.json file")
self.__service = self.__authorize()

@staticmethod
Expand Down Expand Up @@ -222,6 +221,7 @@ def helper(self, link):
msg = "File not found"
else:
msg = err
LOGGER.error(msg)
return msg, "", "", ""
return "", size, name, files

Expand All @@ -234,9 +234,9 @@ def deleteFile(self, link: str):
return msg
msg = ''
try:
res = self.__service.files().delete(
fileId=file_id,
supportsAllDrives=IS_TEAM_DRIVE).execute()
self.__service.files().delete(
fileId=file_id,
supportsAllDrives=IS_TEAM_DRIVE).execute()
msg = "Permanently deleted"
except HttpError as err:
err = str(err).replace('>', '').replace('<', '')
Expand Down Expand Up @@ -302,6 +302,7 @@ def setPermission(self, link, access):
msg = "Insufficient file permissions"
else:
msg = err
LOGGER.error(msg)
return msg

@retry(wait=wait_exponential(multiplier=2, min=3, max=6),
Expand Down Expand Up @@ -348,7 +349,7 @@ def __copyFile(self, file_id, dest_id):
return self.__copyFile(file_id, dest_id)
else:
self.__is_cancelled = True
LOGGER.info(f"Warning: {reason}")
LOGGER.error(f"Warning: {reason}")
raise err
else:
raise err
Expand Down Expand Up @@ -436,6 +437,7 @@ def clone(self, link, dest_id):
msg = "File not found"
else:
msg = err
LOGGER.error(msg)
return msg

def count(self, link):
Expand Down Expand Up @@ -477,6 +479,7 @@ def count(self, link):
msg = "File not found"
else:
msg = err
LOGGER.error(msg)
return msg

def _progress(self):
Expand Down Expand Up @@ -857,7 +860,7 @@ def drive_list(self, file_name):
self.telegraph_content[i-1] += f'<b> | <a href="https://graph.org/{self.telegraph_path[i]}">Next</a></b>'

self.__edit_page(
TELEGRAPH[(acc_no - 1) if i % page_per_acc == 0 else acc_no],
TELEGRAPH[(acc_no-1) if i % page_per_acc == 0 else acc_no],
self.telegraph_content[i-1],
self.telegraph_path[i-1])

Expand Down
Loading

0 comments on commit 24e8d38

Please sign in to comment.