diff --git a/.gitignore b/.gitignore index ea880ec..c6d8d54 100644 --- a/.gitignore +++ b/.gitignore @@ -131,4 +131,5 @@ dmypy.json /.idea/* -databases/* \ No newline at end of file +databases/* +/discordHelper/discordHelper_last_run.json.yaml diff --git a/discordHelper.py b/discordHelper.py index a500207..e57ed34 100644 --- a/discordHelper.py +++ b/discordHelper.py @@ -12,7 +12,7 @@ def main(argm): :param argm: List of arguments :type argm: argparse.Namespace """ - agnostic_path = agnostic_paths.AgnosticPaths(argm.ptb, argm.force_path) + agnostic_path = agnostic_paths.AgnosticPaths(argm) test_runner = main_runner.run_check(argm, agnostic_path) diff --git a/discordHelperWin.py b/discordHelperWin.py index 38ed48d..1b9a7d7 100644 --- a/discordHelperWin.py +++ b/discordHelperWin.py @@ -3,19 +3,38 @@ A windows executable for the discordHelper.py script. """ import os import sys - import discordHelper import time # All modules must be loaded before the main program is run. from modules import spidey_test, test_template - if __name__ == "__main__": - argv = sys.argv[1:] - if len(argv) == 0: - user_path = os.path.join(os.path.expanduser("~"), "Documents", "DiscordHelper") - argv = f"--all --launch --continue --timeout 12 --gen-data {user_path}/new_test_data_{int(time.time())}.yaml".split(" ") + try: + argv = sys.argv[1:] + if len(argv) == 0: + directory_path = os.path.join(os.getcwd(), "discordHelper") + db_path = os.path.join(directory_path, "windows_base.json") + argv = ["-p", db_path] + if os.path.exists(db_path): + # print(" > A user database was found it will be used instead of the bundled one.") + # print(" > If you want to use the bundled database, delete the file: " + db_path) + db_path = "--database " + db_path + " " + else: + db_path = "" + # print(" > No user database was found, the bundled one will be used.") - args = discordHelper.argument_parser.parse(argv) - discordHelper.main(args) + run_db = os.path.join(directory_path, "discordHelper_last_run.json") + argv = f"--all --autodetect --launch --continue --timeout 10 {db_path}--gen-data {run_db}.yaml".split(" ") + + # print(" > Starting the discordHelper with the following arguments:") + # print(" > " + " ".join(argv)) + + args = discordHelper.argument_parser.parse(argv) + + discordHelper.main(args) + except Exception as e: + print(e) + print(" > An error occured, please check the console for more information...") + time.sleep(5) + raise SystemExit diff --git a/modules/agnostic_paths.py b/modules/agnostic_paths.py index d618dee..11b0cc8 100644 --- a/modules/agnostic_paths.py +++ b/modules/agnostic_paths.py @@ -11,17 +11,16 @@ class AgnosticPaths: An agnostic path object, containing all methods to access the files and folders in a standard discord install """ - def __init__(self, ptb, force_path=None): + def __init__(self, args): """ - :param ptb: Whether the discord is a public beta install (ptb="PTB") or not (ptb="") - :type ptb: str - :param force_path: An alternative discord install path, usefull to test the script on a non standard install - :type force_path: str + :param args: The arguments passed to the script + :type args: argparse.Namespace """ - self.ptb = ptb + self.args = args + self.ptb = args.ptb self.os = self.get_os() - if force_path is not None: - self.force_path = force_path[0] + if args.force_path is not None: + self.force_path = args.force_path[0] else: self.force_path = None self.main_path = self._get_path() @@ -59,11 +58,17 @@ class AgnosticPaths: return self.force_path if self.os == 'windows': base_path = os.path.join(os.path.expanduser('~'), "AppData", "Local", f"Discord") + ptb_path = base_path+"PTB" + if self.args.autodetect: + if os.path.exists(ptb_path): + self.ptb = "PTB" + self.args.ptb = "PTB" + return ptb_path + else: + return base_path if self.ptb == 'PTB': return base_path+"PTB" else: - if os.path.exists(base_path): - return base_path return base_path+"PTB" # Try to find the PTB version elif self.os == 'linux': return os.path.join("/", "opt", "discord") @@ -175,13 +180,3 @@ class AgnosticPaths: :rtype: str """ return self.main_path - - -if __name__ == '__main__': - path = AgnosticPaths("") - print(path) - print(path.version) - print(path.list()) - print(path()) - print(path("resources", "bootstrap")) # Return the main_path plus resources, bootstrap - print(path.list_dir_files("resources", "bootstrap")) # List the base_path/resources/bootstrap and return [[folders], [files]] diff --git a/modules/argument_parser.py b/modules/argument_parser.py index 79700c5..9f477f8 100644 --- a/modules/argument_parser.py +++ b/modules/argument_parser.py @@ -8,6 +8,7 @@ def parse(_args): ) parser.add_argument('--ptb', action='store_const', const="PTB", default="", help='Force use of Public Test Version') + parser.add_argument('--autodetect', action='store_true', help='Try to autodetect the discord folder, will override --ptb') # General arguments parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0') diff --git a/modules/internal_io.py b/modules/internal_io.py index 27d57ac..7fc0fd1 100644 --- a/modules/internal_io.py +++ b/modules/internal_io.py @@ -7,10 +7,13 @@ from collections import namedtuple global_status = namedtuple( 'global_status', - 'tests_total, tests_finished, test_success, tests_failed, tests_running, tests_skipped, tests_error', - defaults=(0, 0, 0, 0, 0, 0, 0) + 'tests_total, tests_finished, tests_success, tests_failed, tests_running, tests_skipped, tests_error, progress', + defaults=(0, 0, 0, 0, 0, 0, 0, 0) +) +test_status = namedtuple( + 'test_status', 'name, status, message, failure_dict, data, progress', + defaults=(None, None, None, {}, {}, 0) ) -test_status = namedtuple('test_status', 'name, status, message, failure_dict, data', defaults=(None, None, None, {}, {})) return_code_dict = { "skipped": "The test was not run", "running": "The test is running", diff --git a/modules/main_runner.py b/modules/main_runner.py index 4551b70..7ccefcc 100644 --- a/modules/main_runner.py +++ b/modules/main_runner.py @@ -12,47 +12,58 @@ All modules that can be tested Associate the arguments passed to the command line with the modules to be loaded argparse argument : [module_name, class_name] """ +from termcolor import colored, cprint +os.system('color') +# red, green, yellow, blue, magenta, cyan, white. + _TEST_MODULES = { "spidey": ["spidey_test", "SpideyTest"], - #"test_walk": ["test_template", "TestWalkTemplate"], + # "test_walk": ["test_template", "TestWalkTemplate"], } PROGRAM_VERSION = "1.0.0" POST_RUN_ALLOWED = False +RUN_OVER = False queue_lock = threading.Lock() -CLEAR_CODE = r""" +CLEAR_CODE = colored(r""" _______ _ (_______) | _ | | _____ _____ ____ | | | || ___ (____ |/ ___) | |_____| || ____/ ___ | | \______)\_)_____)_____|_| - """ + """, 'green') -INFECTED_CODE = r""" +INFECTED_CODE = colored(r""" _ ___ _ | | / __) _ | | | |____ _| |__ _____ ____ _| |_ _____ __| | | | _ (_ __) ___ |/ ___|_ _) ___ |/ _ | | | | | || | | ____( (___ | |_| ____( (_| | |_|_| |_||_| |_____)\____) \__)_____)\____| -""" +""", 'red') -if os.name == "nt": - CLEAR_CODE = r"" + CLEAR_CODE + r"" - INFECTED_CODE = r"" + INFECTED_CODE + r"" +LOGO = colored(r""" + __ \ _) | | | | + | | | __| __| _ \ __| _` | | | _ \ | __ \ _ \ __| + | | | \__ \ ( ( | | ( | ___ | __/ | | | __/ | + ____/ _| ____/ \___| \___/ _| \__,_| _| _| \___| _| .__/ \___| _| + _| +""", "cyan") class TestRunner: - def __init__(self, args, agnpath): + def __init__(self, args, agnpath, start_time): """ Main spidey runner :param args: List of arguments :type args: argparse.Namespace :param agnpath: The path to the discord folder :type agnpath: agnostic_path.AgnosticPath + :param start_time: The time the test started + :type start_time: float """ self.ptb = args.ptb self.args = args @@ -60,6 +71,7 @@ class TestRunner: self.os_name = agnpath.os self.main_path = agnpath.main_path self.version = agnpath.version + self.start_time = start_time self.is_infected = 0 self.detections = 0 @@ -104,7 +116,7 @@ class TestRunner: """ self.list_of_tests = [] for module_name, test_class in self.loaded_test_classes.items(): - print(f"Starting test {module_name}") + print(colored(f" > Starting test {module_name}...", "blue")) tc = test_class(self.args, self.agnostic_path, None, self.finished_tests, queue_lock) tc = threading.Thread(target=tc.run_test, args=()) tc.name = str(module_name) @@ -134,25 +146,35 @@ class TestRunner: """ Kills the tests if the user press enter """ - print("Press enter to stop the tests: ") + print(colored("\n > All test started, press ENTER to abort...\n", "blue")) while True: - if input() == "": - if not self.is_infected: - global POST_RUN_ALLOWED - POST_RUN_ALLOWED = True + #print("Controller still up") + try: + if input() == "": + global POST_RUN_ALLOWED, RUN_OVER + print(colored("\n > Aborting tests...\n", "red")) + if not self.is_infected: + POST_RUN_ALLOWED = True + RUN_OVER = True + return + except KeyboardInterrupt: return + except: + sys.exit() def post_test_runner(self): """ Runs the post test runner if all tests are finished """ - global POST_RUN_ALLOWED + global POST_RUN_ALLOWED, RUN_OVER if self.args.launch: while True: - if POST_RUN_ALLOWED: - print("Running post test runner...") - return 0 - time.sleep(0.5) + if RUN_OVER: + if POST_RUN_ALLOWED and self.is_infected == 0: # Second part is redundant + print(colored("\n > Running post test runner...", "green")) + return 0 + return 1 + time.sleep(0.1) return 0 def test_waiter(self): @@ -162,9 +184,10 @@ class TestRunner: """ for t in self.list_of_tests: # Can only proceed if all tests are finished t.join() - + self.get_status() + # time.sleep(0.5) # When all tests are finished or the user stopped the tests, we can proceed - if not self.is_infected: + if self.is_infected == 0: global POST_RUN_ALLOWED POST_RUN_ALLOWED = True @@ -174,43 +197,57 @@ class TestRunner: :return: The exit code :rtype: int """ - global POST_RUN_ALLOWED - if POST_RUN_ALLOWED: - for t in self.list_of_tests: - if t.is_alive(): - return 2 # 2 means that the user stopped the tests before the end - return self.is_infected # The user didn't stop the tests - - return -1 # The program is not finished yet + exit_code = -1 + status = self.get_status() + if status.tests_finished == status.tests_total: + if status.tests_failed != 0: + exit_code = 1 + elif status.tests_success == status.tests_total: + exit_code = 0 + else: + exit_code = -1 + else: + exit_code = 2 + return exit_code + # global POST_RUN_ALLOWED + # if POST_RUN_ALLOWED: + # for t in self.list_of_tests: + # if t.is_alive(): + # return 2 # 2 means that the user stopped the tests before the end + # return self.is_infected # The user didn't stop the tests + # + # return -1 # The program is not finished yet def get_status(self): """ Gets the status of the tests :return: The status - :rtype: str + :rtype: internal_io.global_status """ - queue_lock.acquire() + queue_lock.acquire(timeout=0.5) nb_tests = len(self.list_of_tests) nb_tests_success = 0 nb_tests_failure = 0 nb_tests_skipped = 0 + progress = 0 for test in self.finished_tests: - print(f"Test {test.name} finished with status {test.status}") if test.status == "success": nb_tests_success += 1 elif test.status == "failure": nb_tests_failure += 1 + self.is_infected += 1 elif test.status == "skipped": nb_tests_skipped += 1 elif test.status == "problem": nb_tests_failure += 1 + progress += test.progress queue_lock.release() nb_tests_ran = nb_tests_success + nb_tests_failure + nb_tests_skipped nb_test_running = nb_tests - nb_tests_ran return global_status( tests_total=nb_tests, tests_finished=nb_tests_ran, - test_success=nb_tests_success, + tests_success=nb_tests_success, tests_failed=nb_tests_failure, tests_running=nb_test_running, tests_skipped=nb_tests_skipped, @@ -257,6 +294,30 @@ def export_data(test_runner, data): return main_data +def print_status(status): + """ + Prints the status + :param status: The status + :type status: internal_io.global_status + """ + if status.tests_failed != 0: + color = "red" + else: + color = "green" + + print(colored("\n > Status:", color)) + if status.tests_total == 0: + print(colored(" > No test found", "red")) + return + + print(colored( + f" > Test finished {status.tests_finished}/{status.tests_total}" + f": {status.tests_success} success, " + f"{status.tests_failed} failed, " + f"{status.tests_error} problem", color + )) + + def run_check(args, agnpath): """ Runs all operations selected in the config @@ -264,37 +325,46 @@ def run_check(args, agnpath): :param agnpath: Annostic path to the discord folder :return: None """ - tr = TestRunner(args, agnpath) # All operation are executed in parallel and the user can stop them - - print("Waiting for the end of the tests") + print(LOGO) + start = time.time() + tr = TestRunner(args, agnpath, start_time=start) # All operation are executed in parallel and the user can stop them + # print("Waiting for the end of the tests") while tr.get_exit_code() == -1: - print(tr.get_status()) # TODO : Print status in a more readable way + # print("Waiting for the end of the tests") + print_status(tr.get_status()) # TODO : Print status in a more readable way time.sleep(0.5) - print("The test sequence is now finished") + time.sleep(0.5) # TODO : Remove this line + global RUN_OVER + RUN_OVER = True status = tr.get_status() - print(status) # TODO: Print the final status, test still running are actually skipped if status.tests_failed > 0: print(INFECTED_CODE) - tr.is_infected = True + # tr.is_infected += 1 + color = "red" else: print(CLEAR_CODE) - tr.is_infected = False + color = "green" + # tr.is_infected = False + + print(colored(f"\nThe test sequence is now finished, the program ran for {round(time.time() - start,2)} seconds", color)) + print_status(status) # TODO: Print the final status, test still running are actually skipped if args.gen_data: - print("Generating data...") + print(colored(" > Generating data...", "blue")) data = tr.get_test_data() file_path = os.path.join(os.path.join("databases", args.gen_data[0])) folder = os.path.dirname(file_path) if not os.path.exists(folder): - print("Making folder...") - os.makedirs(args.gen_data) - print("Exporting data...") # TODO : Advertize where the data is exported + print(colored(" > Making folder...", "blue")) + os.makedirs(folder) + print(colored(f" > Exporting the test data to {file_path}", "blue")) # TODO : Advertize where the data is exported main_data = export_data(tr, data) # print(main_data) with open(file_path, "w") as f: json.dump(main_data, f, indent=4) - print(f"Exiting in {args.timeout} seconds...") + msg_error = "sucessfully" if status.tests_failed == 0 else f"with {status.tests_error} errors" + print(colored(f"The program executed {msg_error}, exiting in {args.timeout} seconds...", color)) time.sleep(args.timeout) sys.exit(tr.get_exit_code()) diff --git a/modules/spidey_test.py b/modules/spidey_test.py index 74e56b5..b37c77c 100644 --- a/modules/spidey_test.py +++ b/modules/spidey_test.py @@ -35,13 +35,13 @@ class SpideyTest(test_template.TestTemplate): if lines > 1: self.is_infected = True + # self.is_infected = True if self.is_infected: # TODO: set a status here, explaining and why the test failed, the scary part will be handled by the main program - print("\n!!! WARNING !!!\n" + return self.finish("failure", "\n!!! WARNING !!!\n" "Unless you've installed a plugin you really trust, chances are your discord install " "is corrupted. We suggest uninstalling discord and deleting all its files before reinstalling.\n" "If you've recently downloaded a .exe directly sent from someone, " "do also consider a clean windows reinstall.") - print("Spidey test finished") # TODO : set a status here, explaining and why the test finished return self.finish("success") diff --git a/modules/test_template.py b/modules/test_template.py index fdf2a84..d3db84f 100644 --- a/modules/test_template.py +++ b/modules/test_template.py @@ -41,6 +41,7 @@ class TestTemplate: self.queue_lock = queue_lock self.failure_dict = {} self.new_data = {} + self.progress = 0 def run_test(self): """ @@ -69,7 +70,14 @@ class TestTemplate: :return: Status at the time of call. :rtype: internal_io.test_status """ - return internal_io.test_status(self.name(), self.status_code, self.status, self.failure_dict, self.new_data) + return internal_io.test_status( + self.name(), + self.status_code, + self.status, + self.failure_dict, + self.new_data, + self.progress + ) @staticmethod def get_status_from_code(code): @@ -107,6 +115,7 @@ class TestTemplate: self.status_code = statuscode self.queue_lock.acquire() + # self.progress = 1 self.queue.append(self.get_status()) self.queue_lock.release() return self.get_status_code() diff --git a/ressources/DiscordHelper.ico b/ressources/DiscordHelper.ico new file mode 100644 index 0000000..9285a80 Binary files /dev/null and b/ressources/DiscordHelper.ico differ diff --git a/ressources/DiscordHelper.png b/ressources/DiscordHelper.png new file mode 100644 index 0000000..229bd66 Binary files /dev/null and b/ressources/DiscordHelper.png differ diff --git a/winspec.spec b/winspec.spec index 7deedea..bace872 100644 --- a/winspec.spec +++ b/winspec.spec @@ -41,4 +41,5 @@ exe = EXE( target_arch=None, codesign_identity=None, entitlements_file=None, + icon='ressources/DiscordHelper.ico', )