from core.observers.Notifications import Notifications, EventType from core.models.system.SystemState import SystemState from core.models.session.SessionState import SessionState from core.models.enum_models import ProtocolChoice from dataclasses import dataclass, field from typing import Optional, Dict import subprocess from enum import Enum class ProcessType(Enum): NETWORK = "network" APP = "app" DISPLAY = "display" ACTIVE = "active" LIST_OF_PROCESSES = [ProcessType.APP, ProcessType.DISPLAY, ProcessType.NETWORK] @dataclass class GlobalState: # systemwide: systemwide_active: bool = False protocol: ProtocolChoice = None firewalled: bool = False dns_set: bool = False systemwide_profile_id: Optional[int] = None verified_working: bool = False changed_port: bool = False # session: # session_profile_ids: list[int] = field(default_factory=list) session_profiles: Dict[str, Dict[ProcessType, subprocess.Popen]] = field(default_factory=dict) class ProfileStateRepository: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(ProfileStateRepository, cls).__new__(cls) cls._instance._initialize() return cls._instance def _initialize(self): self.global_state = GlobalState() # Initial load: Sync memory with whatever is currently on disk sys = SystemState.get() if sys: self.global_state.systemwide_profile_id = sys.profile_id self.global_state.firewalled = sys.firewalled self.global_state.dns_set = sys.dns_set # Load existing session IDs from disk into the list self.global_state.session_profile_ids = [s.id for s in SessionState.all()] @property def current_session_ids(self) -> list[int]: """Returns current session profile ids.""" return list(self.global_state.session_profiles.keys()) @property def active_session_ids(self) -> list[int]: """Returns active session profile ids.""" current_list = self.current_session_ids active_list = [] for each_profile_id in current_list: try: if self.global_state.session_profiles[each_profile_id][ProcessType.ACTIVE] is True: active_list.append(each_profile_id) except KeyError: print(f"active doesn't exist yet for profile id {each_profile_id}") continue return active_list def turn_off_system_connection(self): """Clear the system-wide memory cache.""" self.global_state.systemwide_profile_id = None self.global_state.protocol = None self.global_state.firewalled = False self.global_state.dns_set = False self.global_state.systemwide_active = False self.global_state.verified_working = False def sync_system_state(self, state: SystemState): """Called by SystemStateController to update memory cache.""" self.global_state.systemwide_profile_id = state.profile_id self.global_state.protocol = state.protocol self.global_state.firewalled = state.firewalled self.global_state.dns_set = state.dns_set if state.profile_id: self.global_state.systemwide_active = True def verify_its_up(self, profile_id: int) -> bool: """Flips on Verification for Systemwide, if the rest of the state matches""" if not self.global_state.systemwide_active: return False if self.global_state.systemwide_profile_id != profile_id: return False self.global_state.verified_working = True notification = "Connected." Notifications.emit(EventType.STATUS_UPDATE, notification) Notifications.emit(EventType.SYSTEM_ENABLE, profile_id) return True def is_profile_active(self, profile_id: int) -> bool: # Check system profile if self.global_state.systemwide_active and self.global_state.systemwide_profile_id == profile_id: return True # Check session profiles return profile_id in self.active_session_ids def setup_session_profile(self, profile_id: int) -> None: """Ensures a session profile exists in the registry without overwriting existing processes.""" self.global_state.session_profiles.setdefault(profile_id, {}) def add_session_process(self, profile_id: int, process_type: ProcessType, process: subprocess.Popen|bool) -> None: """Adds a live process to a specific profile id group.""" self.setup_session_profile(profile_id) self.global_state.session_profiles[profile_id][process_type] = process def get_entire_session_process_group(self, profile_id: int) -> Optional[Dict[ProcessType, subprocess.Popen]]: """Returns the entire dictionary of processes for a group, or None if not found.""" return self.global_state.session_profiles.get(profile_id) def flip_session_profile_on(self, profile_id: int) -> bool: """If it has all the pre-reqs, then it sets the status to on.""" for each_type in LIST_OF_PROCESSES: if self.global_state.session_profiles[profile_id][each_type] is None: print(f"Process is none for {each_type}") return False print("Global state is setting the session profile to activated") self.global_state.session_profiles[profile_id][ProcessType.ACTIVE] = True return True def get_session_process(self, profile_id: int, process_type: ProcessType) -> Optional[subprocess.Popen]: """Gets a single process from the session profile's group.""" # 1. Leverage the group getter group = self.get_entire_session_process_group(profile_id) # 2. If the group exists, try to get the specific process if group: return group.get(process_type) return None def remove_session_profile(self, profile_id: int) -> None: """ Completely remove a profile, and it's group of processes from the registry""" if profile_id in self.global_state.session_profiles: del self.global_state.session_profiles[profile_id] Notifications.emit(EventType.SESSION_PROFILE_DISABLE, profile_id) # def sync_session_added(self, profile_id: int): # """Called by SessionStateController to update memory cache.""" # if profile_id not in self.global_state.session_profile_ids: # self.global_state.session_profile_ids.append(profile_id) # def sync_session_removed(self, profile_id: int): # """Called by SessionStateController to update memory cache.""" # if profile_id in self.global_state.session_profile_ids: # self.global_state.session_profile_ids.remove(profile_id)