from core.models.enum_models import ProtocolChoice from core.Constants import Constants from core.utils.basic_operations.enum_tools import serialize_enums # generic from dataclasses import dataclass from dataclasses_json import dataclass_json from pathlib import Path from typing import Self import json import os import pathlib from typing import Optional @dataclass_json @dataclass class SystemState: profile_id: int firewalled: bool dns_set: bool protocol: ProtocolChoice process_id: Optional[int] = None def save(self: Self): data_as_dict = self.to_json(indent=4) print(f"data_as_dict is {data_as_dict}") data_without_enums = serialize_enums(data_as_dict) print(f"data_without_enums is {data_without_enums}") system_state_file_contents = f'{data_without_enums}\n' os.makedirs(SystemState.__get_state_path(), exist_ok=True, mode=0o700) system_state_file_path = f'{SystemState.__get_state_path()}/system.json' Path(system_state_file_path).touch(exist_ok=True, mode=0o600) with open(system_state_file_path, 'w') as system_state_file: system_state_file.write(system_state_file_contents) print("saved system state") @staticmethod def get(): try: system_state_file_contents = open(f'{SystemState.__get_state_path()}/system.json', 'r').read() system_state_dict = json.loads(system_state_file_contents) # noinspection PyUnresolvedReferences return SystemState.from_dict(system_state_dict) except (FileNotFoundError, ValueError, KeyError): return None @staticmethod def exists(): return os.path.isfile(f'{SystemState.__get_state_path()}/system.json') @staticmethod def dissolve(): system_state = SystemState.get() if system_state is not None: system_state_path = f'{SystemState.__get_state_path()}/system.json' pathlib.Path.unlink(Path(system_state_path), missing_ok=True) @staticmethod def __get_state_path(): return Constants.HV_STATE_HOME