Improved profile edit flow, with location and protocols checks. State mangement and config checks
This commit is contained in:
parent
ee49e41977
commit
b11625f1e8
3 changed files with 104 additions and 18 deletions
|
|
@ -17,6 +17,7 @@ from core.Helpers import write_atomically
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from dataclasses import asdict
|
from dataclasses import asdict
|
||||||
|
from dataclasses import is_dataclass
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
|
@ -241,21 +242,71 @@ def get_all_profiles() -> dict:
|
||||||
return full_final_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:
|
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)
|
reference = create_profile(profile.id)
|
||||||
|
|
||||||
if type(reference) != type(profile):
|
if type(reference) != type(profile):
|
||||||
return list(profile.__dataclass_fields__.keys())
|
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):
|
||||||
if 'application_version' in dirty_keys:
|
"""
|
||||||
persistent_state_path = f'{get_data_path(profile.id)}/persistent-state'
|
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):
|
if os.path.isdir(persistent_state_path):
|
||||||
shutil.rmtree(persistent_state_path, ignore_errors=True)
|
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:
|
||||||
|
remove_app_data(profile_id=profile.id)
|
||||||
|
|
||||||
if 'location' in dirty_keys:
|
if 'location' in dirty_keys:
|
||||||
profile.delete_proxy_configuration()
|
profile.delete_proxy_configuration()
|
||||||
|
|
||||||
|
|
@ -295,8 +346,11 @@ def save_to_disk(profile: Profile) -> Result:
|
||||||
profile_data_path = get_data_path(profile_id)
|
profile_data_path = get_data_path(profile_id)
|
||||||
config_dict = profile.to_dict()
|
config_dict = profile.to_dict()
|
||||||
|
|
||||||
|
logger.info(f"Saving profile {profile_id} to disk..")
|
||||||
|
|
||||||
dirty_keys = get_dirty_keys(profile)
|
dirty_keys = get_dirty_keys(profile)
|
||||||
if 'location' in dirty_keys:
|
if 'location' in dirty_keys:
|
||||||
|
logger.info("Deleting WG keys because location is marked dirty.")
|
||||||
profile.delete_wireguard_configuration() # for all polymorphic types.
|
profile.delete_wireguard_configuration() # for all polymorphic types.
|
||||||
|
|
||||||
if profile.type == ProfileType.SESSION:
|
if profile.type == ProfileType.SESSION:
|
||||||
|
|
|
||||||
|
|
@ -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.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.config_tools.config_manager import delete_connection_configs
|
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.controllers.ProfileController import ProfileController
|
||||||
from core.models.BaseProfile import BaseProfile as Profile
|
from core.models.BaseProfile import BaseProfile as Profile
|
||||||
from core.models.BaseProfile import ProfileType, PROTOCOL_CHOICES
|
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.application_version_calls import get_application_by_id
|
||||||
from core.models.orm_calls.location_calls import get_profile_location_data_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.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:
|
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:
|
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")
|
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.subscription = original_subscription
|
||||||
new_profile_object.ticket = original_ticket
|
new_profile_object.ticket = original_ticket
|
||||||
|
|
||||||
|
|
@ -76,7 +77,6 @@ def _mutate_one_profile_choice(
|
||||||
) -> Result:
|
) -> Result:
|
||||||
"""Mutates the profile object fo a single value, but doesn't save it. Returns it."""
|
"""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}.")
|
logger.info(f"Recieved profile_id {profile.id}, key {key}, and new_value {new_value}.")
|
||||||
|
|
||||||
if not key:
|
if not key:
|
||||||
|
|
@ -111,6 +111,10 @@ def _mutate_one_profile_choice(
|
||||||
|
|
||||||
# ============= BROWSER =============
|
# ============= BROWSER =============
|
||||||
elif key == '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)
|
profile.application_version = get_application_by_id(new_value)
|
||||||
|
|
||||||
# ============= PROTOCOL TYPE =============
|
# ============= PROTOCOL TYPE =============
|
||||||
|
|
@ -124,15 +128,10 @@ def _mutate_one_profile_choice(
|
||||||
|
|
||||||
# ============= LOCATION =============
|
# ============= LOCATION =============
|
||||||
elif key == "location":
|
elif key == "location":
|
||||||
new_location = get_profile_location_data_by_id(new_value)
|
changed_location = change_location(profile=profile, new_value=new_value)
|
||||||
pre_existing_protocol = profile.protocol
|
if not changed_location.valid:
|
||||||
if new_location.supports_protocol(pre_existing_protocol):
|
return changed_location.wrap("Couldn't edit the profile due to location change issues.")
|
||||||
profile.location = new_location
|
profile = changed_location.data
|
||||||
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
|
|
||||||
else:
|
else:
|
||||||
return Result(valid=False, message="Invalid Value to Edit", error_type=ResultError.INVALID_INPUT)
|
return Result(valid=False, message="Invalid Value to Edit", error_type=ResultError.INVALID_INPUT)
|
||||||
|
|
||||||
|
|
@ -162,7 +161,11 @@ def update_profile(
|
||||||
# -------------------------
|
# -------------------------
|
||||||
# LOOP UPDATE EACH
|
# 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}")
|
logger.info(f"Updating {each_category}")
|
||||||
|
|
||||||
each_update = _mutate_one_profile_choice(
|
each_update = _mutate_one_profile_choice(
|
||||||
|
|
@ -228,3 +231,25 @@ def change_protocol(profile: Profile, new_value: str) -> Result:
|
||||||
profile.connection.masked = False
|
profile.connection.masked = False
|
||||||
|
|
||||||
return Result(valid=True, data=profile)
|
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)
|
||||||
7
core/utils/dict_tools.py
Normal file
7
core/utils/dict_tools.py
Normal file
|
|
@ -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
|
||||||
|
|
||||||
Loading…
Reference in a new issue