sp-hydra-veil-core/core/models/system/SystemState.py

61 lines
1.7 KiB
Python

from core.Constants import Constants
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from json import JSONDecodeError
from pathlib import Path
from typing import Self
import json
import os
import pathlib
@dataclass_json
@dataclass
class SystemState:
profile_id: int
def save(self: Self):
system_state_file_contents = f'{self.to_json(indent=4)}\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)
system_state_file.close()
@staticmethod
def get():
try:
system_state_file_contents = open(f'{SystemState.__get_state_path()}/system.json', 'r').read()
except FileNotFoundError:
return None
try:
system_state = json.loads(system_state_file_contents)
except JSONDecodeError:
return None
# noinspection PyUnresolvedReferences
return SystemState.from_dict(system_state)
@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