From c92c55da7686d16a194bc0943ad3f5b370805e7c Mon Sep 17 00:00:00 2001 From: SimplifiedPrivacy Date: Sun, 15 Nov 2026 19:14:28 -0500 Subject: [PATCH] Change locations when node is down --- .../controllers/profile_state/data_filters.py | 3 +- core/models/DatabaseOperation.py | 1 + core/models/Result.py | 2 + core/models/manage/insert.py | 11 ++ core/models/manage/server_reply_tools.py | 6 +- .../location_evaluation.py | 2 +- core/services/networking/ports/port_change.py | 2 +- core/services/profiles/change_location.py | 100 ++++++++++++++++++ core/services/profiles/update_profile.py | 36 +++++-- 9 files changed, 151 insertions(+), 12 deletions(-) create mode 100644 core/services/profiles/change_location.py diff --git a/core/controllers/profile_state/data_filters.py b/core/controllers/profile_state/data_filters.py index 7bc4ba7..ee5585d 100644 --- a/core/controllers/profile_state/data_filters.py +++ b/core/controllers/profile_state/data_filters.py @@ -1,3 +1,4 @@ +from core.controllers.ProfileController import ProfileController from core.services.payment_phase.payment_state import PaymentData from core.models.BaseProfile import BaseProfile as Profile from core.models.orm_models.Plan import Plan @@ -67,7 +68,7 @@ def get_plans_for_profile(profile_id: int) -> Result: """ # Get profile: - profile = Profile.find_by_id(profile_id) + 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) diff --git a/core/models/DatabaseOperation.py b/core/models/DatabaseOperation.py index 2613c02..e2876da 100644 --- a/core/models/DatabaseOperation.py +++ b/core/models/DatabaseOperation.py @@ -14,6 +14,7 @@ class DBErrorType(Enum): MALFORMED_SQL = "malformed_sql_file" MISSING_SQL = "missing_sql_file" MISSING_DEPENDENCY = "missing_dependency" + MISSING_DATA = "missing_data" INTEGRITY_ERROR = "integrity_error" PERMISSION_ERROR = "permission_error" FILESYSTEM_FULL = "filesystem_full" diff --git a/core/models/Result.py b/core/models/Result.py index 3d95929..bdcad15 100644 --- a/core/models/Result.py +++ b/core/models/Result.py @@ -64,6 +64,7 @@ class ResultError(Enum): TOR_NEEDED = "tor_needed" API_DOWN = "api_down" NODE_ERROR = "node_error" + CHANGE_LOCATION = "change_location" NO_INTERNET = "no_internet" PORT = "port" RENEGOTIATION = "renegotiation" @@ -90,6 +91,7 @@ class Result(): created_by: Optional[str] = None caused_by: Optional['Result'] = None created_by: Optional[str] = field(default=None, init=False) + profile_id: Optional[int] = None def __post_init__(self): stack = inspect.stack() diff --git a/core/models/manage/insert.py b/core/models/manage/insert.py index 5e06023..364ad11 100644 --- a/core/models/manage/insert.py +++ b/core/models/manage/insert.py @@ -45,6 +45,15 @@ def insert_into_model(model_class: Type, all_data: dict | list, override=False) def _wrapped_insert(model_class: Type, data_list: dict | list, session: Session, override=False) -> DatabaseOperation: """Insert items. Doesn't manage session. It's managed by the wrapper safe_db_operation""" + if not data_list: + error_msg = f"Critical error with Insert: There's blank data_list for {model_class}." + logger.error(error_msg) + return DatabaseOperation( + valid=False, + error_type=DBErrorType.MISSING_DATA, + message=error_msg + ) + if override: logger.info(f"First, WIPING the pre-existing data for {model_class.__name__}. Are you sure you intended to completely delete the old data?") session.query(model_class).delete() @@ -53,6 +62,7 @@ def _wrapped_insert(model_class: Type, data_list: dict | list, session: Session, # Get valid field names upfront valid_fields = {col.name for col in model_class.__table__.columns} + logger.info(f"valid_fields are {valid_fields}") # Filter data proactively filtered_data_list = [] @@ -72,6 +82,7 @@ def _wrapped_insert(model_class: Type, data_list: dict | list, session: Session, try: for filtered_json in filtered_data_list: + logger.info(f"inserting {filtered_json}") instance = model_class(**filtered_json) session.add(instance) session.commit() diff --git a/core/models/manage/server_reply_tools.py b/core/models/manage/server_reply_tools.py index 1b2b7b6..4edde30 100644 --- a/core/models/manage/server_reply_tools.py +++ b/core/models/manage/server_reply_tools.py @@ -16,7 +16,7 @@ class ApiCall(Enum): # Translate Server-side to client-side errors in THIS CONTEXT, TRANSLATION_DICT = { ServerError.WRONG_LOCATION: ResultError.WRONG_LOCATION, - ServerError.NODE_ERROR: ResultError.WRONG_LOCATION, + ServerError.NODE_ERROR: ResultError.NODE_ERROR, ServerError.CRYPTO_NODE: ResultError.SERVER_SIDE, ServerError.INVALID: ResultError.INVALID_INPUT, ServerError.MISSING_DATA: ResultError.INVALID_INPUT, @@ -169,6 +169,10 @@ def api_call_and_extraction( # translate by enum error code: return translate_server_failure(server_reply) + # No desired type (but not return the whole object either): + if desired_type is None: + return Result(valid=True, data=server_reply) + logger.info(f"Checking for the desired data type of {desired_type}") if not hasattr(server_reply, desired_type): error_msg = "Developer Error: You're asking for a data type that isn't in the object!" diff --git a/core/services/networking/general_connection_tools/location_evaluation.py b/core/services/networking/general_connection_tools/location_evaluation.py index d93abe2..b92145f 100644 --- a/core/services/networking/general_connection_tools/location_evaluation.py +++ b/core/services/networking/general_connection_tools/location_evaluation.py @@ -102,7 +102,7 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs if location_up: return Result(valid=True, backoff_strategy=BackoffStrategy.RETRY_IMMEDIATE) else: - error_msg = f"The {location_name} node is currently down." + error_msg = f"The {location_name} node is currently down, as told to us by the official API. Do you want to switch this billing code's location?" return Result(valid=False, backoff_strategy=BackoffStrategy.NO_RETRY, error_type=ResultError.NODE_ERROR, message=error_msg) diff --git a/core/services/networking/ports/port_change.py b/core/services/networking/ports/port_change.py index ced63e9..0284952 100644 --- a/core/services/networking/ports/port_change.py +++ b/core/services/networking/ports/port_change.py @@ -10,7 +10,7 @@ from functools import partial def change_port_then_reconnect( profile: Profile, - profile_id: int # it's redundant, but it's for the reconnect's inputs + profile_id: int = None # it's redundant, but it's for the reconnect's inputs ) -> Result: """ Changes the Wireguard config port, diff --git a/core/services/profiles/change_location.py b/core/services/profiles/change_location.py new file mode 100644 index 0000000..713e79e --- /dev/null +++ b/core/services/profiles/change_location.py @@ -0,0 +1,100 @@ +from core.models.BaseProfile import BaseProfile as Profile +from core.models.manage.server_reply_tools import api_call_and_extraction, ApiCall +from core.models.enum_models import ProtocolChoice +from core.observers.ObserverStash import ObserverStash +from core.errors.logger import logger +from core.models.Result import Result, ResultError +from core.Constants import Constants + +from typing import Optional + +def register_location_change( + profile: Profile, + new_location_id: int, + new_protocol: ProtocolChoice +) -> Result: + """Make a POST request to change the location for the given profile.""" + + if not profile.subscription or not profile.subscription.billing_code: + return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message="Can't change location without a subscription.") + + billing_code = profile.subscription.billing_code + + payload = { + "location_id": new_location_id, + "protocol": new_protocol + } + + url = f'{Constants.SP_BASE_URL}/v2/switch_location' + + observer_stash = ObserverStash() + logger.info("Sending location change to API") + + result = api_call_and_extraction( + desired_type=None, + method=ApiCall.POST, + url=url, + connection_observer=observer_stash.connection_observer, + payload=payload, + billing_code=billing_code, + return_server_reply=False + ) + + logger.info(f"API result: {result}") + + if not result.valid: + error_msg = "Was unable to switch location server-side" + logger.error(error_msg) + return result.wrap(error_msg) + + logger.info("Server-side location change was a success") + return Result(valid=True) + + +def change_location_server( + profile: Profile, + new_choices: dict, + force_non_ticket: Optional[bool] = False +) -> Result: + + # ------------------------- + # PRE-REQS + # ------------------------- + new_location_id = new_choices.get("location") + new_protocol = new_choices.get("protocol") + + logger.info(f"Changing profile {profile.id} to location {new_location_id} and protocol {new_protocol}") + + if not new_location_id: + return Result(valid=False, error_type=ResultError.MISSING_DATA, message="Missing location to change location") + + if not new_protocol: + new_protocol = profile.protocol + logger.info(f"Using the same protocol {new_protocol}") + + # ------------------------- + # NO TICKET (UPDATE SERVER) + # ------------------------- + if force_non_ticket or not profile.which_ticket: + return register_location_change( + profile=profile, + new_location_id=new_location_id, + new_protocol=new_protocol + ) + + # ------------------------- + # TICKETS (UPDATE SERVER) + # ------------------------- + observer_stash = ObserverStash() + return respawn_profile( + profile=profile, + ticket_observer=observer_stash.ticket_observer, + connection_observer=observer_stash.connection_observer + ) + + + # if not server_side_changed.valid: + # return server_side_changed.wrap("server-side failed") + + +# return Result(valid=True) diff --git a/core/services/profiles/update_profile.py b/core/services/profiles/update_profile.py index a536fa1..22f13a5 100644 --- a/core/services/profiles/update_profile.py +++ b/core/services/profiles/update_profile.py @@ -1,3 +1,4 @@ +from core.services.profiles.change_location import change_location_server from core.observers.ObserverStash import ObserverStash from core.errors.logger import logger from core.models.Result import Result, ResultError @@ -17,6 +18,8 @@ from core.services.profiles.create_objects import create_new_profile_object from core.services.assassin.ticket_respawn import respawn_profile from core.utils.dict_tools import get_sorted_keys +from typing import Optional + def finally_save_it(profile: Profile) -> Result: # ------------------------- # SAVE ENTIRE THING @@ -75,7 +78,8 @@ def mutate_profile_object_type(profile: Profile, new_choices: dict) -> Result: def _mutate_one_profile_choice( profile: Profile, key: str, - new_value: str + new_value: str, + keep_location: bool ) -> Result: """Mutates the profile object fo a single value, but doesn't save it. Returns it.""" @@ -130,7 +134,7 @@ def _mutate_one_profile_choice( # ============= LOCATION ============= elif key == "location": - changed_location = change_location(profile=profile, new_value=new_value) + changed_location = change_location(profile=profile, new_value=new_value, keep_location=keep_location) if not changed_location.valid: return changed_location.wrap("Couldn't edit the profile due to location change issues.") profile = changed_location.data @@ -143,7 +147,8 @@ def _mutate_one_profile_choice( def update_profile( profile_id: int, - new_choices: dict + new_choices: dict, + server_location_change: Optional[bool] = False ) -> Result: # ------------------------- @@ -154,6 +159,16 @@ def update_profile( error_msg = f"Invalid profile id of {profile_id}" return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) + # ------------------------- + # SERVER-SIDE LOCATION CHANGE + # ------------------------- + if server_location_change and "location" in new_choices: + logger.info("Triggering change server location.") + changed = change_location_server(profile=profile, new_choices=new_choices, force_non_ticket=True) + if not changed.valid: + return changed.wrap("Couldn't change server-side") + logger.info("Completed location change server-side") + # ------------------------- # TYPE CHANGE (requires object swap) # ------------------------- @@ -173,7 +188,8 @@ def update_profile( each_update = _mutate_one_profile_choice( profile=profile, key=each_category, - new_value=each_value + new_value=each_value, + keep_location=server_location_change ) if not each_update.valid: return each_update.wrap(f"Category {each_category} choice failed to update.") @@ -234,7 +250,7 @@ def change_protocol(profile: Profile, new_value: str) -> Result: return Result(valid=True, data=profile) -def change_location(profile: Profile, new_value: int) -> Result: +def change_location(profile: Profile, new_value: int, keep_location: bool) -> Result: """ Change a profile's location for the in memory object, and return it. Changes the connection configs and respawns the ticket. But this does NOT save the profile to disk. @@ -280,9 +296,13 @@ def change_location(profile: Profile, new_value: int) -> Result: # REGARDLESS OF TICKET, SUB & LOCATION #################################### - # Subscription gets wiped on a location change, and is outside location ORM - profile.subscription = None - profile.ticket = None + if not keep_location: + logger.info("Wiping the sub") + # Subscription gets wiped on a location change, and is outside location ORM + profile.subscription = None + profile.ticket = None + else: + logger.info("Keeping the same sub despite location change.") # finally set location: profile.location = new_location