From b11625f1e88ab3b22f3c71b201c6bd0fded14d9a Mon Sep 17 00:00:00 2001 From: SimplifiedPrivacy Date: Sun, 8 Nov 2026 13:46:04 -0500 Subject: [PATCH] Improved profile edit flow, with location and protocols checks. State mangement and config checks --- core/services/profiles/model_manipulator.py | 64 +++++++++++++++++++-- core/services/profiles/update_profile.py | 51 +++++++++++----- core/utils/dict_tools.py | 7 +++ 3 files changed, 104 insertions(+), 18 deletions(-) create mode 100644 core/utils/dict_tools.py diff --git a/core/services/profiles/model_manipulator.py b/core/services/profiles/model_manipulator.py index af7ddd8..78b1d91 100644 --- a/core/services/profiles/model_manipulator.py +++ b/core/services/profiles/model_manipulator.py @@ -17,6 +17,7 @@ from core.Helpers import write_atomically from datetime import datetime from dataclasses import asdict +from dataclasses import is_dataclass import json import os import re @@ -241,20 +242,70 @@ def get_all_profiles() -> dict: return full_final_dict +def is_actually_different(val1, val2): + """Evaluate if two values are different, with a variety of data formats.""" + + # If both are None, they aren't different + if val1 is None and val2 is None: + return False + + # If one is None and the other isn't, they are different + if val1 is None or val2 is None: + return True + + # Handle SQLAlchemy objects or objects with an 'id' attribute + # We compare the ID instead of the object instance to avoid identity bugs + if hasattr(val1, 'id') and hasattr(val2, 'id'): + return val1.id != val2.id + + # Handle nested dataclasses (they have built-in equality based on values) + if is_dataclass(val1) and is_dataclass(val2): + return val1 != val2 + + # Fallback for strings, ints, bools, etc. + return val1 != val2 + def get_dirty_keys(profile: Profile) -> list: + """What attributes are different between the object in memory, and the saved file currently on disk.""" reference = create_profile(profile.id) if type(reference) != type(profile): return list(profile.__dataclass_fields__.keys()) - return list([key for key, value in asdict(profile).items() if value != asdict(reference).get(key)]) + dirty_keys = [] + for key in profile.__dataclass_fields__.keys(): + val_mem = getattr(profile, key) + val_ref = getattr(reference, key) + + if is_actually_different(val_mem, val_ref): + dirty_keys.append(key) + + logger.info(f"dirty_keys are {dirty_keys}") + return dirty_keys -def handle_outdated_session_data(dirty_keys: dict, profile: SessionProfile): +def remove_app_data(profile_id): + """ + Purpose: + Remove the persistent data related to the app (ie browser) + + Called by: + update_profile's _mutate_one_profile_choice + internally this module: handle_outdated_session_data + """ + persistent_state_path = f'{get_data_path(profile_id)}/persistent-state' + if os.path.isdir(persistent_state_path): + shutil.rmtree(persistent_state_path, ignore_errors=True) + + +def handle_outdated_session_data(profile: SessionProfile, dirty_keys: dict = None): + """Evaluate the dirty keys of a Session profile.""" + + if not dirty_keys: + dirty_keys = get_dirty_keys(profile) + if 'application_version' in dirty_keys: - persistent_state_path = f'{get_data_path(profile.id)}/persistent-state' - if os.path.isdir(persistent_state_path): - shutil.rmtree(persistent_state_path, ignore_errors=True) + remove_app_data(profile_id=profile.id) if 'location' in dirty_keys: profile.delete_proxy_configuration() @@ -295,8 +346,11 @@ def save_to_disk(profile: Profile) -> Result: profile_data_path = get_data_path(profile_id) config_dict = profile.to_dict() + logger.info(f"Saving profile {profile_id} to disk..") + dirty_keys = get_dirty_keys(profile) if 'location' in dirty_keys: + logger.info("Deleting WG keys because location is marked dirty.") profile.delete_wireguard_configuration() # for all polymorphic types. if profile.type == ProfileType.SESSION: diff --git a/core/services/profiles/update_profile.py b/core/services/profiles/update_profile.py index a5bd2fb..894d4b7 100644 --- a/core/services/profiles/update_profile.py +++ b/core/services/profiles/update_profile.py @@ -3,7 +3,7 @@ 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.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 @@ -13,6 +13,7 @@ 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 +from core.utils.dict_tools import get_sorted_keys def finally_save_it(profile: Profile) -> Result: # ------------------------- @@ -57,7 +58,7 @@ def mutate_profile_object_type(profile: Profile, new_choices: dict) -> Result: 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:") + logger.info("Copying over sub data.") new_profile_object.subscription = original_subscription new_profile_object.ticket = original_ticket @@ -76,7 +77,6 @@ def _mutate_one_profile_choice( ) -> Result: """Mutates the profile object fo a single value, but doesn't save it. Returns it.""" - # final_data = None logger.info(f"Recieved profile_id {profile.id}, key {key}, and new_value {new_value}.") if not key: @@ -111,6 +111,10 @@ def _mutate_one_profile_choice( # ============= BROWSER ============= elif key == 'browser': + # remove stale data: + model_manipulator.remove_app_data(profile) + + # set the new app: profile.application_version = get_application_by_id(new_value) # ============= PROTOCOL TYPE ============= @@ -124,15 +128,10 @@ def _mutate_one_profile_choice( # ============= LOCATION ============= elif key == "location": - 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 - else: - return Result(valid=False, message=f"The {new_location.name} location doesn't currently support the {str(pre_existing_protocol)} protocol", error_type=ResultError.WRONG_LOCATION) - - # Subscription gets wiped on a location change, and is outside ORM - profile.subscription = None + changed_location = change_location(profile=profile, new_value=new_value) + if not changed_location.valid: + return changed_location.wrap("Couldn't edit the profile due to location change issues.") + profile = changed_location.data else: return Result(valid=False, message="Invalid Value to Edit", error_type=ResultError.INVALID_INPUT) @@ -162,7 +161,11 @@ def update_profile( # ------------------------- # LOOP UPDATE EACH # ------------------------- - for each_category, each_value in new_choices.items(): + # we put protocol before location, to make sure the new location is compatible. (same for type before both) + PRE_DEFINED_ORDER = ["type", "protocol", "location"] + + for each_category in get_sorted_keys(PRE_DEFINED_ORDER, new_choices): + each_value = new_choices[each_category] logger.info(f"Updating {each_category}") each_update = _mutate_one_profile_choice( @@ -228,3 +231,25 @@ def change_protocol(profile: Profile, new_value: str) -> Result: profile.connection.masked = False return Result(valid=True, data=profile) + +def change_location(profile: Profile, new_value: int) -> Result: + """ + Change a profile's location for the in memory object, and return it. + This does NOT save it to disk. + """ + new_location = get_profile_location_data_by_id(new_value) + + pre_existing_protocol = profile.protocol + + if not new_location.supports_protocol(pre_existing_protocol): + return Result(valid=False, message=f"The {new_location.name} location doesn't currently support the {str(pre_existing_protocol)} protocol", error_type=ResultError.WRONG_LOCATION) + + if pre_existing_protocol == ProtocolChoice.WIREGUARD: + profile.delete_wireguard_configuration() # for all polymorphic types. + + profile.location = new_location + + # Subscription gets wiped on a location change, and is outside location ORM + profile.subscription = None + + return Result(valid=True, data=profile) \ No newline at end of file diff --git a/core/utils/dict_tools.py b/core/utils/dict_tools.py new file mode 100644 index 0000000..141ef1b --- /dev/null +++ b/core/utils/dict_tools.py @@ -0,0 +1,7 @@ + +def get_sorted_keys(priority_order: list, data_dict: dict) -> dict: + """Returns keys from data_dict sorted by priority_order, then by remaining keys.""" + ordered_keys = [k for k in priority_order if k in data_dict] + remaining_keys = [k for k in data_dict if k not in priority_order] + return ordered_keys + remaining_keys +