From e02847966bcead3d5b78b7ac7c04ea029ae94054 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Fri, 16 Feb 2024 22:18:57 -0500 Subject: [PATCH 01/12] Set paths to CONSTs. Create initial debug function. --- lidarr/python/ARLChecker.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index 9625a9b..fff8ce3 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -11,8 +11,16 @@ import logging import os from datetime import datetime +CUSTOM_SERVICES_PATH = '/custom-services.d/' +CUSTOM_INIT_PATH = '/custom-cont_init.d/' +EXTENDED_CONF_PATH = '/config/extended.conf' +NOT_FOUND_PATH = '/config/extended/logs/notfound' +FAILED_DOWNLOADS_PATH = '/config/extended/logs/downloaded/failed/deezer' +STATUS_FALLBACK_LOCATION = '/custom-services.d/python/ARLStatus.txt' + + # Pull script version from bash script. will likely change this to a var passthrough -with open("/custom-services.d/ARLChecker", "r") as r: +with open(CUSTOM_SERVICES_PATH+"ARLChecker", "r") as r: for line in r: if 'scriptVersion' in line: VERSION = re.search(r'"([A-Za-z0-9_\./\\-]*)"', line)[0].replace('"','') @@ -136,7 +144,7 @@ class LidarrExtendedAPI: #self.parentDir = str(workingDir.parents[1]) self.parentDir = str(workingDir.parents[3]) print(self.parentDir) - self.extendedConfDir = self.parentDir + '/config/extended.conf' + self.extendedConfDir = self.parentDir + EXTENDED_CONF_PATH self.newARLToken = new_arl_token self.arlToken = None self.arlLineText = None @@ -251,14 +259,14 @@ class LidarrExtendedAPI: # After new token is set, clean up notfound and failed downloads to bypass the default 30 day wait def clear_not_found(self): - paths = [self.parentDir + '/config/extended/logs/notfound',self.parentDir+'/config/extended/logs/downloaded/failed/deezer'] + paths = [self.parentDir + NOT_FOUND_PATH,self.parentDir+FAILED_DOWNLOADS_PATH] for path in paths: for file in os.listdir(path): file_to_delete = os.path.join(path,file) os.remove(file_to_delete) def report_status(self, status): - f = open("/custom-services.d/python/ARLStatus.txt", "w") + f = open(STATUS_FALLBACK_LOCATION, "w") now = datetime.strftime(datetime.now(),"%b-%d-%Y at %H:%M:%S") f.write(f"{now}: ARL Token is {status}.{' Please update arlToken in extended.conf' if status=='EXPIRED' else ''}") f.close() @@ -384,6 +392,13 @@ def main(arlToken = None): parser.print_help() +def enable_debug(debug_enable = False): + if debug_enable is True: + root = './env/' + else: + root = '' + return root + if __name__ == '__main__': main('FAKETOKEN') From 8da2c1d77f60a63e4ef0ba93fd75edfcc08b6e78 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Fri, 16 Feb 2024 22:28:27 -0500 Subject: [PATCH 02/12] 1.6 dev Set paths to CONSTs. Create initial debug function. --- lidarr/python/ARLChecker.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index fff8ce3..503fe64 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -138,7 +138,11 @@ class DeezerPlatformProvider: class LidarrExtendedAPI: # sets new token to extended.conf - def __init__(self, new_arl_token): + def __init__(self, new_arl_token, root_path=''): + # :param new_ark_token: if running with the -n flag, sets the supplied string as the new token + # :param root_path: change root of all path params to param, for debugging outside the Docker container. + # TODO: change these to be changed in main + self.root = root_path workingDir = Path(os.getcwd()) print(workingDir) #self.parentDir = str(workingDir.parents[1]) From 201e2867fbf4c500dd02c25641acdc5a6ca71d35 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Fri, 16 Feb 2024 22:28:39 -0500 Subject: [PATCH 03/12] 1.6 dev Set paths to CONSTs. Create initial debug function. --- lidarr/ARLChecker | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lidarr/ARLChecker b/lidarr/ARLChecker index 1028f84..0d992eb 100644 --- a/lidarr/ARLChecker +++ b/lidarr/ARLChecker @@ -1,6 +1,6 @@ #!/usr/bin/with-contenv bash ### Default values -scriptVersion="1.5" +scriptVersion="1.6 dev" scriptName="ARLChecker" sleepInterval='24h' ### Import Settings From 1e053a8064a22f6f4e3b9d9a3d78ec2a3a851082 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Fri, 16 Feb 2024 23:50:21 -0500 Subject: [PATCH 04/12] 1.6 dev: debugging setup complete. refactor logging, version fetching to functions. --- lidarr/ARLChecker | 2 +- lidarr/python/ARLChecker.py | 263 ++++++++++++++++++------------------ 2 files changed, 135 insertions(+), 130 deletions(-) diff --git a/lidarr/ARLChecker b/lidarr/ARLChecker index 0d992eb..3204d95 100644 --- a/lidarr/ARLChecker +++ b/lidarr/ARLChecker @@ -1,6 +1,6 @@ #!/usr/bin/with-contenv bash ### Default values -scriptVersion="1.6 dev" +scriptVersion="1.6dev" scriptName="ARLChecker" sleepInterval='24h' ### Import Settings diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index 503fe64..b29b167 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -11,40 +11,15 @@ import logging import os from datetime import datetime +# TODO: Breakout check function to be able to test new ARL tokens + CUSTOM_SERVICES_PATH = '/custom-services.d/' CUSTOM_INIT_PATH = '/custom-cont_init.d/' EXTENDED_CONF_PATH = '/config/extended.conf' NOT_FOUND_PATH = '/config/extended/logs/notfound' FAILED_DOWNLOADS_PATH = '/config/extended/logs/downloaded/failed/deezer' STATUS_FALLBACK_LOCATION = '/custom-services.d/python/ARLStatus.txt' - - -# Pull script version from bash script. will likely change this to a var passthrough -with open(CUSTOM_SERVICES_PATH+"ARLChecker", "r") as r: - for line in r: - if 'scriptVersion' in line: - VERSION = re.search(r'"([A-Za-z0-9_\./\\-]*)"', line)[0].replace('"','') - -# Get current log file -path = '/config/logs' -latest_file = max([os.path.join(path, f) for f in os.listdir(path) if 'ARLChecker' in f],key=os.path.getctime) - -# Logging Setup -logging.basicConfig( - format=f'%(asctime)s :: ARLChecker :: {VERSION} :: %(levelname)s :: %(message)s', - datefmt='%Y-%m-%d %H:%M:%S', - level=logging.INFO, - handlers=[ - logging.StreamHandler(stdout), - logging.FileHandler(latest_file, mode="a") - ] -) -logger = logging.getLogger(__name__) - - - -# Initialize colorama -init(autoreset=True) +LOG_FILES_DIRECTORY = '/config/logs' # Web agent used to access Deezer USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/110.0' @@ -93,6 +68,7 @@ class DeezerPlatformProvider: def __init__(self): super().__init__() + self.log = logging.getLogger('ARLChecker') self.session = Session() self.session.headers.update({'User-Agent': USER_AGENT}) @@ -105,7 +81,7 @@ class DeezerPlatformProvider: ) res.raise_for_status() except Exception as error: - logger.error(Fore.RED + 'Could not connect! Service down, API changed, wrong credentials or code-related issue.' + Fore.LIGHTWHITE_EX) + self.log.error(Fore.RED + 'Could not connect! Service down, API changed, wrong credentials or code-related issue.' + Fore.LIGHTWHITE_EX) raise ConnectionError() self.session.cookies.clear() @@ -113,17 +89,17 @@ class DeezerPlatformProvider: try: res = res.json() except Exception as error: - logger.error(Fore.RED + "Could not parse JSON response from DEEZER!" + Fore.LIGHTWHITE_EX) + self.log.error(Fore.RED + "Could not parse JSON response from DEEZER!" + Fore.LIGHTWHITE_EX) raise ParseError() if 'error' in res and res['error']: - logger.error(Fore.RED + "Deezer returned the following error:{}".format(res["error"]) + Fore.LIGHTWHITE_EX) + self.log.error(Fore.RED + "Deezer returned the following error:{}".format(res["error"]) + Fore.LIGHTWHITE_EX) raise ServiceError() res = res['results'] if res['USER']['USER_ID'] == 0: - logger.error(Fore.RED+"ARL Token Expired. Update the token in extended.conf"+Fore.LIGHTWHITE_EX) + self.log.error(Fore.RED+"ARL Token Expired. Update the token in extended.conf"+Fore.LIGHTWHITE_EX) raise AuthError() return Account(username, secret, res['COUNTRY'], Plan( @@ -138,19 +114,11 @@ class DeezerPlatformProvider: class LidarrExtendedAPI: # sets new token to extended.conf - def __init__(self, new_arl_token, root_path=''): - # :param new_ark_token: if running with the -n flag, sets the supplied string as the new token - # :param root_path: change root of all path params to param, for debugging outside the Docker container. - # TODO: change these to be changed in main - self.root = root_path - workingDir = Path(os.getcwd()) - print(workingDir) - #self.parentDir = str(workingDir.parents[1]) - self.parentDir = str(workingDir.parents[3]) - print(self.parentDir) - self.extendedConfDir = self.parentDir + EXTENDED_CONF_PATH - self.newARLToken = new_arl_token - self.arlToken = None + def __init__(self): + self.root = '' + self.log = logging.getLogger('ARLChecker') + self.newARLToken = None + self.currentARLToken = None self.arlLineText = None self.arlLineIndex = None self.fileText = None @@ -160,23 +128,19 @@ class LidarrExtendedAPI: self.telegram_user_chat_id = None self.telegramBotEnableLineText = None self.telegramBotEnableLineIndex = None - self.bot = None - self.parse_extended_conf() - - def parse_extended_conf(self): - deezer_active = False - self.arlToken = None + self.currentARLToken = None arl_token_match = None + deezer_active = False re_search_pattern = r'"([^"]*)"' try: # Try to open extended.conf and read all text into a var. - with open(self.extendedConfDir, 'r', encoding='utf-8') as file: + with open(self.root+EXTENDED_CONF_PATH, 'r', encoding='utf-8') as file: self.fileText = file.readlines() file.close() except: - logger.error(f"Could not find {self.extendedConfDir}") + self.log.error(f"Could not find {self.root+EXTENDED_CONF_PATH}") exit(1) # Ensure Deezer is enabled and ARL token is populated for line in self.fileText: @@ -190,14 +154,14 @@ class LidarrExtendedAPI: # ARL Token wrong flag error handling. if arl_token_match is None: - logger.error("ARL Token not found in extended.conf. Exiting") + self.log.error("ARL Token not found in extended.conf. Exiting") exit(1) elif deezer_active is False: - logger.error("Deezer not set as an active downloader in extended.conf. Exiting") + self.log.error("Deezer not set as an active downloader in extended.conf. Exiting") file.close() exit(1) - self.arlToken = arl_token_match[0] - logger.info('ARL Found in extended.conf') + self.currentARLToken = arl_token_match[0] + self.log.info('ARL Found in extended.conf') for line in self.fileText: if 'telegramBotEnable=' in line: @@ -211,36 +175,36 @@ class LidarrExtendedAPI: if self.enable_telegram_bot: - logger.info('Telegram bot is enabled.') + self.log.info('Telegram bot is enabled.') if self.telegram_bot_token is None or self.telegram_user_chat_id is None: - logger.error('Telegram bot token or user chat ID not set in extended.conf. Exiting') + self.log.error('Telegram bot token or user chat ID not set in extended.conf. Exiting') exit(1) else: - logger.info('Telegram bot is disabled. Set the flag in extended.conf to enable.') + self.log.info('Telegram bot is disabled. Set the flag in extended.conf to enable.') # Uses DeezerPlatformProvider to check if the token is valid def check_token(self, token=None): - logger.info('Checking ARL Token Validity...') + self.log.info('Checking ARL Token Validity...') if token == '""': - logger.info(Fore.YELLOW+"No ARL Token set in Extended.conf"+Fore.LIGHTWHITE_EX) + self.log.info(Fore.YELLOW+"No ARL Token set in Extended.conf"+Fore.LIGHTWHITE_EX) self.report_status("NOT SET") exit(0) if token is None: - print('Invalid ARL Token Entry') + self.log.error('Invalid ARL Token Entry (None Object)') return False try: deezer_check = DeezerPlatformProvider() account = deezer_check.login('', token.replace('"','')) if account.plan: - logger.info(Fore.GREEN + f'Deezer Account Found.'+ Fore.LIGHTWHITE_EX) - logger.info('-------------------------------') - logger.info(f'Plan: {account.plan.name}') - logger.info(f'Expiration: {account.plan.expires}') - logger.info(f'Active: {Fore.GREEN+"Y" if account.plan.active else "N"}'+Fore.LIGHTWHITE_EX) - logger.info(f'Download: {Fore.GREEN+"Y" if account.plan.download else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) - logger.info(f'Lossless: {Fore.GREEN+"Y" if account.plan.lossless else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) - logger.info(f'Explicit: {Fore.GREEN+"Y" if account.plan.explicit else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) - logger.info('-------------------------------') + self.log.info(Fore.GREEN + f'Deezer Account Found.'+ Fore.LIGHTWHITE_EX) + self.log.info('-------------------------------') + self.log.info(f'Plan: {account.plan.name}') + self.log.info(f'Expiration: {account.plan.expires}') + self.log.info(f'Active: {Fore.GREEN+"Y" if account.plan.active else "N"}'+Fore.LIGHTWHITE_EX) + self.log.info(f'Download: {Fore.GREEN+"Y" if account.plan.download else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) + self.log.info(f'Lossless: {Fore.GREEN+"Y" if account.plan.lossless else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) + self.log.info(f'Explicit: {Fore.GREEN+"Y" if account.plan.explicit else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) + self.log.info('-------------------------------') self.report_status('VALID') return True except Exception as e: @@ -249,17 +213,18 @@ class LidarrExtendedAPI: if self.telegram_bot_running: return False if self.enable_telegram_bot: - logger.info('Starting Telegram bot...Check Telegram and follow instructions.') + self.log.info('Starting Telegram bot...Check Telegram and follow instructions.') self.telegram_bot_running = True self.start_telegram_bot() exit(420) def set_new_token(self): # Re-writes extended.conf with previously read-in text, replacing w/ new ARL - self.fileText[self.arlLineIndex] = self.arlLineText.replace(self.arlToken, self.newARLToken) - with open(self.extendedConfDir, 'w', encoding='utf-8') as file: + self.fileText[self.arlLineIndex] = self.arlLineText.replace(self.currentARLToken, self.newARLToken) + with open(self.root+EXTENDED_CONF_PATH, 'w', encoding='utf-8') as file: file.writelines(self.fileText) file.close() - logger.info("New ARL token written to extended.conf") + self.log.info("New ARL token written to extended.conf") + self.parse_extended_conf() # After new token is set, clean up notfound and failed downloads to bypass the default 30 day wait def clear_not_found(self): @@ -270,7 +235,7 @@ class LidarrExtendedAPI: os.remove(file_to_delete) def report_status(self, status): - f = open(STATUS_FALLBACK_LOCATION, "w") + f = open(self.root+STATUS_FALLBACK_LOCATION, "w") now = datetime.strftime(datetime.now(),"%b-%d-%Y at %H:%M:%S") f.write(f"{now}: ARL Token is {status}.{' Please update arlToken in extended.conf' if status=='EXPIRED' else ''}") f.close() @@ -281,24 +246,26 @@ class LidarrExtendedAPI: def disable_telegram_bot(self): compiled = re.compile(re.escape('true'), re.IGNORECASE) self.fileText[self.telegramBotEnableLineIndex] = compiled.sub('false', self.telegramBotEnableLineText) - with open(self.extendedConfDir, 'w', encoding='utf-8') as file: + with open(self.root+EXTENDED_CONF_PATH, 'w', encoding='utf-8') as file: file.writelines(self.fileText) file.close() - logger.info("Telegram Bot Disabled.") + self.log.info("Telegram Bot Disabled.") class TelegramBotControl: - def __init__(self, parent,telegram_bot_token,telegram_user_chat_id): + def __init__(self, parent, telegram_bot_token, telegram_user_chat_id): + self.log = logging.getLogger('ARLChecker') + self.parent = parent + self.telegram_bot_token = telegram_bot_token + self.telegram_chat_id = telegram_user_chat_id + # Send initial notification async def send_expired_token_notification(application): await application.bot.sendMessage(chat_id=self.telegram_chat_id,text='---\U0001F6A8WARNING\U0001F6A8-----\nARL TOKEN EXPIRED\n Update Token by running "/set_token "\n You can find a new ARL at:\nhttps://rentry.org/firehawk52#deezer-arls\n\n\n Other Commands:\n/cancel - Cancel this session\n/disable - Disable Telegram Bot',disable_web_page_preview=True) # TODO: Get Chat ID/ test on new bot - self.parent = parent - self.telegram_bot_token = telegram_bot_token - self.telegram_chat_id = telegram_user_chat_id # start bot control self.application = ApplicationBuilder().token(self.telegram_bot_token).post_init(send_expired_token_notification).build() token_handler = CommandHandler('set_token', self.set_token) @@ -309,14 +276,12 @@ class TelegramBotControl: self.application.add_handler(disable_handler) self.application.run_polling(allowed_updates=Update.ALL_TYPES) - - async def disable_bot(self, update, context: ContextTypes.DEFAULT_TYPE): + async def disable_bot(self, update): self.parent.disable_telegram_bot() await update.message.reply_text('Disabled Telegram Bot. \U0001F614\nIf you would like to re-enable,\nset telegramBotEnable to true\nin extended.conf') self.application.stop_running() - - async def cancel(self, update, context: ContextTypes.DEFAULT_TYPE): + async def cancel(self, update): await update.message.reply_text('Canceling...ARLToken is still expired.') try: self.application.stop_running() @@ -331,14 +296,11 @@ class TelegramBotControl: await update.message.reply_text('Invalid Entry... please try again.') return print(new_token) - logger.info("Testing ARL Token Validity...") + self.log.info("Testing ARL Token Validity...") token_validity = self.parent.check_token(new_token) if token_validity: await context.bot.send_message(chat_id=update.effective_chat.id, text="ARL valid, applying...") self.parent.newARLToken = '"'+new_token+'"' - self.parent.set_new_token() - self.parent.arlToken = self.parent.newARLToken - # TODO Fix this garbage - move functionality out of telegram stuff await context.bot.send_message(chat_id=update.effective_chat.id, text="Checking configuration") # reparse extended.conf self.parent.parse_extended_conf() @@ -350,59 +312,102 @@ class TelegramBotControl: except Exception: pass - else:# If Token invalid + else: # If Token invalid await update.message.reply_text(text="Token expired or inactive. try another token.") return - -def main(arlToken = None): +def parse_arguments(): parser = ArgumentParser(prog='Account Checker', description='Check if Deezer ARL Token is valid') - parser.add_argument('-c', '--check', help='Check if current ARL Token is active/valid',required=False, default=False, action='store_true') + parser.add_argument('-c', '--check', help='Check if currently set ARL Token is active/valid',required=False, default=False, action='store_true') + parser.add_argument('-t', '--test', help='Test new token for validity', required=False,default=False, action='store_true') + parser.add_argument('-d', '--debug', help='For debug and development', required=False, default=False,action='store_true') parser.add_argument('-n', '--new', help='Set new ARL Token',type = str, required=False, default=False) if not argv[1:]: parser.print_help() parser.exit() - args = parser.parse_args() - arlToken_instance = LidarrExtendedAPI(arlToken) - - if args.check is True: - if arlToken_instance.arlToken == '': - print("ARL Token not set. re-run with -n flag") - exit(1) - try: - arlToken_instance.check_token(arlToken_instance.arlToken) - except Exception as e: - if 'Chat not found' in str(e): - logger.error(Fore.RED + "Chat not found. Check your chat ID in extended.conf, or start a chat with your bot."+Fore.LIGHTWHITE_EX) - elif 'The token' in str(e): - logger.error(Fore.RED + "Check your Bot Token in extended.conf."+Fore.LIGHTWHITE_EX) - else: - print(e) - exit(1) + return parser.parse_args() - elif args.new: - if args.new == '': - print("Please pass new ARL token as an argument") - exit(96) - - arlToken_instance.newARLToken = '"'+args.new+'"' - arlToken_instance.set_new_token() - - else: - parser.print_help() +def get_version(root): + # Pull script version from bash script. will likely change this to a var passthrough + with open(root+CUSTOM_SERVICES_PATH+"ARLChecker", "r") as r: + for line in r: + if 'scriptVersion' in line: + return re.search(r'"([A-Za-z0-9_\./\\-]*)"', line)[0].replace('"','') + logging.error('Script Version not found! Exiting...') + exit(1) -def enable_debug(debug_enable = False): - if debug_enable is True: - root = './env/' - else: - root = '' - return root +def get_active_log(root): + # Get current log file + path = root + LOG_FILES_DIRECTORY + latest_file = max([os.path.join(path, f) for f in os.listdir(path) if 'ARLChecker' in f], key=os.path.getctime) + return latest_file + + +def init_logging(version, log_file_path): + # Logging Setup + logging.basicConfig( + format=f'%(asctime)s :: ARLChecker :: {version} :: %(levelname)s :: %(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + level=logging.INFO, + handlers=[ + logging.StreamHandler(stdout), + logging.FileHandler(log_file_path, mode="a") + ] + ) + logger = logging.getLogger('ARLChecker') + + # Initialize colorama + init(autoreset=True) + logger.info('Logger initialized') + + return logger + + +def main(): + root = '' + args = parse_arguments() + arl_checker_instance = LidarrExtendedAPI() + + if args.debug: + root = './env' + + + log = init_logging(get_version(root), get_active_log(root)) + arl_checker_instance.root = root + #arl_checker_instance.log = log + try: + if args.check is True: + if arl_checker_instance.currentARLToken == '': + log.error("ARL Token not set. re-run with -n flag") + try: + arl_checker_instance.parse_extended_conf() + arl_checker_instance.check_token(arl_checker_instance.currentARLToken) + except Exception as e: + if 'Chat not found' in str(e): + log.error(Fore.RED + "Chat not found. Check your chat ID in extended.conf, or start a chat with your bot."+Fore.LIGHTWHITE_EX) + elif 'The token' in str(e): + log.error(Fore.RED + "Check your Bot Token in extended.conf."+Fore.LIGHTWHITE_EX) + else: + log.error(e) + + elif args.new: + if args.new == '': + print("Please pass new ARL token as an argument") + exit(96) + arl_checker_instance.newARLToken = '"'+args.new+'"' + arl_checker_instance.set_new_token() + + else: + args.print_help() + except Exception as e: + logging.error(e, exc_info=True) + exit(1) if __name__ == '__main__': - main('FAKETOKEN') + main() From 7ee55d58669c40ea1a34fe106555cdfaaf380961 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Tue, 5 Mar 2024 22:27:35 -0500 Subject: [PATCH 05/12] 1.6 dev: debugging setup complete. refactor logging and version fetching to functions. --- lidarr/python/ARLChecker.py | 40 ++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index b29b167..9f66d42 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -1,5 +1,4 @@ import re -from pathlib import Path from dataclasses import dataclass from requests import Session from argparse import ArgumentParser @@ -12,14 +11,14 @@ import os from datetime import datetime # TODO: Breakout check function to be able to test new ARL tokens - -CUSTOM_SERVICES_PATH = '/custom-services.d/' CUSTOM_INIT_PATH = '/custom-cont_init.d/' +CUSTOM_SERVICES_PATH = '/custom-services.d/' +STATUS_FALLBACK_LOCATION = '/custom-services.d/python/ARLStatus.txt' EXTENDED_CONF_PATH = '/config/extended.conf' NOT_FOUND_PATH = '/config/extended/logs/notfound' FAILED_DOWNLOADS_PATH = '/config/extended/logs/downloaded/failed/deezer' -STATUS_FALLBACK_LOCATION = '/custom-services.d/python/ARLStatus.txt' LOG_FILES_DIRECTORY = '/config/logs' +DEBUG_ROOT_PATH = './env' # Web agent used to access Deezer USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/110.0' @@ -228,7 +227,7 @@ class LidarrExtendedAPI: # After new token is set, clean up notfound and failed downloads to bypass the default 30 day wait def clear_not_found(self): - paths = [self.parentDir + NOT_FOUND_PATH,self.parentDir+FAILED_DOWNLOADS_PATH] + paths = [self.root + NOT_FOUND_PATH,self.root+FAILED_DOWNLOADS_PATH] for path in paths: for file in os.listdir(path): file_to_delete = os.path.join(path,file) @@ -252,8 +251,6 @@ class LidarrExtendedAPI: self.log.info("Telegram Bot Disabled.") - - class TelegramBotControl: def __init__(self, parent, telegram_bot_token, telegram_user_chat_id): self.log = logging.getLogger('ARLChecker') @@ -308,7 +305,7 @@ class TelegramBotControl: if token_validity: await context.bot.send_message(chat_id=update.effective_chat.id, text="ARL Updated! \U0001F44D") try: - await self.application.stop_running() + self.application.stop_running() except Exception: pass @@ -318,11 +315,11 @@ class TelegramBotControl: def parse_arguments(): - parser = ArgumentParser(prog='Account Checker', description='Check if Deezer ARL Token is valid') + parser = ArgumentParser(prog='Account Checker', description='Lidarr Extended Deezer ARL Token Tools') parser.add_argument('-c', '--check', help='Check if currently set ARL Token is active/valid',required=False, default=False, action='store_true') - parser.add_argument('-t', '--test', help='Test new token for validity', required=False,default=False, action='store_true') + parser.add_argument('-t', '--test_token', help='Test any token for validity', type=str, required=False, default=False) parser.add_argument('-d', '--debug', help='For debug and development', required=False, default=False,action='store_true') - parser.add_argument('-n', '--new', help='Set new ARL Token',type = str, required=False, default=False) + parser.add_argument('-n', '--new_token', help='Set new ARL Token',type=str, required=False, default=False) if not argv[1:]: parser.print_help() @@ -336,7 +333,7 @@ def get_version(root): with open(root+CUSTOM_SERVICES_PATH+"ARLChecker", "r") as r: for line in r: if 'scriptVersion' in line: - return re.search(r'"([A-Za-z0-9_\./\\-]*)"', line)[0].replace('"','') + return re.search(r'"([A-Za-z0-9_./\\-]*)"', line)[0].replace('"', '') logging.error('Script Version not found! Exiting...') exit(1) @@ -363,7 +360,7 @@ def init_logging(version, log_file_path): # Initialize colorama init(autoreset=True) - logger.info('Logger initialized') + logger.info(Fore.LIGHTWHITE_EX + 'Logger initialized') return logger @@ -371,16 +368,17 @@ def init_logging(version, log_file_path): def main(): root = '' args = parse_arguments() - arl_checker_instance = LidarrExtendedAPI() - - if args.debug: - root = './env' - - + if args.debug is True: # If debug flag set, works with IDE structure + root = DEBUG_ROOT_PATH log = init_logging(get_version(root), get_active_log(root)) - arl_checker_instance.root = root - #arl_checker_instance.log = log + try: + if args.test is True: + log.info("Test flag not currently functioning. Exiting.") + exit(0) + arl_checker_instance = LidarrExtendedAPI() + arl_checker_instance.root = root + if args.check is True: if arl_checker_instance.currentARLToken == '': log.error("ARL Token not set. re-run with -n flag") From ff1131e471504cbf1d5c361f8fe16a751068adb7 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Tue, 5 Mar 2024 22:32:09 -0500 Subject: [PATCH 06/12] 1.6 dev: debugging setup complete. refactor logging and version fetching to functions. --- lidarr/python/ARLChecker.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index 9f66d42..03d00d4 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -317,9 +317,10 @@ class TelegramBotControl: def parse_arguments(): parser = ArgumentParser(prog='Account Checker', description='Lidarr Extended Deezer ARL Token Tools') parser.add_argument('-c', '--check', help='Check if currently set ARL Token is active/valid',required=False, default=False, action='store_true') + parser.add_argument('-n', '--new_token', help='Set new ARL Token', type=str, required=False, default=False) parser.add_argument('-t', '--test_token', help='Test any token for validity', type=str, required=False, default=False) - parser.add_argument('-d', '--debug', help='For debug and development', required=False, default=False,action='store_true') - parser.add_argument('-n', '--new_token', help='Set new ARL Token',type=str, required=False, default=False) + parser.add_argument('-d', '--debug', help='For debug and development, sets root path to match testing env. See DEBUG_ROOT_PATH', required=False, default=False,action='store_true') + if not argv[1:]: parser.print_help() From 612fa48d9e45d130b2a99fefe04429d317c4d268 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Wed, 6 Mar 2024 00:10:57 -0500 Subject: [PATCH 07/12] 1.6 dev: Added Telegram Bot Messages to Logs, Colored yellow in Terminal output. --- lidarr/python/ARLChecker.py | 53 +++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index 03d00d4..d5eb74d 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -98,7 +98,6 @@ class DeezerPlatformProvider: res = res['results'] if res['USER']['USER_ID'] == 0: - self.log.error(Fore.RED+"ARL Token Expired. Update the token in extended.conf"+Fore.LIGHTWHITE_EX) raise AuthError() return Account(username, secret, res['COUNTRY'], Plan( @@ -207,12 +206,15 @@ class LidarrExtendedAPI: self.report_status('VALID') return True except Exception as e: - print(e) + if type(e) == AuthError: + self.log.error(Fore.RED+"ARL Token Expired/Invalid. Update the token in extended.conf"+Fore.LIGHTWHITE_EX) + else: + self.log.error(e) self.report_status('EXPIRED') if self.telegram_bot_running: return False if self.enable_telegram_bot: - self.log.info('Starting Telegram bot...Check Telegram and follow instructions.') + self.log.info(Fore.YELLOW + 'Starting Telegram bot...Check Telegram and follow instructions.' + Fore.LIGHTWHITE_EX) self.telegram_bot_running = True self.start_telegram_bot() exit(420) @@ -261,6 +263,7 @@ class TelegramBotControl: # Send initial notification async def send_expired_token_notification(application): await application.bot.sendMessage(chat_id=self.telegram_chat_id,text='---\U0001F6A8WARNING\U0001F6A8-----\nARL TOKEN EXPIRED\n Update Token by running "/set_token "\n You can find a new ARL at:\nhttps://rentry.org/firehawk52#deezer-arls\n\n\n Other Commands:\n/cancel - Cancel this session\n/disable - Disable Telegram Bot',disable_web_page_preview=True) + self.log.info(Fore.YELLOW + "Telegram Bot Sent ARL Token Expiry Message " + Fore.LIGHTWHITE_EX) # TODO: Get Chat ID/ test on new bot # start bot control @@ -273,44 +276,54 @@ class TelegramBotControl: self.application.add_handler(disable_handler) self.application.run_polling(allowed_updates=Update.ALL_TYPES) - async def disable_bot(self, update): + async def disable_bot(self, update, context: ContextTypes.DEFAULT_TYPE): self.parent.disable_telegram_bot() await update.message.reply_text('Disabled Telegram Bot. \U0001F614\nIf you would like to re-enable,\nset telegramBotEnable to true\nin extended.conf') + self.log.info(Fore.YELLOW + 'Telegram Bot: Send Disable Bot Message :(' + Fore.LIGHTWHITE_EX) self.application.stop_running() - async def cancel(self, update): + async def cancel(self, update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text('Canceling...ARLToken is still expired.') + self.log.info(Fore.YELLOW + 'Telegram Bot: Canceling...ARLToken is still expired.' + Fore.LIGHTWHITE_EX) try: self.application.stop_running() except Exception: pass async def set_token(self, update, context: ContextTypes.DEFAULT_TYPE): + async def send_message(text, reply=False): + if reply is True: + await update.message.reply_text(text=text) + else: + await context.bot.send_message(chat_id=update.effective_chat.id, text=text) + self.log.info(Fore.YELLOW+"Telegram Bot: " + text + Fore.LIGHTWHITE_EX) try: new_token = update.message.text.split('/set_token ')[1] if new_token == '': raise Exception except: - await update.message.reply_text('Invalid Entry... please try again.') + await update.message.reply_text('Invalid Entry... Please try again.') return - print(new_token) - self.log.info("Testing ARL Token Validity...") + self.log.info(Fore.YELLOW+f"Telegram Bot:Token received: {new_token}" + Fore.LIGHTWHITE_EX) token_validity = self.parent.check_token(new_token) if token_validity: - await context.bot.send_message(chat_id=update.effective_chat.id, text="ARL valid, applying...") + # await context.bot.send_message(chat_id=update.effective_chat.id, text="ARL valid, applying...") + # self.log.info(Fore.YELLOW+"TELEGRAM BOT SENT: ARL valid, applying..."+Fore.LIGHTWHITE_EX) + await send_message("ARL valid, applying...") self.parent.newARLToken = '"'+new_token+'"' - await context.bot.send_message(chat_id=update.effective_chat.id, text="Checking configuration") + self.parent.set_new_token() + await send_message("Checking configuration") # reparse extended.conf self.parent.parse_extended_conf() - token_validity = self.parent.check_token(self.parent.arlToken) + token_validity = self.parent.check_token(self.parent.currentARLToken) if token_validity: - await context.bot.send_message(chat_id=update.effective_chat.id, text="ARL Updated! \U0001F44D") + await send_message("ARL Token Updated! \U0001F44D",reply=True) try: self.application.stop_running() except Exception: pass else: # If Token invalid - await update.message.reply_text(text="Token expired or inactive. try another token.") + await send_message("Token expired or invalid. Try another token.", reply=True) return @@ -326,7 +339,7 @@ def parse_arguments(): parser.print_help() parser.exit() - return parser.parse_args() + return parser, parser.parse_args() def get_version(root): @@ -354,7 +367,7 @@ def init_logging(version, log_file_path): level=logging.INFO, handlers=[ logging.StreamHandler(stdout), - logging.FileHandler(log_file_path, mode="a") + logging.FileHandler(log_file_path, mode="a", encoding='utf-8') ] ) logger = logging.getLogger('ARLChecker') @@ -368,13 +381,13 @@ def init_logging(version, log_file_path): def main(): root = '' - args = parse_arguments() + parser, args = parse_arguments() if args.debug is True: # If debug flag set, works with IDE structure root = DEBUG_ROOT_PATH log = init_logging(get_version(root), get_active_log(root)) try: - if args.test is True: + if args.test_token is True: log.info("Test flag not currently functioning. Exiting.") exit(0) arl_checker_instance = LidarrExtendedAPI() @@ -394,15 +407,15 @@ def main(): else: log.error(e) - elif args.new: + elif args.new_token: if args.new == '': - print("Please pass new ARL token as an argument") + log.error('Please pass new ARL token as an argument') exit(96) arl_checker_instance.newARLToken = '"'+args.new+'"' arl_checker_instance.set_new_token() else: - args.print_help() + parser.print_help() except Exception as e: logging.error(e, exc_info=True) exit(1) From 79f13d273e16865f7777d629b928b9bd7b4f47f3 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Wed, 6 Mar 2024 23:13:18 -0500 Subject: [PATCH 08/12] 1.6 dev: Error Handling for -t flag --- lidarr/python/ARLChecker.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index d5eb74d..6f76b49 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -387,7 +387,7 @@ def main(): log = init_logging(get_version(root), get_active_log(root)) try: - if args.test_token is True: + if args.test_token: log.info("Test flag not currently functioning. Exiting.") exit(0) arl_checker_instance = LidarrExtendedAPI() @@ -408,10 +408,11 @@ def main(): log.error(e) elif args.new_token: - if args.new == '': + if args.new_token == '': log.error('Please pass new ARL token as an argument') exit(96) - arl_checker_instance.newARLToken = '"'+args.new+'"' + arl_checker_instance.newARLToken = '"'+args.new_token+'"' + arl_checker_instance.parse_extended_conf() arl_checker_instance.set_new_token() else: From 88d4e8422321000ecc7625a1787c6e2b204d2eef Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Wed, 6 Mar 2024 23:50:56 -0500 Subject: [PATCH 09/12] 1.6 dev: Broke out check function outside of LidarrExtendedAPI. Allows -c and -t flags to share the same function. Write Wrapper function inside LidarrExtendedAPI. --- lidarr/python/ARLChecker.py | 80 ++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index 6f76b49..66e28a8 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -10,7 +10,6 @@ import logging import os from datetime import datetime -# TODO: Breakout check function to be able to test new ARL tokens CUSTOM_INIT_PATH = '/custom-cont_init.d/' CUSTOM_SERVICES_PATH = '/custom-services.d/' STATUS_FALLBACK_LOCATION = '/custom-services.d/python/ARLStatus.txt' @@ -180,38 +179,22 @@ class LidarrExtendedAPI: else: self.log.info('Telegram bot is disabled. Set the flag in extended.conf to enable.') - # Uses DeezerPlatformProvider to check if the token is valid - def check_token(self, token=None): - self.log.info('Checking ARL Token Validity...') - if token == '""': + def check_token_wrapper(self): # adds Lidarr_extended specific logging and actions around check_token + self.log.info("Checking ARL Token from extended.conf") + if self.currentARLToken == '""': self.log.info(Fore.YELLOW+"No ARL Token set in Extended.conf"+Fore.LIGHTWHITE_EX) self.report_status("NOT SET") exit(0) - if token is None: + if self.currentARLToken is None: self.log.error('Invalid ARL Token Entry (None Object)') return False - try: - deezer_check = DeezerPlatformProvider() - account = deezer_check.login('', token.replace('"','')) - if account.plan: - self.log.info(Fore.GREEN + f'Deezer Account Found.'+ Fore.LIGHTWHITE_EX) - self.log.info('-------------------------------') - self.log.info(f'Plan: {account.plan.name}') - self.log.info(f'Expiration: {account.plan.expires}') - self.log.info(f'Active: {Fore.GREEN+"Y" if account.plan.active else "N"}'+Fore.LIGHTWHITE_EX) - self.log.info(f'Download: {Fore.GREEN+"Y" if account.plan.download else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) - self.log.info(f'Lossless: {Fore.GREEN+"Y" if account.plan.lossless else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) - self.log.info(f'Explicit: {Fore.GREEN+"Y" if account.plan.explicit else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) - self.log.info('-------------------------------') - self.report_status('VALID') - return True - except Exception as e: - if type(e) == AuthError: - self.log.error(Fore.RED+"ARL Token Expired/Invalid. Update the token in extended.conf"+Fore.LIGHTWHITE_EX) - else: - self.log.error(e) + validity_results = check_token(self.currentARLToken) + if validity_results is True: + self.report_status('VALID') # For text fallback method + else: self.report_status('EXPIRED') - if self.telegram_bot_running: + self.log.error(Fore.RED + 'Update the token in extended.conf' + Fore.LIGHTWHITE_EX) + if self.telegram_bot_running: # Don't re-start the telegram bot if it's alread running after bot invalid token entry return False if self.enable_telegram_bot: self.log.info(Fore.YELLOW + 'Starting Telegram bot...Check Telegram and follow instructions.' + Fore.LIGHTWHITE_EX) @@ -304,17 +287,15 @@ class TelegramBotControl: await update.message.reply_text('Invalid Entry... Please try again.') return self.log.info(Fore.YELLOW+f"Telegram Bot:Token received: {new_token}" + Fore.LIGHTWHITE_EX) - token_validity = self.parent.check_token(new_token) + token_validity = check_token(new_token) if token_validity: - # await context.bot.send_message(chat_id=update.effective_chat.id, text="ARL valid, applying...") - # self.log.info(Fore.YELLOW+"TELEGRAM BOT SENT: ARL valid, applying..."+Fore.LIGHTWHITE_EX) await send_message("ARL valid, applying...") self.parent.newARLToken = '"'+new_token+'"' self.parent.set_new_token() - await send_message("Checking configuration") + await send_message("Checking configuration...") # reparse extended.conf self.parent.parse_extended_conf() - token_validity = self.parent.check_token(self.parent.currentARLToken) + token_validity = check_token(self.parent.currentARLToken) if token_validity: await send_message("ARL Token Updated! \U0001F44D",reply=True) try: @@ -327,6 +308,33 @@ class TelegramBotControl: return +def check_token(token=None): + log = logging.getLogger('ARLChecker') + log.info(f"ARL Token to check: {token}") + log.info('Checking ARL Token Validity...') + try: + deezer_check = DeezerPlatformProvider() + account = deezer_check.login('', token.replace('"','')) + if account.plan: + log.info(Fore.GREEN + f'Deezer Account Found.'+ Fore.LIGHTWHITE_EX) + log.info('-------------------------------') + log.info(f'Plan: {account.plan.name}') + log.info(f'Expiration: {account.plan.expires}') + log.info(f'Active: {Fore.GREEN+"Y" if account.plan.active else "N"}'+Fore.LIGHTWHITE_EX) + log.info(f'Download: {Fore.GREEN+"Y" if account.plan.download else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) + log.info(f'Lossless: {Fore.GREEN+"Y" if account.plan.lossless else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) + log.info(f'Explicit: {Fore.GREEN+"Y" if account.plan.explicit else Fore.RED+"N"}'+Fore.LIGHTWHITE_EX) + log.info('-------------------------------') + return True + except Exception as e: + if type(e) == AuthError: + log.error(Fore.RED + 'ARL Token Invalid/Expired.' + Fore.LIGHTWHITE_EX) + return False + else: + log.error(e) + return + + def parse_arguments(): parser = ArgumentParser(prog='Account Checker', description='Lidarr Extended Deezer ARL Token Tools') parser.add_argument('-c', '--check', help='Check if currently set ARL Token is active/valid',required=False, default=False, action='store_true') @@ -374,7 +382,7 @@ def init_logging(version, log_file_path): # Initialize colorama init(autoreset=True) - logger.info(Fore.LIGHTWHITE_EX + 'Logger initialized') + logger.info(Fore.GREEN + 'Logger initialized'+Fore.LIGHTWHITE_EX) return logger @@ -388,17 +396,17 @@ def main(): try: if args.test_token: - log.info("Test flag not currently functioning. Exiting.") + log.info(Fore.CYAN+"CLI Token Tester"+Fore.LIGHTWHITE_EX) + check_token(args.test_token) exit(0) arl_checker_instance = LidarrExtendedAPI() arl_checker_instance.root = root - if args.check is True: if arl_checker_instance.currentARLToken == '': log.error("ARL Token not set. re-run with -n flag") try: arl_checker_instance.parse_extended_conf() - arl_checker_instance.check_token(arl_checker_instance.currentARLToken) + arl_checker_instance.check_token_wrapper() except Exception as e: if 'Chat not found' in str(e): log.error(Fore.RED + "Chat not found. Check your chat ID in extended.conf, or start a chat with your bot."+Fore.LIGHTWHITE_EX) From c460898694d4bec583ebe4f3370844b6f8937e69 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Thu, 7 Mar 2024 22:48:02 -0500 Subject: [PATCH 10/12] 1.6: Refactor --- lidarr/python/ARLChecker.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index 66e28a8..a5992aa 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -151,10 +151,10 @@ class LidarrExtendedAPI: # ARL Token wrong flag error handling. if arl_token_match is None: - self.log.error("ARL Token not found in extended.conf. Exiting") + self.log.error("ARL Token not found in extended.conf. Exiting.") exit(1) elif deezer_active is False: - self.log.error("Deezer not set as an active downloader in extended.conf. Exiting") + self.log.error("Deezer not set as an active downloader in extended.conf. Exiting.") file.close() exit(1) self.currentARLToken = arl_token_match[0] @@ -173,6 +173,7 @@ class LidarrExtendedAPI: if self.enable_telegram_bot: self.log.info('Telegram bot is enabled.') + if self.telegram_bot_token is None or self.telegram_user_chat_id is None: self.log.error('Telegram bot token or user chat ID not set in extended.conf. Exiting') exit(1) @@ -408,7 +409,7 @@ def main(): arl_checker_instance.parse_extended_conf() arl_checker_instance.check_token_wrapper() except Exception as e: - if 'Chat not found' in str(e): + if 'Chat not found' in str(e) or 'Chat_id' in str(e): log.error(Fore.RED + "Chat not found. Check your chat ID in extended.conf, or start a chat with your bot."+Fore.LIGHTWHITE_EX) elif 'The token' in str(e): log.error(Fore.RED + "Check your Bot Token in extended.conf."+Fore.LIGHTWHITE_EX) @@ -431,4 +432,4 @@ def main(): if __name__ == '__main__': - main() + main() \ No newline at end of file From cb8dbdd79b1a7ead0333e7330319156f47cdf4f9 Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Thu, 7 Mar 2024 22:52:44 -0500 Subject: [PATCH 11/12] 1.6: Error Handling Improvements --- lidarr/python/ARLChecker.py | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/lidarr/python/ARLChecker.py b/lidarr/python/ARLChecker.py index a5992aa..ba933c4 100644 --- a/lidarr/python/ARLChecker.py +++ b/lidarr/python/ARLChecker.py @@ -22,6 +22,7 @@ DEBUG_ROOT_PATH = './env' # Web agent used to access Deezer USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/110.0' + @dataclass class Plan: name: str @@ -169,7 +170,6 @@ class LidarrExtendedAPI: self.telegram_bot_token = re.search(re_search_pattern, line)[0].replace('"', '') if 'telegramUserChatID=' in line: self.telegram_user_chat_id = re.search(re_search_pattern, line)[0].replace('"', '') - if self.enable_telegram_bot: self.log.info('Telegram bot is enabled.') @@ -180,7 +180,7 @@ class LidarrExtendedAPI: else: self.log.info('Telegram bot is disabled. Set the flag in extended.conf to enable.') - def check_token_wrapper(self): # adds Lidarr_extended specific logging and actions around check_token + def check_token_wrapper(self): # adds Lidarr_extended specific logging and actions around check_token self.log.info("Checking ARL Token from extended.conf") if self.currentARLToken == '""': self.log.info(Fore.YELLOW+"No ARL Token set in Extended.conf"+Fore.LIGHTWHITE_EX) @@ -191,11 +191,11 @@ class LidarrExtendedAPI: return False validity_results = check_token(self.currentARLToken) if validity_results is True: - self.report_status('VALID') # For text fallback method + self.report_status('VALID') # For text fallback method else: self.report_status('EXPIRED') self.log.error(Fore.RED + 'Update the token in extended.conf' + Fore.LIGHTWHITE_EX) - if self.telegram_bot_running: # Don't re-start the telegram bot if it's alread running after bot invalid token entry + if self.telegram_bot_running: # Don't re-start the telegram bot if it's already running after bot invalid token entry return False if self.enable_telegram_bot: self.log.info(Fore.YELLOW + 'Starting Telegram bot...Check Telegram and follow instructions.' + Fore.LIGHTWHITE_EX) @@ -213,20 +213,20 @@ class LidarrExtendedAPI: # After new token is set, clean up notfound and failed downloads to bypass the default 30 day wait def clear_not_found(self): - paths = [self.root + NOT_FOUND_PATH,self.root+FAILED_DOWNLOADS_PATH] + paths = [self.root + NOT_FOUND_PATH, self.root+FAILED_DOWNLOADS_PATH] for path in paths: for file in os.listdir(path): - file_to_delete = os.path.join(path,file) + file_to_delete = os.path.join(path, file) os.remove(file_to_delete) def report_status(self, status): f = open(self.root+STATUS_FALLBACK_LOCATION, "w") - now = datetime.strftime(datetime.now(),"%b-%d-%Y at %H:%M:%S") + now = datetime.strftime(datetime.now(), "%b-%d-%Y at %H:%M:%S") f.write(f"{now}: ARL Token is {status}.{' Please update arlToken in extended.conf' if status=='EXPIRED' else ''}") f.close() def start_telegram_bot(self): - self.bot = TelegramBotControl(self,self.telegram_bot_token,self.telegram_user_chat_id) + self.bot = TelegramBotControl(self, self.telegram_bot_token, self.telegram_user_chat_id) def disable_telegram_bot(self): compiled = re.compile(re.escape('true'), re.IGNORECASE) @@ -246,7 +246,7 @@ class TelegramBotControl: # Send initial notification async def send_expired_token_notification(application): - await application.bot.sendMessage(chat_id=self.telegram_chat_id,text='---\U0001F6A8WARNING\U0001F6A8-----\nARL TOKEN EXPIRED\n Update Token by running "/set_token "\n You can find a new ARL at:\nhttps://rentry.org/firehawk52#deezer-arls\n\n\n Other Commands:\n/cancel - Cancel this session\n/disable - Disable Telegram Bot',disable_web_page_preview=True) + await application.bot.sendMessage(chat_id=self.telegram_chat_id, text='---\U0001F6A8WARNING\U0001F6A8-----\nARL TOKEN EXPIRED\n Update Token by running "/set_token "\n You can find a new ARL at:\nhttps://rentry.org/firehawk52#deezer-arls\n\n\n Other Commands:\n/cancel - Cancel this session\n/disable - Disable Telegram Bot', disable_web_page_preview=True) self.log.info(Fore.YELLOW + "Telegram Bot Sent ARL Token Expiry Message " + Fore.LIGHTWHITE_EX) # TODO: Get Chat ID/ test on new bot @@ -260,7 +260,7 @@ class TelegramBotControl: self.application.add_handler(disable_handler) self.application.run_polling(allowed_updates=Update.ALL_TYPES) - async def disable_bot(self, update, context: ContextTypes.DEFAULT_TYPE): + async def disable_bot(self, update, context: ContextTypes.DEFAULT_TYPE): self.parent.disable_telegram_bot() await update.message.reply_text('Disabled Telegram Bot. \U0001F614\nIf you would like to re-enable,\nset telegramBotEnable to true\nin extended.conf') self.log.info(Fore.YELLOW + 'Telegram Bot: Send Disable Bot Message :(' + Fore.LIGHTWHITE_EX) @@ -273,6 +273,7 @@ class TelegramBotControl: self.application.stop_running() except Exception: pass + async def set_token(self, update, context: ContextTypes.DEFAULT_TYPE): async def send_message(text, reply=False): if reply is True: @@ -298,7 +299,7 @@ class TelegramBotControl: self.parent.parse_extended_conf() token_validity = check_token(self.parent.currentARLToken) if token_validity: - await send_message("ARL Token Updated! \U0001F44D",reply=True) + await send_message("ARL Token Updated! \U0001F44D", reply=True) try: self.application.stop_running() except Exception: @@ -315,9 +316,9 @@ def check_token(token=None): log.info('Checking ARL Token Validity...') try: deezer_check = DeezerPlatformProvider() - account = deezer_check.login('', token.replace('"','')) + account = deezer_check.login('', token.replace('"', '')) if account.plan: - log.info(Fore.GREEN + f'Deezer Account Found.'+ Fore.LIGHTWHITE_EX) + log.info(Fore.GREEN + f'Deezer Account Found.' + Fore.LIGHTWHITE_EX) log.info('-------------------------------') log.info(f'Plan: {account.plan.name}') log.info(f'Expiration: {account.plan.expires}') @@ -328,7 +329,7 @@ def check_token(token=None): log.info('-------------------------------') return True except Exception as e: - if type(e) == AuthError: + if type(e) is AuthError: log.error(Fore.RED + 'ARL Token Invalid/Expired.' + Fore.LIGHTWHITE_EX) return False else: @@ -338,11 +339,10 @@ def check_token(token=None): def parse_arguments(): parser = ArgumentParser(prog='Account Checker', description='Lidarr Extended Deezer ARL Token Tools') - parser.add_argument('-c', '--check', help='Check if currently set ARL Token is active/valid',required=False, default=False, action='store_true') + parser.add_argument('-c', '--check', help='Check if currently set ARL Token is active/valid', required=False, default=False, action='store_true') parser.add_argument('-n', '--new_token', help='Set new ARL Token', type=str, required=False, default=False) parser.add_argument('-t', '--test_token', help='Test any token for validity', type=str, required=False, default=False) - parser.add_argument('-d', '--debug', help='For debug and development, sets root path to match testing env. See DEBUG_ROOT_PATH', required=False, default=False,action='store_true') - + parser.add_argument('-d', '--debug', help='For debug and development, sets root path to match testing env. See DEBUG_ROOT_PATH', required=False, default=False, action='store_true') if not argv[1:]: parser.print_help() @@ -432,4 +432,4 @@ def main(): if __name__ == '__main__': - main() \ No newline at end of file + main() From 7ab4ecd0f6fd63618eb90c4745c1eebb810b14db Mon Sep 17 00:00:00 2001 From: hockeygoalie35 Date: Thu, 7 Mar 2024 22:54:12 -0500 Subject: [PATCH 12/12] 1.6: Refactor, -t and -d flags added. --- lidarr/ARLChecker | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lidarr/ARLChecker b/lidarr/ARLChecker index 3204d95..7d2dbc5 100644 --- a/lidarr/ARLChecker +++ b/lidarr/ARLChecker @@ -1,6 +1,6 @@ #!/usr/bin/with-contenv bash ### Default values -scriptVersion="1.6dev" +scriptVersion="1.6" scriptName="ARLChecker" sleepInterval='24h' ### Import Settings