diff --git a/core/controllers/ProfileController.py b/core/controllers/ProfileController.py index 23ee2c9..6e9f5ad 100644 --- a/core/controllers/ProfileController.py +++ b/core/controllers/ProfileController.py @@ -105,49 +105,22 @@ class ProfileController: given_profile = all_data[profile_id] return given_profile.type - # print(f"all_data[{profile_id}] is {all_data[profile_id]}") - + @staticmethod + def get_default_state_dict(profile_id: int) -> dict: + """Get a dict of state for UI callers""" + + profile = ProfileController._repo.get(profile_id) + profile_dict = profile.to_dict() + profile_dict["location"] = profile.location.id - # @staticmethod - # def attach_subscription(profile: Union[SessionProfile, SystemProfile], subscription: Subscription): + if isinstance(profile, SessionProfile): + app_id = profile.application_version.id + profile_dict["browser"] = app_id + + return profile_dict - # profile.subscription = subscription - # profile.save() - - # @staticmethod - # def activate_subscription(profile: Union[SessionProfile, SystemProfile], connection_observer: Optional[ConnectionObserver] = None): - - # from core.controllers.ConnectionController import ConnectionController - - # if profile.has_subscription(): - - # subscription = subscriptions.get_subscription( - # billing_code=profile.subscription.billing_code, - # connection_observer=connection_observer - # ) - - # if subscription is not None: - - # profile.subscription = subscription - # profile.save() - - # else: - # raise () - - # else: - # raise () - - - # @staticmethod - # def get_invoice(profile: Union[SessionProfile, SystemProfile]): - - # if profile.has_subscription(): - # # return subscriptions.get_invoice(billing_code=profile.subscription.billing_code) - # return WebServiceApiService.get_invoice(profile.subscription.billing_code) - # else: - # return None @staticmethod def attach_proxy_configuration(profile: Union[SessionProfile, SystemProfile]): @@ -178,21 +151,3 @@ class ProfileController: @staticmethod def has_wireguard_configuration(profile: Union[SessionProfile, SystemProfile]): return profile.has_wireguard_configuration() - - - -# from core.observers.TicketObserver import TicketObserver -# from core.services.assassin.ticket_respawn import respawn_profile -# from core.services.assassin import assassin_tools -# from core.errors.exceptions import FirewallError -# from core.services.networking.systemwide.systemwide_wireguard import terminate_system_connection -# from core.services.networking.general_connection_tools.testing_evaluating import system_uses_wireguard_interface -# from core.services.networking.general_connection_tools.connection_enable import establish_connection -# from core.services.networking.systemwide.systemwide_utils import get_firewall_setting, get_dns_setting -# from core.services.networking.systemwide.encrypted_proxy.singbox_runner import end_singbox -# from core.services.networking.systemwide import killswitch -#, ConnectionTerminationError, ProfileActivationError, ProfileDeactivationError, MissingLocationError, ConnectionUnprotectedError, EndpointVerificationError, ProfileStateConflictError -# from core.controllers.ApplicationController import ApplicationController -# from core.controllers.ApplicationVersionController import ApplicationVersionController -# from core.controllers.SessionStateController import SessionStateController -# from core.controllers.SystemStateController import SystemStateController diff --git a/core/controllers/SyncController.py b/core/controllers/SyncController.py index b11aaab..f8bfe62 100644 --- a/core/controllers/SyncController.py +++ b/core/controllers/SyncController.py @@ -1,3 +1,4 @@ +from core.infrastructure.state_management.global_state_controller import global_state_marks_sync_completed from core.observers.Notifications import Notifications, EventType from core.services.sync import legacy_insert from core.models.manage.session_management import init_session, close_session @@ -108,6 +109,8 @@ def new_sync(client_observer: ClientObserver, connection_observer: ConnectionObs client_observer.notify('synchronized') notification = "Sync Complete. (already up to date)" Notifications.emit(EventType.STATUS_UPDATE, notification) + Notifications.emit(EventType.SYNC_COMPLETE, notification) + global_state_marks_sync_completed() return Result(valid=True) # We only make it past this point if there's New Data @@ -183,17 +186,19 @@ def new_sync(client_observer: ClientObserver, connection_observer: ConnectionObs if save_successful: notification = "Finshed sync." Notifications.emit(EventType.STATUS_UPDATE, notification) - Notifications.emit(EventType.SYNC_COMPLETE, notification) + Notifications.emit(EventType.SYNC_COMPLETE, notification) + global_state_marks_sync_completed() return Result(valid=True, message=notification) else: error_msg = "Finshed sync, but had issues with the saving of metadata for next time." logger.error(error_msg) + global_state_marks_sync_completed() return Result(valid=True, message=error_msg) elif total_skipped < quantity_of_entries: error_msg = f"Partial Success. {total_skipped} skipped." - # client_observer.notify('synchronized', error_msg) Notifications.emit(EventType.STATUS_UPDATE, error_msg) + global_state_marks_sync_completed() return Result(valid=True, data=skipped, message=error_msg) else: diff --git a/core/infrastructure/global_state.py b/core/infrastructure/global_state.py index 6eeb323..a05ec1c 100644 --- a/core/infrastructure/global_state.py +++ b/core/infrastructure/global_state.py @@ -20,6 +20,8 @@ LIST_OF_PROCESSES = [ProcessType.APP, ProcessType.DISPLAY, ProcessType.NETWORK] @dataclass class GlobalState: + synced: bool = False + # systemwide: systemwide_active: bool = False protocol: ProtocolChoice = None @@ -55,6 +57,11 @@ class ProfileStateRepository: # Load existing session IDs from disk into the list self.global_state.session_profile_ids = [s.id for s in SessionState.all()] + + def sync_done(self): + """Turn Sync on""" + self.global_state.synced = True + @property def current_session_ids(self) -> list[int]: """Returns current session profile ids.""" diff --git a/core/infrastructure/state_management/global_state_controller.py b/core/infrastructure/state_management/global_state_controller.py index 3247422..80c7788 100644 --- a/core/infrastructure/state_management/global_state_controller.py +++ b/core/infrastructure/state_management/global_state_controller.py @@ -57,3 +57,11 @@ def is_connected(profile_id: int) -> bool: is_session_connected = state_repo.is_profile_active(profile_id) print(f"Is this session profile connected? {profile_id}") return is_session_connected + +def is_synced() -> bool: + return ProfileStateRepository().global_state.synced + +def global_state_marks_sync_completed(): + state_repo = ProfileStateRepository() + state_repo.sync_done() + diff --git a/core/models/BaseProfile.py b/core/models/BaseProfile.py index 8951469..c556c81 100644 --- a/core/models/BaseProfile.py +++ b/core/models/BaseProfile.py @@ -50,6 +50,7 @@ class BaseProfile(ABC): name: str subscription: Optional[Subscription] type: ProfileType + # location: Optional[Location] = field(encoder=lambda u: u.id) location: Optional[Location] = field(metadata=config(exclude=Exclude.ALWAYS)) # SQLAlchemy object protocol: ProtocolChoice diff --git a/core/models/orm_models/Location.py b/core/models/orm_models/Location.py index 39d8293..484cdd7 100644 --- a/core/models/orm_models/Location.py +++ b/core/models/orm_models/Location.py @@ -58,8 +58,6 @@ class Location(BaseModel): def supports_protocol(self, enum_value: ProtocolChoice|str) -> bool: """Check if a given location supports a given protocol""" - - print(f"enum_value is {enum_value}") if enum_value is None: return False diff --git a/core/services/config_tools/config_manager.py b/core/services/config_tools/config_manager.py new file mode 100644 index 0000000..b173ec1 --- /dev/null +++ b/core/services/config_tools/config_manager.py @@ -0,0 +1,34 @@ +from core.services.config_tools.manage_sudo_configs import remove_sudo_config +from core.services.profiles.model_manipulator import get_config_path +from core.models.BaseProfile import BaseProfile as Profile +from core.models.BaseProfile import ProfileType, CONFIG_NAME, SYSTEM_WIDE_BACKUP_CONFIG_NAME +from core.models.Result import Result, ResultError +from core.errors.logger import logger + +from pathlib import Path + + +def delete_connection_configs(profile: Profile) -> Result: + """Delete both connection configuration and backup connection config files for a given profile.""" + + logger.info(f"Attempting to delete profile {profile.id}'s network config files") + config_path = get_config_path(profile.id) + + # CONFIG NAME: + if profile.type == ProfileType.SESSION: + config_name = CONFIG_NAME[profile.protocol] + elif profile.type == ProfileType.SYSTEM: + config_name = SYSTEM_WIDE_BACKUP_CONFIG_NAME[profile.protocol] + else: + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Invalid protocol choice") + + Path(config_path, config_name).unlink(missing_ok=True) + + # SYSTEMWIDE: + if profile.type == ProfileType.SYSTEM: + removed = remove_sudo_config(profile) + if not removed.valid: + return removed.wrap("Unable to delete the systemwide configs behind sudo protection.") + + logger.info("Deleted the previous connection configuration") + return Result(valid=True) \ No newline at end of file diff --git a/core/services/profiles/create_objects.py b/core/services/profiles/create_objects.py index a852e3b..09df17c 100644 --- a/core/services/profiles/create_objects.py +++ b/core/services/profiles/create_objects.py @@ -17,7 +17,7 @@ from typing import Optional def create_app_object_by_id(potential_data: dict) -> Result: """With a given app id, get an ApplicationVersion object""" - app_id = potential_data.get('Browser', None) + app_id = potential_data.get('browser', None) if not app_id: error_msg = "Missing the app by id" @@ -47,7 +47,7 @@ def create_session_object( """Return a SessionProfile object""" # SESSION ONLY PRE-REQS - resolution = potential_data.get('Resolution', None) + resolution = potential_data.get('resolution', None) if not resolution: resolution = potential_data.get('resolution', None) @@ -103,11 +103,11 @@ def create_new_profile_object(profile_id: int, potential_data: dict) -> Result: #--------------------------- # EXTRACT DATA #--------------------------- - profile_type = potential_data.get('Type', None) - protocol = potential_data.get('Protocol', None) - location_id = potential_data.get('Location', None) + profile_type = potential_data.get('type', None) + protocol = potential_data.get('protocol', None) + location_id = potential_data.get('location', None) location = get_profile_location_data_by_id(location_id) - name = potential_data.get('Name', None) + name = potential_data.get('name', None) if not profile_type or not isinstance(profile_type, ProfileType): return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="The data to create the profile is not structured properly. It's missing the type") diff --git a/core/services/profiles/model_manipulator.py b/core/services/profiles/model_manipulator.py index afd9e0d..dac491a 100644 --- a/core/services/profiles/model_manipulator.py +++ b/core/services/profiles/model_manipulator.py @@ -2,7 +2,7 @@ from core.services.config_tools.manage_sudo_configs import remove_sudo_config from core.models.session.SessionProfile import SessionProfile from core.models.orm_calls.location_calls import LocationCache from core.models.BaseProfile import BaseProfile as Profile -from core.models.BaseProfile import ProfileType, CONFIG_NAME, SYSTEM_WIDE_BACKUP_CONFIG_NAME +from core.models.BaseProfile import ProfileType from core.services.profiles.create_objects import create_session_object, create_system_object from core.utils.basic_operations.write_or_read_from_json import read_entire_json from core.models.orm_calls.application_version_calls import get_application_version @@ -19,7 +19,6 @@ import json import os import re import shutil -from pathlib import Path def get_config_path(id: int): return f'{Constants.HV_PROFILE_CONFIG_HOME}/{str(id)}' @@ -308,26 +307,3 @@ def delete(profile: Profile) -> Result: shutil.rmtree(get_data_path(profile.id), ignore_errors=True) return Result(valid=True) - -def delete_connection_configs(profile: Profile) -> Result: - """Delete both connection configuration and backup connection config files for a given profile.""" - - config_path = get_config_path(profile.id) - - # CONFIG NAME: - if profile.type == ProfileType.SESSION: - config_name = CONFIG_NAME[profile.protocol] - elif profile.type == ProfileType.SYSTEM: - config_name = SYSTEM_WIDE_BACKUP_CONFIG_NAME[profile.protocol] - else: - return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Invalid protocol choice") - - Path(config_path, config_name).unlink(missing_ok=True) - - # SYSTEMWIDE: - if profile.type == ProfileType.SYSTEM: - removed = remove_sudo_config(profile) - if not removed.valid: - return removed.wrap("Unable to delete the systemwide configs behind sudo protection.") - - return Result(valid=True) \ No newline at end of file diff --git a/core/services/profiles/update_profile.py b/core/services/profiles/update_profile.py index 174f3e7..9e25f80 100644 --- a/core/services/profiles/update_profile.py +++ b/core/services/profiles/update_profile.py @@ -1,9 +1,8 @@ -# utils from core.errors.logger import logger from core.models.Result import Result, ResultError from core.services.config_tools.manage_sudo_configs import remove_sudo_config from core.models.enum_models import ProtocolChoice, is_valid_protocol -from core.services.profiles.model_manipulator import delete_connection_configs +from core.services.config_tools.config_manager import delete_connection_configs from core.controllers.ProfileController import ProfileController from core.models.BaseProfile import BaseProfile as Profile