Tweaks for Edit profile functionality as well as shifting to using protocol enums over connection.code

This commit is contained in:
SimplifiedPrivacy 2026-11-07 20:25:34 -05:00
parent 87cc90ffb1
commit a01bd42122
10 changed files with 77 additions and 94 deletions

View file

@ -105,49 +105,22 @@ class ProfileController:
given_profile = all_data[profile_id] given_profile = all_data[profile_id]
return given_profile.type 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 if isinstance(profile, SessionProfile):
# def attach_subscription(profile: Union[SessionProfile, SystemProfile], subscription: Subscription): 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 @staticmethod
def attach_proxy_configuration(profile: Union[SessionProfile, SystemProfile]): def attach_proxy_configuration(profile: Union[SessionProfile, SystemProfile]):
@ -178,21 +151,3 @@ class ProfileController:
@staticmethod @staticmethod
def has_wireguard_configuration(profile: Union[SessionProfile, SystemProfile]): def has_wireguard_configuration(profile: Union[SessionProfile, SystemProfile]):
return profile.has_wireguard_configuration() 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

View file

@ -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.observers.Notifications import Notifications, EventType
from core.services.sync import legacy_insert from core.services.sync import legacy_insert
from core.models.manage.session_management import init_session, close_session 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') client_observer.notify('synchronized')
notification = "Sync Complete. (already up to date)" notification = "Sync Complete. (already up to date)"
Notifications.emit(EventType.STATUS_UPDATE, notification) Notifications.emit(EventType.STATUS_UPDATE, notification)
Notifications.emit(EventType.SYNC_COMPLETE, notification)
global_state_marks_sync_completed()
return Result(valid=True) return Result(valid=True)
# We only make it past this point if there's New Data # 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: if save_successful:
notification = "Finshed sync." notification = "Finshed sync."
Notifications.emit(EventType.STATUS_UPDATE, notification) 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) return Result(valid=True, message=notification)
else: else:
error_msg = "Finshed sync, but had issues with the saving of metadata for next time." error_msg = "Finshed sync, but had issues with the saving of metadata for next time."
logger.error(error_msg) logger.error(error_msg)
global_state_marks_sync_completed()
return Result(valid=True, message=error_msg) return Result(valid=True, message=error_msg)
elif total_skipped < quantity_of_entries: elif total_skipped < quantity_of_entries:
error_msg = f"Partial Success. {total_skipped} skipped." error_msg = f"Partial Success. {total_skipped} skipped."
# client_observer.notify('synchronized', error_msg)
Notifications.emit(EventType.STATUS_UPDATE, error_msg) Notifications.emit(EventType.STATUS_UPDATE, error_msg)
global_state_marks_sync_completed()
return Result(valid=True, data=skipped, message=error_msg) return Result(valid=True, data=skipped, message=error_msg)
else: else:

View file

@ -20,6 +20,8 @@ LIST_OF_PROCESSES = [ProcessType.APP, ProcessType.DISPLAY, ProcessType.NETWORK]
@dataclass @dataclass
class GlobalState: class GlobalState:
synced: bool = False
# systemwide: # systemwide:
systemwide_active: bool = False systemwide_active: bool = False
protocol: ProtocolChoice = None protocol: ProtocolChoice = None
@ -55,6 +57,11 @@ class ProfileStateRepository:
# Load existing session IDs from disk into the list # Load existing session IDs from disk into the list
self.global_state.session_profile_ids = [s.id for s in SessionState.all()] 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 @property
def current_session_ids(self) -> list[int]: def current_session_ids(self) -> list[int]:
"""Returns current session profile ids.""" """Returns current session profile ids."""

View file

@ -57,3 +57,11 @@ def is_connected(profile_id: int) -> bool:
is_session_connected = state_repo.is_profile_active(profile_id) is_session_connected = state_repo.is_profile_active(profile_id)
print(f"Is this session profile connected? {profile_id}") print(f"Is this session profile connected? {profile_id}")
return is_session_connected 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()

View file

@ -50,6 +50,7 @@ class BaseProfile(ABC):
name: str name: str
subscription: Optional[Subscription] subscription: Optional[Subscription]
type: ProfileType type: ProfileType
# location: Optional[Location] = field(encoder=lambda u: u.id)
location: Optional[Location] = field(metadata=config(exclude=Exclude.ALWAYS)) # SQLAlchemy object location: Optional[Location] = field(metadata=config(exclude=Exclude.ALWAYS)) # SQLAlchemy object
protocol: ProtocolChoice protocol: ProtocolChoice

View file

@ -58,8 +58,6 @@ class Location(BaseModel):
def supports_protocol(self, enum_value: ProtocolChoice|str) -> bool: def supports_protocol(self, enum_value: ProtocolChoice|str) -> bool:
"""Check if a given location supports a given protocol""" """Check if a given location supports a given protocol"""
print(f"enum_value is {enum_value}")
if enum_value is None: if enum_value is None:
return False return False

View file

@ -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)

View file

@ -17,7 +17,7 @@ from typing import Optional
def create_app_object_by_id(potential_data: dict) -> Result: def create_app_object_by_id(potential_data: dict) -> Result:
"""With a given app id, get an ApplicationVersion object""" """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: if not app_id:
error_msg = "Missing the app by id" error_msg = "Missing the app by id"
@ -47,7 +47,7 @@ def create_session_object(
"""Return a SessionProfile object""" """Return a SessionProfile object"""
# SESSION ONLY PRE-REQS # SESSION ONLY PRE-REQS
resolution = potential_data.get('Resolution', None) resolution = potential_data.get('resolution', None)
if not resolution: if not resolution:
resolution = potential_data.get('resolution', None) resolution = potential_data.get('resolution', None)
@ -103,11 +103,11 @@ def create_new_profile_object(profile_id: int, potential_data: dict) -> Result:
#--------------------------- #---------------------------
# EXTRACT DATA # EXTRACT DATA
#--------------------------- #---------------------------
profile_type = potential_data.get('Type', None) profile_type = potential_data.get('type', None)
protocol = potential_data.get('Protocol', None) protocol = potential_data.get('protocol', None)
location_id = potential_data.get('Location', None) location_id = potential_data.get('location', None)
location = get_profile_location_data_by_id(location_id) 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): 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") 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")

View file

@ -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.session.SessionProfile import SessionProfile
from core.models.orm_calls.location_calls import LocationCache from core.models.orm_calls.location_calls import LocationCache
from core.models.BaseProfile import BaseProfile as Profile 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.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.utils.basic_operations.write_or_read_from_json import read_entire_json
from core.models.orm_calls.application_version_calls import get_application_version from core.models.orm_calls.application_version_calls import get_application_version
@ -19,7 +19,6 @@ import json
import os import os
import re import re
import shutil import shutil
from pathlib import Path
def get_config_path(id: int): def get_config_path(id: int):
return f'{Constants.HV_PROFILE_CONFIG_HOME}/{str(id)}' 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) shutil.rmtree(get_data_path(profile.id), ignore_errors=True)
return Result(valid=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)

View file

@ -1,9 +1,8 @@
# utils
from core.errors.logger import logger from core.errors.logger import logger
from core.models.Result import Result, ResultError from core.models.Result import Result, ResultError
from core.services.config_tools.manage_sudo_configs import remove_sudo_config from core.services.config_tools.manage_sudo_configs import remove_sudo_config
from core.models.enum_models import ProtocolChoice, is_valid_protocol 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.controllers.ProfileController import ProfileController
from core.models.BaseProfile import BaseProfile as Profile from core.models.BaseProfile import BaseProfile as Profile