From ee49e41977bf28e685e314fa8c0e24dcd9ed9fa9 Mon Sep 17 00:00:00 2001 From: SimplifiedPrivacy Date: Sun, 8 Nov 2026 10:22:07 -0500 Subject: [PATCH] Introduced Support for Changing Profile Type --- core/controllers/ProfileController.py | 10 +- core/models/session/SessionConnection.py | 6 +- core/models/system/SystemConnection.py | 6 +- core/services/profiles/create_objects.py | 23 ++- core/services/profiles/model_manipulator.py | 58 ++++++- core/services/profiles/update_profile.py | 166 ++++++++++++++------ 6 files changed, 202 insertions(+), 67 deletions(-) diff --git a/core/controllers/ProfileController.py b/core/controllers/ProfileController.py index 6e9f5ad..ec7b537 100644 --- a/core/controllers/ProfileController.py +++ b/core/controllers/ProfileController.py @@ -41,10 +41,11 @@ class ProfileController: """Internal helper to handle the actual persistence and cache synchronization.""" # 1. Persist to disk - logger.info("Saving to disk.") + logger.info(f"Saving to disk profile {profile.id}.") model_manipulator.save_to_disk(profile) # 2. update cache to prevent drift + logger.info(f"Saved to disk. Now updating cache for profile {profile.id}..") ProfileController._repo.update_cache(profile) # 3. Notify observer @@ -79,13 +80,16 @@ class ProfileController: return Result(valid=True) @staticmethod - def update(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None): + def update(profile: Profile, profile_observer: ProfileObserver = None): # Call the helper with the 'updated' event ProfileController._save_and_sync(profile, 'updated', profile_observer) + # update ui: + Notifications.emit(EventType.PROFILES_CHANGED) + @staticmethod - def delete(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None): + def delete(profile: Profile, profile_observer: ProfileObserver = None): """Remove the profile from both disk and cache""" # 1. Save to temp variable: diff --git a/core/models/session/SessionConnection.py b/core/models/session/SessionConnection.py index 85ead48..923fdf0 100644 --- a/core/models/session/SessionConnection.py +++ b/core/models/session/SessionConnection.py @@ -5,10 +5,10 @@ from dataclasses import dataclass class SessionConnection(BaseConnection): masked: bool = False - def __post_init__(self): + # def __post_init__(self): - if self.code not in ('system', 'tor', 'wireguard'): - raise ValueError('Invalid connection code.') + # if self.code not in ('system', 'tor', 'wireguard'): + # raise ValueError('Invalid connection code.') # Called by: ConnectionController diff --git a/core/models/system/SystemConnection.py b/core/models/system/SystemConnection.py index 7de09f2..80b8d35 100644 --- a/core/models/system/SystemConnection.py +++ b/core/models/system/SystemConnection.py @@ -5,10 +5,10 @@ from dataclasses import dataclass @dataclass class SystemConnection (BaseConnection): - def __post_init__(self): + # def __post_init__(self): - if self.code not in ('vless', 'hysteria2', 'wireguard'): - raise ValueError('Invalid connection code.') + # if self.code not in ('vless', 'hysteria2', 'wireguard'): + # raise ValueError('Invalid connection code.') @staticmethod def needs_proxy_configuration(): diff --git a/core/services/profiles/create_objects.py b/core/services/profiles/create_objects.py index 09df17c..6d35266 100644 --- a/core/services/profiles/create_objects.py +++ b/core/services/profiles/create_objects.py @@ -105,8 +105,27 @@ def create_new_profile_object(profile_id: int, potential_data: dict) -> Result: #--------------------------- 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) + + raw_location = potential_data.get('location', None) + + # already a location id: + if isinstance(raw_location, int): + location = get_profile_location_data_by_id(raw_location) + + # serialized form: + elif isinstance(raw_location, dict): + location_id = raw_location.get('location_id', None) + location = get_profile_location_data_by_id(location_id) + + # already a location: + elif isinstance(raw_location, Location): + location = raw_location + + else: + error_msg = f"invalid location format of type {type(raw_location)} with data: {raw_location}." + logger.error(error_msg) + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + name = potential_data.get('name', None) if not profile_type or not isinstance(profile_type, ProfileType): diff --git a/core/services/profiles/model_manipulator.py b/core/services/profiles/model_manipulator.py index dac491a..af7ddd8 100644 --- a/core/services/profiles/model_manipulator.py +++ b/core/services/profiles/model_manipulator.py @@ -8,6 +8,8 @@ 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.Subscription import Subscription from core.models.enum_models import ProtocolChoice +from core.models.orm_models.Location import Location +from core.models.orm_models.ApplicationVersion import ApplicationVersion from core.models.Result import Result, ResultError from core.errors.logger import logger from core.Constants import Constants @@ -258,7 +260,32 @@ def handle_outdated_session_data(dirty_keys: dict, profile: SessionProfile): profile.delete_proxy_configuration() -def save_to_disk(profile: Profile): +def ensure_dict_format(profile: Profile, string_name: str, potential_sql_type) -> dict|None: + """Make sure the hot profile object coming in, matches the cold data storage format.""" + + potential_data = getattr(profile, string_name) + + # if it's an SQL model, we convert it, + if isinstance(potential_data, potential_sql_type): + return potential_data.convert_to_dict() + + # already is a dict: + elif isinstance(potential_data, dict): + return potential_data + + else: + error_msg = "Invalid format for application version." + logger.error(error_msg) + return None + + +# dict_format = ensure_dict_format(profile=profile, string_name=, potential_sql_type) +# if not dict_format: +# return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + + + +def save_to_disk(profile: Profile) -> Result: """ Persist a Profile model to disk. For SQL based attributes, we manually override the dict prior to serialization. @@ -274,14 +301,30 @@ def save_to_disk(profile: Profile): if profile.type == ProfileType.SESSION: handle_outdated_session_data(dirty_keys=dirty_keys, profile=profile) - # Application is an SQL model, so we override the dict, - app_version_dict = profile.application_version.convert_to_dict() - config_dict["application_version"] = app_version_dict + + # if it's an SQL model, we convert it, + if isinstance(profile.application_version, ApplicationVersion): + app_version_dict = profile.application_version.convert_to_dict() + config_dict["application_version"] = app_version_dict + # already is a dict: + elif isinstance(profile.application_version, dict): + config_dict["application_version"] = profile.application_version + else: + error_msg = "Invalid format for application version." + logger.error(error_msg) + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) # === LOCATION === - # Location is an SQL model, so we override the dict, - location_dict = profile.location.convert_to_dict() # this is from SQLAlchemy, and not JSON-models, that's why it's separate. - config_dict["location"] = location_dict + # if it's an SQL model, we convert it, + if isinstance(profile.location, Location): + location_dict = profile.location.convert_to_dict() + config_dict["location"] = location_dict + elif isinstance(profile.location, dict): + config_dict["location"] = profile.location + else: + error_msg = "Invalid format for location." + logger.error(error_msg) + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) # === FILE I/O === config_file_contents = json.dumps(config_dict, indent=4) + '\n' @@ -291,6 +334,7 @@ def save_to_disk(profile: Profile): config_file_path = f'{profile_config_path}/config.json' write_atomically(config_file_path, config_file_contents) + return Result(valid=True) def delete(profile: Profile) -> Result: diff --git a/core/services/profiles/update_profile.py b/core/services/profiles/update_profile.py index 9e25f80..a5bd2fb 100644 --- a/core/services/profiles/update_profile.py +++ b/core/services/profiles/update_profile.py @@ -3,51 +3,96 @@ 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.config_tools.config_manager import delete_connection_configs - +# from core.services.profiles import model_manipulator from core.controllers.ProfileController import ProfileController from core.models.BaseProfile import BaseProfile as Profile from core.models.BaseProfile import ProfileType, PROTOCOL_CHOICES - -from core.models.orm_calls.location_calls import get_profile_location_data -from core.models.orm_calls.application_version_calls import get_application_version +from core.models.system.SystemProfile import SystemProfile +from core.models.session.SessionProfile import SessionProfile from core.models.orm_models.Location import Location +from core.models.orm_calls.application_version_calls import get_application_by_id +from core.models.orm_calls.location_calls import get_profile_location_data_by_id +from core.services.profiles.create_objects import create_new_profile_object -""" -Steps: -1) Looks up the profile by id number -2) Filters what values to save, using the ORM for some such as location -3) Saves it with the abstract class' json serialization methods, which use the ORM methods +def finally_save_it(profile: Profile) -> Result: + # ------------------------- + # SAVE ENTIRE THING + # ------------------------- + logger.info(f"We in the final stage with the mutated profile {profile}") + try: + ProfileController.update(profile) + logger.info("Save worked, passing to the GUI the Result..") + return Result(valid=True) + except Exception as e: + error_msg = f"Profile save failed because {str(e)}" + return Result(valid=False, message=error_msg, error_type=ResultError.UNKNOWN) -Returns: - Result Object -Called by: - GUI's editor_page +def mutate_profile_object_type(profile: Profile, new_choices: dict) -> Result: + """Mutate a profile object from one type to another.""" -Raises Errors: - False -""" + new_type = new_choices["type"] + profile_id = profile.id + original_subscription = profile.subscription + original_ticket = profile.ticket -def update_profile( - profile_id: int, + original_choices = profile.to_dict() + + if "location" not in new_choices: + # re-use existing location object: + new_choices["location"] = profile.location + + for each_category, each_value in original_choices.items(): + if each_category not in new_choices: + logger.info(f"Copying over category {each_category} from the original.") + new_choices[each_category] = original_choices[each_category] + + creation_result = create_new_profile_object(profile_id=profile_id, potential_data=new_choices) + + if not creation_result.valid: + return creation_result.wrap("Unable to switch profile type due to creation of new object.") + + new_profile_object = creation_result.data + + if not new_profile_object: + return Result(valid=False, data=creation_result, error_type=ResultError.INVALID_INPUT, message="Dev error, this was marked true but its missing the data") + + logger.info("Copying over sub data:") + new_profile_object.subscription = original_subscription + new_profile_object.ticket = original_ticket + + # Delete the old one: + logger.info("Deleting the previous profile in that slot.") + ProfileController.delete(profile) + + # save the new: + return finally_save_it(new_profile_object) + + +def _mutate_one_profile_choice( + profile: Profile, key: str, new_value: str ) -> Result: + """Mutates the profile object fo a single value, but doesn't save it. Returns it.""" # final_data = None - logger.info(f"[UPDATE PROFILE] Recieved profile_id {profile_id}, key {key}, and new_value {new_value}.") + logger.info(f"Recieved profile_id {profile.id}, key {key}, and new_value {new_value}.") - if not key or not new_value: - return Result(valid=False, data=f"Invalid Inputs of {key} and {new_value}", error_type=ResultError.INVALID_INPUT) + if not key: + return Result(valid=False, data=f"Invalid Input of {key}", error_type=ResultError.INVALID_INPUT) - profile = ProfileController.get(profile_id) - if not profile: - error_msg = f"Invalid profile id of {profile_id}" - return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) - - if key == 'dimentions': + # ============= RESOLUTION ============= + if key == 'resolution': profile.resolution = new_value + # # ============= TYPE ============= + elif key == 'type': + error_msg = "This is a developer bug. The type should have triggered an object conversion prior to this function." + logger.error(error_msg) + return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) + + # ============= NAME ============= elif key == 'name': profile.name = new_value @@ -66,15 +111,9 @@ def update_profile( # ============= BROWSER ============= elif key == 'browser': - browser_type, browser_version = new_value.split(':', 1) - - application_version = get_application_version( # SQLAlchemy - application_code=browser_type, - version_number=browser_version - ) - # SQLAlchemy foreign key assignment — fills in id, timezone, operator, etc. - profile.application_version = application_version + profile.application_version = get_application_by_id(new_value) + # ============= PROTOCOL TYPE ============= elif key == 'protocol': logger.info("Changing the protocol..") changed_result = change_protocol(profile, new_value) @@ -85,11 +124,7 @@ def update_profile( # ============= LOCATION ============= elif key == "location": - country_code, city_code = new_value.split("_") - new_location = get_profile_location_data( # SQLAlchemy - country_code=country_code, - city_code=city_code - ) + new_location = get_profile_location_data_by_id(new_value) pre_existing_protocol = profile.protocol if new_location.supports_protocol(pre_existing_protocol): profile.location = new_location @@ -101,14 +136,47 @@ def update_profile( else: return Result(valid=False, message="Invalid Value to Edit", error_type=ResultError.INVALID_INPUT) - logger.info("[UPDATE PROFILE] Passing to Profile model to save..") - try: - ProfileController.update(profile) - logger.info("[UPDATE PROFILE] Save worked, passing to the GUI the Result..") - return Result(valid=True) - except Exception as e: - error_msg = f"Profile save failed because {str(e)}" - return Result(valid=False, message=error_msg, error_type=ResultError.UNKNOWN) + logger.info("Passing back the mutated profile object..") + + return Result(valid=True, data=profile) + +def update_profile( + profile_id: int, + new_choices: dict +) -> Result: + + # ------------------------- + # GET PROFILE + # ------------------------- + profile = ProfileController.get(profile_id) + if not profile: + error_msg = f"Invalid profile id of {profile_id}" + return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) + + # ------------------------- + # TYPE CHANGE (requires object swap) + # ------------------------- + if "type" in new_choices: + return mutate_profile_object_type(profile=profile, new_choices=new_choices) + + # ------------------------- + # LOOP UPDATE EACH + # ------------------------- + for each_category, each_value in new_choices.items(): + logger.info(f"Updating {each_category}") + + each_update = _mutate_one_profile_choice( + profile=profile, + key=each_category, + new_value=each_value + ) + if not each_update.valid: + return each_update.wrap(f"Category {each_category} choice failed to update.") + + # mutated profile object continues loop, + profile = each_update.data + + return finally_save_it(profile) def change_protocol(profile: Profile, new_value: str) -> Result: @@ -130,8 +198,8 @@ def change_protocol(profile: Profile, new_value: str) -> Result: return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) # ============= LOCATION SUPPORTS PROTOCOL ============= - logger.info("checking protocol support for this location..") pre_existing_location = profile.location + logger.info(f"checking protocol support for location {pre_existing_location.country_name} with {protocol_choice}..") if not pre_existing_location.supports_protocol(new_value): logger.error(f"User is trying to update the protocol to {new_value}, but selected an invalid location to do so.")